text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file libuobject/main.cc
#include <libport/cerrno>
#include <libport/cstdio>
#include <libport/debug.hh>
#include <libport/unistd.h>
#include <iostream>
#include <list>
#include <sstream>
#include <libport/debug.hh>
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <libport/lexical-cast.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <urbi/package-info.hh>
#include <urbi/uexternal.hh>
#include <urbi/umain.hh>
#include <urbi/umessage.hh>
#include <urbi/uobject.hh>
#include <urbi/urbi-root.hh>
#include <urbi/usyncclient.hh>
#include <libuobject/remote-ucontext-impl.hh>
using libport::program_name;
GD_CATEGORY(urbi-launch);
namespace urbi
{
static impl::RemoteUContextImpl* defaultContext;
static
UCallbackAction
debug(const UMessage& msg)
{
GD_SWARN("unexpected message: " << msg);
return URBI_CONTINUE;
}
static
UCallbackAction
endProgram(const UMessage& msg)
{
GD_SWARN("got a disconnection message: " << msg);
exit(0);
return URBI_CONTINUE; //stupid gcc
}
static
void
usage()
{
std::cout <<
"usage:\n" << libport::program_name() << " [OPTION]...\n"
"\n"
"Options:\n"
" -b, --buffer SIZE input buffer size"
<< " [" << UAbstractClient::URBI_BUFLEN << "]\n"
" -h, --help display this message and exit\n"
" -H, --host ADDR server host name"
<< " [" << UClient::default_host() << "]\n"
" --server put remote in server mode\n"
" --no-sync-client Use UClient instead of USyncClient\n"
" -p, --port PORT tcp port URBI will listen to"
<< " [" << UAbstractClient::URBI_PORT << "]\n"
" -r, --port-file FILE file containing the port to listen to\n"
" -V, --version print version information and exit\n"
" -d, --disconnect exit program if disconnected(defaults)\n"
" -s, --stay-alive do not exit program if disconnected\n"
" --describe describe loaded UObjects and exit\n"
" --describe-file FILE write the list of present UObjects to FILE\n"
<< libport::exit (EX_OK);
}
static
void
version()
{
std::cout << urbi::package_info() << std::endl
<< libport::exit (EX_OK);
}
typedef std::vector<std::string> files_type;
int
initialize(const std::string& host, int port, size_t buflen,
bool exitOnDisconnect, bool server, const files_type& files,
bool useSyncClient)
{
std::cerr << program_name()
<< ": " << urbi::package_info() << std::endl
<< program_name()
<< ": Remote Component Running on "
<< host << " " << port << std::endl;
if (useSyncClient)
{
USyncClient::options o;
o.server(server);
new USyncClient(host, port, buflen, o);
}
else
{
std::cerr << "#WARNING: the no-sync-client mode is dangerous.\n"
"Any attempt to use synchronous operation will crash your program."
<< std::endl;
UClient::options o;
o.server(server);
setDefaultClient(new UClient(host, port, buflen, o));
}
if (exitOnDisconnect)
{
if (!getDefaultClient() || getDefaultClient()->error())
std::cerr << "ERROR: failed to connect, exiting..." << std::endl
<< libport::exit(1);
getDefaultClient()->setClientErrorCallback(callback(&endProgram));
}
if (!getDefaultClient() || getDefaultClient()->error())
return 1;
#ifdef LIBURBIDEBUG
getDefaultClient()->setWildcardCallback(callback(&debug));
#else
getDefaultClient()->setErrorCallback(callback(&debug));
#endif
// Wait for client to be connected if in server mode.
while (getDefaultClient()
&& !getDefaultClient()->error()
&& !getDefaultClient()->isConnected())
usleep(20000);
defaultContext = new impl::RemoteUContextImpl(
(USyncClient*)dynamic_cast<UClient*>(getDefaultClient()));
// Waiting for connectionID.
while (getDefaultClient()
&& getDefaultClient()->connectionID() == "")
usleep(5000);
// Initialize in the correct thread.
getDefaultClient()->notifyCallbacks(UMessage(*getDefaultClient(), 0,
externalModuleTag.c_str(),
("[" + boost::lexical_cast<std::string>(UEM_INIT)
+ "]").c_str()
));
// Load initialization files.
foreach (const std::string& file, files)
getDefaultClient()->sendFile(file);
return 0;
}
namespace
{
static
void
argument_with_option(const char* longopt,
char shortopt,
const std::string& val)
{
std::cerr
<< program_name()
<< ": warning: arguments without options are deprecated"
<< std::endl
<< "use `-" << shortopt << ' ' << val << '\''
<< " or `--" << longopt << ' ' << val << "' instead"
<< std::endl
<< "Try `" << program_name() << " --help' for more information."
<< std::endl;
}
}
URBI_SDK_API int
main(const libport::cli_args_type& args, UrbiRoot&, bool block, bool)
{
GD_INIT();
std::string host = UClient::default_host();
bool exitOnDisconnect = true;
int port = UAbstractClient::URBI_PORT;
bool server = false;
bool useSyncClient = true;
bool describeMode = false;
std::string describeFile;
size_t buflen = UAbstractClient::URBI_BUFLEN;
// Files to load
files_type files;
// The number of the next (non-option) argument.
unsigned argp = 1;
for (unsigned i = 1; i < args.size(); ++i)
{
const std::string& arg = args[i];
if (arg == "--buffer" || arg == "-b")
buflen = libport::convert_argument<size_t>(args, i++);
else if (arg == "--disconnect" || arg == "-d")
exitOnDisconnect = true;
else if (arg == "--file" || arg == "-f")
files.push_back(libport::convert_argument<const char*>(args, i++));
else if (arg == "--stay-alive" || arg == "-s")
exitOnDisconnect = false;
else if (arg == "--help" || arg == "-h")
usage();
else if (arg == "--host" || arg == "-H")
host = libport::convert_argument<std::string>(args, i++);
else if (arg == "--no-sync-client")
useSyncClient = false;
else if (arg == "--port" || arg == "-p")
port = libport::convert_argument<unsigned>(args, i++);
else if (arg == "--port-file" || arg == "-r")
port =
(libport::file_contents_get<int>
(libport::convert_argument<const char*>(args, i++)));
else if (arg == "--server")
server = true;
// FIXME: Remove -v some day.
else if (arg == "--version" || arg == "-V" || arg == "-v")
version();
else if (arg == "--describe")
describeMode = true;
else if (arg == "--describe-file")
describeFile = libport::convert_argument<const char*>(args, i++);
else if (arg[0] == '-')
libport::invalid_option(arg);
else
// A genuine argument.
switch (argp++)
{
case 1:
argument_with_option("host", 'H', args[i]);
host = args[i];
break;
case 2:
argument_with_option("port", 'p', args[i]);
port = libport::convert_argument<unsigned>("port", args[i]);
break;
default:
std::cerr << "unexpected argument: " << arg << std::endl
<< libport::exit(EX_USAGE);
}
}
if (describeMode)
{
foreach(baseURBIStarter* s, baseURBIStarter::list())
std::cout << s->name << std::endl;
foreach(baseURBIStarterHub* s, baseURBIStarterHub::list())
std::cout << s->name << std::endl;
return 0;
}
if (!describeFile.empty())
{
std::ofstream of(describeFile.c_str());
foreach(baseURBIStarter* s, baseURBIStarter::list())
of << s->name << std::endl;
foreach(baseURBIStarterHub* s, baseURBIStarterHub::list())
of << s->name << std::endl;
}
initialize(host, port, buflen, exitOnDisconnect, server, files,
useSyncClient);
if (block)
while (true)
usleep(30000000);
return 0;
}
}
<commit_msg>umain: use GD.<commit_after>/*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file libuobject/main.cc
#include <libport/cerrno>
#include <libport/cstdio>
#include <libport/debug.hh>
#include <libport/unistd.h>
#include <iostream>
#include <list>
#include <sstream>
#include <libport/debug.hh>
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <libport/lexical-cast.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <urbi/package-info.hh>
#include <urbi/uexternal.hh>
#include <urbi/umain.hh>
#include <urbi/umessage.hh>
#include <urbi/uobject.hh>
#include <urbi/urbi-root.hh>
#include <urbi/usyncclient.hh>
#include <libuobject/remote-ucontext-impl.hh>
using libport::program_name;
GD_CATEGORY(urbi-launch);
namespace urbi
{
static impl::RemoteUContextImpl* defaultContext;
static
UCallbackAction
debug(const UMessage& msg)
{
GD_SWARN("unexpected message: " << msg);
return URBI_CONTINUE;
}
static
UCallbackAction
endProgram(const UMessage& msg)
{
GD_SWARN("got a disconnection message: " << msg);
exit(0);
return URBI_CONTINUE; //stupid gcc
}
static
void
usage()
{
std::cout <<
"usage:\n" << libport::program_name() << " [OPTION]...\n"
"\n"
"Options:\n"
" -b, --buffer SIZE input buffer size"
<< " [" << UAbstractClient::URBI_BUFLEN << "]\n"
" -h, --help display this message and exit\n"
" -H, --host ADDR server host name"
<< " [" << UClient::default_host() << "]\n"
" --server put remote in server mode\n"
" --no-sync-client Use UClient instead of USyncClient\n"
" -p, --port PORT tcp port URBI will listen to"
<< " [" << UAbstractClient::URBI_PORT << "]\n"
" -r, --port-file FILE file containing the port to listen to\n"
" -V, --version print version information and exit\n"
" -d, --disconnect exit program if disconnected(defaults)\n"
" -s, --stay-alive do not exit program if disconnected\n"
" --describe describe loaded UObjects and exit\n"
" --describe-file FILE write the list of present UObjects to FILE\n"
<< libport::exit (EX_OK);
}
static
void
version()
{
std::cout << urbi::package_info() << std::endl
<< libport::exit (EX_OK);
}
typedef std::vector<std::string> files_type;
int
initialize(const std::string& host, int port, size_t buflen,
bool exitOnDisconnect, bool server, const files_type& files,
bool useSyncClient)
{
GD_FINFO_TRACE("this is %s", program_name());
GD_SINFO_TRACE(urbi::package_info());
GD_FINFO_TRACE("remote component running on %s:%s", host, port);
if (useSyncClient)
{
USyncClient::options o;
o.server(server);
new USyncClient(host, port, buflen, o);
}
else
{
GD_WARN("the no-sync-client mode is dangerous. "
"Any attempt to use synchronous operation will crash"
" your program.");
UClient::options o;
o.server(server);
setDefaultClient(new UClient(host, port, buflen, o));
}
if (exitOnDisconnect)
{
if (!getDefaultClient() || getDefaultClient()->error())
std::cerr << "ERROR: failed to connect, exiting..." << std::endl
<< libport::exit(1);
getDefaultClient()->setClientErrorCallback(callback(&endProgram));
}
if (!getDefaultClient() || getDefaultClient()->error())
return 1;
#ifdef LIBURBIDEBUG
getDefaultClient()->setWildcardCallback(callback(&debug));
#else
getDefaultClient()->setErrorCallback(callback(&debug));
#endif
// Wait for client to be connected if in server mode.
while (getDefaultClient()
&& !getDefaultClient()->error()
&& !getDefaultClient()->isConnected())
usleep(20000);
defaultContext = new impl::RemoteUContextImpl(
(USyncClient*)dynamic_cast<UClient*>(getDefaultClient()));
// Waiting for connectionID.
while (getDefaultClient()
&& getDefaultClient()->connectionID() == "")
usleep(5000);
// Initialize in the correct thread.
getDefaultClient()->notifyCallbacks(UMessage(*getDefaultClient(), 0,
externalModuleTag.c_str(),
("[" + boost::lexical_cast<std::string>(UEM_INIT)
+ "]").c_str()
));
// Load initialization files.
foreach (const std::string& file, files)
getDefaultClient()->sendFile(file);
return 0;
}
namespace
{
static
void
argument_with_option(const char* longopt,
char shortopt,
const std::string& val)
{
std::cerr
<< program_name()
<< ": warning: arguments without options are deprecated"
<< std::endl
<< "use `-" << shortopt << ' ' << val << '\''
<< " or `--" << longopt << ' ' << val << "' instead"
<< std::endl
<< "Try `" << program_name() << " --help' for more information."
<< std::endl;
}
}
URBI_SDK_API int
main(const libport::cli_args_type& args, UrbiRoot&, bool block, bool)
{
GD_INIT();
std::string host = UClient::default_host();
bool exitOnDisconnect = true;
int port = UAbstractClient::URBI_PORT;
bool server = false;
bool useSyncClient = true;
bool describeMode = false;
std::string describeFile;
size_t buflen = UAbstractClient::URBI_BUFLEN;
// Files to load
files_type files;
// The number of the next (non-option) argument.
unsigned argp = 1;
for (unsigned i = 1; i < args.size(); ++i)
{
const std::string& arg = args[i];
if (arg == "--buffer" || arg == "-b")
buflen = libport::convert_argument<size_t>(args, i++);
else if (arg == "--disconnect" || arg == "-d")
exitOnDisconnect = true;
else if (arg == "--file" || arg == "-f")
files.push_back(libport::convert_argument<const char*>(args, i++));
else if (arg == "--stay-alive" || arg == "-s")
exitOnDisconnect = false;
else if (arg == "--help" || arg == "-h")
usage();
else if (arg == "--host" || arg == "-H")
host = libport::convert_argument<std::string>(args, i++);
else if (arg == "--no-sync-client")
useSyncClient = false;
else if (arg == "--port" || arg == "-p")
port = libport::convert_argument<unsigned>(args, i++);
else if (arg == "--port-file" || arg == "-r")
port =
(libport::file_contents_get<int>
(libport::convert_argument<const char*>(args, i++)));
else if (arg == "--server")
server = true;
// FIXME: Remove -v some day.
else if (arg == "--version" || arg == "-V" || arg == "-v")
version();
else if (arg == "--describe")
describeMode = true;
else if (arg == "--describe-file")
describeFile = libport::convert_argument<const char*>(args, i++);
else if (arg[0] == '-')
libport::invalid_option(arg);
else
// A genuine argument.
switch (argp++)
{
case 1:
argument_with_option("host", 'H', args[i]);
host = args[i];
break;
case 2:
argument_with_option("port", 'p', args[i]);
port = libport::convert_argument<unsigned>("port", args[i]);
break;
default:
std::cerr << "unexpected argument: " << arg << std::endl
<< libport::exit(EX_USAGE);
}
}
if (describeMode)
{
foreach(baseURBIStarter* s, baseURBIStarter::list())
std::cout << s->name << std::endl;
foreach(baseURBIStarterHub* s, baseURBIStarterHub::list())
std::cout << s->name << std::endl;
return 0;
}
if (!describeFile.empty())
{
std::ofstream of(describeFile.c_str());
foreach(baseURBIStarter* s, baseURBIStarter::list())
of << s->name << std::endl;
foreach(baseURBIStarterHub* s, baseURBIStarterHub::list())
of << s->name << std::endl;
}
initialize(host, port, buflen, exitOnDisconnect, server, files,
useSyncClient);
if (block)
while (true)
usleep(30000000);
return 0;
}
}
<|endoftext|> |
<commit_before>/**
* @file conv_layer.hpp
* @author Marcus Edel
*
* Definition of the ConvLayer class.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_CONV_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_CONV_LAYER_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/layer/layer_traits.hpp>
#include <mlpack/methods/ann/convolution_rules/border_modes.hpp>
#include <mlpack/methods/ann/convolution_rules/naive_convolution.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* Implementation of the ConvLayer class. The ConvLayer class represents a
* single layer of a neural network.
*
* @tparam ForwardConvolutionRule Convolution to perform forward process.
* @tparam BackwardConvolutionRule Convolution to perform backward process.
* @tparam GradientConvolutionRule Convolution to calculate gradient.
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename ForwardConvolutionRule = NaiveConvolution<ValidConvolution>,
typename BackwardConvolutionRule = NaiveConvolution<FullConvolution>,
typename GradientConvolutionRule = NaiveConvolution<ValidConvolution>,
typename InputDataType = arma::cube,
typename OutputDataType = arma::cube
>
class ConvLayer
{
public:
/**
* Create the ConvLayer object using the specified number of input maps,
* output maps, filter size, stride and padding parameter.
*
* @param inMaps The number of input maps.
* @param outMaps The number of output maps.
* @param wfilter Width of the filter/kernel.
* @param wfilter Height of the filter/kernel.
* @param xStride Stride of filter application in the x direction.
* @param yStride Stride of filter application in the y direction.
* @param wPad Spatial padding width of the input.
* @param hPad Spatial padding height of the input.
*/
ConvLayer(const size_t inMaps,
const size_t outMaps,
const size_t wfilter,
const size_t hfilter,
const size_t xStride = 1,
const size_t yStride = 1,
const size_t wPad = 0,
const size_t hPad = 0) :
wfilter(wfilter),
hfilter(hfilter),
inMaps(inMaps),
outMaps(outMaps),
xStride(xStride),
yStride(yStride),
wPad(wPad),
hPad(hPad)
{
weights.set_size(wfilter, hfilter, inMaps * outMaps);
}
ConvLayer(ConvLayer &&layer) noexcept
{
*this = std::move(layer);
}
ConvLayer& operator=(ConvLayer &&layer) noexcept
{
wfilter = layer.wfilter;
hfilter = layer.hfilter;
inMaps = layer.inMaps;
outMaps = layer.outMaps;
xStride = layer.xStride;
yStride = layer.yStride;
wPad = layer.wPad;
hPad = layer.hPad;
weights.swap(layer.weights);
return *this;
}
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Cube<eT>& input, arma::Cube<eT>& output)
{
const size_t wConv = ConvOutSize(input.n_rows, wfilter, xStride, wPad);
const size_t hConv = ConvOutSize(input.n_cols, hfilter, yStride, hPad);
output = arma::zeros<arma::Cube<eT> >(wConv, hConv, outMaps);
for (size_t outMap = 0, outMapIdx = 0; outMap < outMaps; outMap++)
{
for (size_t inMap = 0; inMap < inMaps; inMap++, outMapIdx++)
{
arma::Mat<eT> convOutput;
ForwardConvolutionRule::Convolution(input.slice(inMap),
weights.slice(outMap), convOutput);
output.slice(outMap) += convOutput;
}
}
}
/**
* Ordinary feed backward pass of a neural network, calculating the function
* f(x) by propagating x backwards through f. Using the results from the feed
* forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Cube<eT>& /* unused */,
const arma::Cube<eT>& gy,
arma::Cube<eT>& g)
{
g = arma::zeros<arma::Cube<eT> >(inputParameter.n_rows,
inputParameter.n_cols,
inputParameter.n_slices);
for (size_t outMap = 0, outMapIdx = 0; outMap < inMaps; outMap++)
{
for (size_t inMap = 0; inMap < outMaps; inMap++, outMapIdx++)
{
arma::Mat<eT> rotatedFilter;
Rotate180(weights.slice(outMap * outMaps + inMap), rotatedFilter);
arma::Mat<eT> output;
BackwardConvolutionRule::Convolution(gy.slice(inMap), rotatedFilter,
output);
g.slice(outMap) += output;
}
}
}
/*
* Calculate the gradient using the output delta and the input activation.
*
* @param d The calculated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Gradient(const arma::Cube<eT>& d, arma::Cube<eT>& g)
{
g = arma::zeros<arma::Cube<eT> >(weights.n_rows, weights.n_cols,
weights.n_slices);
for (size_t outMap = 0; outMap < outMaps; outMap++)
{
for (size_t inMap = 0, s = outMap; inMap < inMaps; inMap++, s += outMaps)
{
arma::Cube<eT> inputSlices = inputParameter.slices(inMap, inMap);
arma::Cube<eT> deltaSlices = d.slices(outMap, outMap);
arma::Cube<eT> output;
GradientConvolutionRule::Convolution(inputSlices, deltaSlices, output);
for (size_t i = 0; i < output.n_slices; i++)
g.slice(s) += output.slice(i);
}
}
}
/**
* Serialize the layer
*/
template<typename Archive>
void Serialize(Archive& ar, const unsigned int /* version */)
{
ar & data::CreateNVP(weights, "weights");
}
//! Get the weights.
OutputDataType& Weights() const { return weights; }
//! Modify the weights.
OutputDataType& Weights() { return weights; }
//! Get the input parameter.
InputDataType& InputParameter() const { return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType& OutputParameter() const { return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
OutputDataType& Delta() const { return delta; }
//! Modify the delta.
OutputDataType& Delta() { return delta; }
//! Get the gradient.
OutputDataType& Gradient() const { return gradient; }
//! Modify the gradient.
OutputDataType& Gradient() { return gradient; }
private:
/*
* Rotates a 3rd-order tesor counterclockwise by 180 degrees.
*
* @param input The input data to be rotated.
* @param output The rotated output.
*/
template<typename eT>
void Rotate180(const arma::Cube<eT>& input, arma::Cube<eT>& output)
{
output = arma::Cube<eT>(input.n_rows, input.n_cols, input.n_slices);
// * left-right flip, up-down flip */
for (size_t s = 0; s < output.n_slices; s++)
output.slice(s) = arma::fliplr(arma::flipud(input.slice(s)));
}
/*
* Rotates a dense matrix counterclockwise by 180 degrees.
*
* @param input The input data to be rotated.
* @param output The rotated output.
*/
template<typename eT>
void Rotate180(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
// * left-right flip, up-down flip */
output = arma::fliplr(arma::flipud(input));
}
/*
* Return the convolution output size.
*
* @param size The size of the input (row or column).
* @param k The size of the filter (width or height).
* @param s The stride size (x or y direction).
* @param p The size of the padding (width or height).
* @return The convolution output size.
*/
size_t ConvOutSize(const size_t size,
const size_t k,
const size_t s,
const size_t p)
{
return std::floor(size + p * 2 - k) / s + 1;
}
//! Locally-stored filter/kernel width.
size_t wfilter;
//! Locally-stored filter/kernel height.
size_t hfilter;
//! Locally-stored number of input maps.
size_t inMaps;
//! Locally-stored number of output maps.
size_t outMaps;
//! Locally-stored stride of the filter in x-direction.
size_t xStride;
//! Locally-stored stride of the filter in y-direction.
size_t yStride;
//! Locally-stored padding width.
size_t wPad;
//! Locally-stored padding height.
size_t hPad;
//! Locally-stored weight object.
OutputDataType weights;
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored gradient object.
OutputDataType gradient;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
}; // class ConvLayer
//! Layer traits for the convolution layer.
template<
typename ForwardConvolutionRule,
typename BackwardConvolutionRule,
typename GradientConvolutionRule,
typename InputDataType,
typename OutputDataType
>
class LayerTraits<ConvLayer<ForwardConvolutionRule,
BackwardConvolutionRule,
GradientConvolutionRule,
InputDataType,
OutputDataType> >
{
public:
static const bool IsBinary = false;
static const bool IsOutputLayer = false;
static const bool IsBiasLayer = false;
static const bool IsLSTMLayer = false;
static const bool IsConnection = true;
};
} // namespace ann
} // namespace mlpack
#endif
<commit_msg>format codes<commit_after>/**
* @file conv_layer.hpp
* @author Marcus Edel
*
* Definition of the ConvLayer class.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_CONV_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_CONV_LAYER_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/layer/layer_traits.hpp>
#include <mlpack/methods/ann/convolution_rules/border_modes.hpp>
#include <mlpack/methods/ann/convolution_rules/naive_convolution.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* Implementation of the ConvLayer class. The ConvLayer class represents a
* single layer of a neural network.
*
* @tparam ForwardConvolutionRule Convolution to perform forward process.
* @tparam BackwardConvolutionRule Convolution to perform backward process.
* @tparam GradientConvolutionRule Convolution to calculate gradient.
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename ForwardConvolutionRule = NaiveConvolution<ValidConvolution>,
typename BackwardConvolutionRule = NaiveConvolution<FullConvolution>,
typename GradientConvolutionRule = NaiveConvolution<ValidConvolution>,
typename InputDataType = arma::cube,
typename OutputDataType = arma::cube
>
class ConvLayer
{
public:
/**
* Create the ConvLayer object using the specified number of input maps,
* output maps, filter size, stride and padding parameter.
*
* @param inMaps The number of input maps.
* @param outMaps The number of output maps.
* @param wfilter Width of the filter/kernel.
* @param wfilter Height of the filter/kernel.
* @param xStride Stride of filter application in the x direction.
* @param yStride Stride of filter application in the y direction.
* @param wPad Spatial padding width of the input.
* @param hPad Spatial padding height of the input.
*/
ConvLayer(const size_t inMaps,
const size_t outMaps,
const size_t wfilter,
const size_t hfilter,
const size_t xStride = 1,
const size_t yStride = 1,
const size_t wPad = 0,
const size_t hPad = 0) :
wfilter(wfilter),
hfilter(hfilter),
inMaps(inMaps),
outMaps(outMaps),
xStride(xStride),
yStride(yStride),
wPad(wPad),
hPad(hPad)
{
weights.set_size(wfilter, hfilter, inMaps * outMaps);
}
ConvLayer(ConvLayer &&layer) noexcept
{
*this = std::move(layer);
}
ConvLayer& operator=(ConvLayer &&layer) noexcept
{
wfilter = layer.wfilter;
hfilter = layer.hfilter;
inMaps = layer.inMaps;
outMaps = layer.outMaps;
xStride = layer.xStride;
yStride = layer.yStride;
wPad = layer.wPad;
hPad = layer.hPad;
weights.swap(layer.weights);
return *this;
}
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Cube<eT>& input, arma::Cube<eT>& output)
{
const size_t wConv = ConvOutSize(input.n_rows, wfilter, xStride, wPad);
const size_t hConv = ConvOutSize(input.n_cols, hfilter, yStride, hPad);
output = arma::zeros<arma::Cube<eT> >(wConv, hConv, outMaps);
for (size_t outMap = 0, outMapIdx = 0; outMap < outMaps; outMap++)
{
for (size_t inMap = 0; inMap < inMaps; inMap++, outMapIdx++)
{
arma::Mat<eT> convOutput;
ForwardConvolutionRule::Convolution(input.slice(inMap),
weights.slice(outMap), convOutput);
output.slice(outMap) += convOutput;
}
}
}
/**
* Ordinary feed backward pass of a neural network, calculating the function
* f(x) by propagating x backwards through f. Using the results from the feed
* forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Cube<eT>& /* unused */,
const arma::Cube<eT>& gy,
arma::Cube<eT>& g)
{
g = arma::zeros<arma::Cube<eT> >(inputParameter.n_rows,
inputParameter.n_cols,
inputParameter.n_slices);
for (size_t outMap = 0, outMapIdx = 0; outMap < inMaps; outMap++)
{
for (size_t inMap = 0; inMap < outMaps; inMap++, outMapIdx++)
{
arma::Mat<eT> rotatedFilter;
Rotate180(weights.slice(outMap * outMaps + inMap), rotatedFilter);
arma::Mat<eT> output;
BackwardConvolutionRule::Convolution(gy.slice(inMap), rotatedFilter,
output);
g.slice(outMap) += output;
}
}
}
/*
* Calculate the gradient using the output delta and the input activation.
*
* @param d The calculated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Gradient(const arma::Cube<eT>& d, arma::Cube<eT>& g)
{
g = arma::zeros<arma::Cube<eT> >(weights.n_rows, weights.n_cols,
weights.n_slices);
for (size_t outMap = 0; outMap < outMaps; outMap++)
{
for (size_t inMap = 0, s = outMap; inMap < inMaps; inMap++, s += outMaps)
{
arma::Cube<eT> inputSlices = inputParameter.slices(inMap, inMap);
arma::Cube<eT> deltaSlices = d.slices(outMap, outMap);
arma::Cube<eT> output;
GradientConvolutionRule::Convolution(inputSlices, deltaSlices, output);
for (size_t i = 0; i < output.n_slices; i++)
g.slice(s) += output.slice(i);
}
}
}
//! Get the weights.
OutputDataType& Weights() const { return weights; }
//! Modify the weights.
OutputDataType& Weights() { return weights; }
//! Get the input parameter.
InputDataType& InputParameter() const { return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType& OutputParameter() const { return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
OutputDataType& Delta() const { return delta; }
//! Modify the delta.
OutputDataType& Delta() { return delta; }
//! Get the gradient.
OutputDataType& Gradient() const { return gradient; }
//! Modify the gradient.
OutputDataType& Gradient() { return gradient; }
/**
* Serialize the layer
*/
template<typename Archive>
void Serialize(Archive& ar, const unsigned int /* version */)
{
ar & data::CreateNVP(weights, "weights");
}
private:
/*
* Rotates a 3rd-order tesor counterclockwise by 180 degrees.
*
* @param input The input data to be rotated.
* @param output The rotated output.
*/
template<typename eT>
void Rotate180(const arma::Cube<eT>& input, arma::Cube<eT>& output)
{
output = arma::Cube<eT>(input.n_rows, input.n_cols, input.n_slices);
// * left-right flip, up-down flip */
for (size_t s = 0; s < output.n_slices; s++)
output.slice(s) = arma::fliplr(arma::flipud(input.slice(s)));
}
/*
* Rotates a dense matrix counterclockwise by 180 degrees.
*
* @param input The input data to be rotated.
* @param output The rotated output.
*/
template<typename eT>
void Rotate180(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
// * left-right flip, up-down flip */
output = arma::fliplr(arma::flipud(input));
}
/*
* Return the convolution output size.
*
* @param size The size of the input (row or column).
* @param k The size of the filter (width or height).
* @param s The stride size (x or y direction).
* @param p The size of the padding (width or height).
* @return The convolution output size.
*/
size_t ConvOutSize(const size_t size,
const size_t k,
const size_t s,
const size_t p)
{
return std::floor(size + p * 2 - k) / s + 1;
}
//! Locally-stored filter/kernel width.
size_t wfilter;
//! Locally-stored filter/kernel height.
size_t hfilter;
//! Locally-stored number of input maps.
size_t inMaps;
//! Locally-stored number of output maps.
size_t outMaps;
//! Locally-stored stride of the filter in x-direction.
size_t xStride;
//! Locally-stored stride of the filter in y-direction.
size_t yStride;
//! Locally-stored padding width.
size_t wPad;
//! Locally-stored padding height.
size_t hPad;
//! Locally-stored weight object.
OutputDataType weights;
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored gradient object.
OutputDataType gradient;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
}; // class ConvLayer
//! Layer traits for the convolution layer.
template<
typename ForwardConvolutionRule,
typename BackwardConvolutionRule,
typename GradientConvolutionRule,
typename InputDataType,
typename OutputDataType
>
class LayerTraits<ConvLayer<ForwardConvolutionRule,
BackwardConvolutionRule,
GradientConvolutionRule,
InputDataType,
OutputDataType> >
{
public:
static const bool IsBinary = false;
static const bool IsOutputLayer = false;
static const bool IsBiasLayer = false;
static const bool IsLSTMLayer = false;
static const bool IsConnection = true;
};
} // namespace ann
} // namespace mlpack
#endif
<|endoftext|> |
<commit_before>#include <memory>
#include <zmqpp/message.hpp>
#include <boost/property_tree/ptree.hpp>
#include <tools/log.hpp>
#include <zmqpp/context.hpp>
#include <fcntl.h>
#include "pifacedigital.hpp"
#include "zmqpp/actor.hpp"
#include "../../../libpifacedigital/src/pifacedigital.h"
#include "../../../libmcp23s17/src/mcp23s17.h"
#include "tools/unixsyscall.hpp"
#include "exception/gpioexception.hpp"
/**
* pipe is pipe back to module manager.
* this function is called in its own thread.
*
* do signaling when ready
*/
extern "C" __attribute__((visibility("default"))) bool start_module(zmqpp::socket *pipe,
boost::property_tree::ptree cfg,
zmqpp::context &zmq_ctx)
{
PFGpioModule module(cfg, pipe, zmq_ctx);
std::cout << "Init ok (myname = " << cfg.get_child("name").data() << "... sending OK" << std::endl;
pipe->send(zmqpp::signal::ok);
module.run();
std::cout << "module PFGpio shutying down" << std::endl;
return true;
}
PFGpioModule::PFGpioModule(const boost::property_tree::ptree &config,
zmqpp::socket *module_manager_pipe,
zmqpp::context &ctx) :
pipe_(*module_manager_pipe),
config_(config),
is_running_(true),
ctx_(ctx),
bus_push_(ctx_, zmqpp::socket_type::push)
{
process_config(config);
pifacedigital_open(0);
bus_push_.connect("inproc://zmq-bus-pull");
for (auto &gpio : gpios_)
{
reactor_.add(gpio.sock_, std::bind(&PFGpioPin::handle_message, &gpio));
}
reactor_.add(pipe_, std::bind(&PFGpioModule::handle_pipe, this));
assert(pifacedigital_enable_interrupts() == 0);
std::string path_to_gpio = "/sys/class/gpio/gpio" + std::to_string(GPIO_INTERRUPT_PIN) + "/value";
interrupt_fd_ = open(path_to_gpio.c_str(), O_RDONLY | O_NONBLOCK);
assert(interrupt_fd_ > 0);
pifacedigital_read_reg(0x11, 0);//flush
first_ = true; // Ignore GPIO Initial Event
reactor_.add(interrupt_fd_, std::bind(&PFGpioModule::handle_interrupt, this), zmqpp::poller::poll_pri);
}
void PFGpioModule::run()
{
while (is_running_)
{
reactor_.poll(-1);
}
}
void PFGpioModule::handle_pipe()
{
zmqpp::signal s;
pipe_.receive(s, true);
if (s == zmqpp::signal::stop)
is_running_ = false;
}
void PFGpioModule::handle_interrupt()
{
// get interrupt state.
LOG() << "BOAP";
std::array<char, 64> buffer;
if (::read(interrupt_fd_, &buffer[0], buffer.size()) < 0)
throw (GpioException(UnixSyscall::getErrorString("read", errno)));
if (::lseek(interrupt_fd_, 0, SEEK_SET) < 0)
throw (GpioException(UnixSyscall::getErrorString("lseek", errno)));
if (first_)
{
first_ = false;
return;
}
uint8_t states = pifacedigital_read_reg(0x11, 0);
for (int i = 0; i < 8; ++i)
{
if (((states >> i) & 0x01) == 0)
{
// this pin triggered interrupt
// LOG() << "PIN " << i << " IS IN INTERRUPT MODE";
bus_push_.send(zmqpp::message() << "S_TEST" << (std::string("OMG INTERRUPT ON PIN " + std::to_string(i))));
// signal interrupt if needed (ie the pin is registered in config
std::string gpio_name;
if (get_input_pin_name(gpio_name, i))
{
bus_push_.send(zmqpp::message() << std::string ("S_INT:" + gpio_name));
}
}
}
// states = pifacedigital_read_reg(INPUT, 0);
// for (int i = 0; i < 8; ++i)
// {
// LOG() << "PIN " << i << " HAS VALUE: " << ((states >> i) & 0x01);
// }
// pifacedigital_read_reg(0x11, 0); // flush
}
bool PFGpioModule::get_input_pin_name(std::string &dest, int idx)
{
for (auto &gpio : gpios_)
{
if (gpio.gpio_no_ == idx && gpio.direction_ == PFGpioPin::Direction::In)
{
dest = gpio.name_;
return true;
}
}
return false;
}
void PFGpioModule::process_config(const boost::property_tree::ptree &cfg)
{
boost::property_tree::ptree module_config = cfg.get_child("module_config");
for (auto &node : module_config.get_child("gpios"))
{
boost::property_tree::ptree gpio_cfg = node.second;
std::string gpio_name = gpio_cfg.get_child("name").data();
int gpio_no = std::stoi(gpio_cfg.get_child("no").data());
std::string gpio_direction = gpio_cfg.get_child("direction").data();
LOG() << "Creating GPIO " << gpio_name << ", with no " << gpio_no;//<< ". direction = " << gpio_direction;
//export_gpio(gpio_no);
PFGpioPin pin(ctx_, gpio_name, gpio_no);
if (gpio_direction != "in" && gpio_direction != "out")
throw GpioException("Direction (" + gpio_direction + ") is invalid");
pin.set_direction(gpio_direction == "in" ? PFGpioPin::Direction::In : PFGpioPin::Direction::Out);
gpios_.push_back(std::move(pin));
}
}
PFGpioPin::PFGpioPin(zmqpp::context &ctx, const std::string &name, int gpio_no) :
gpio_no_(gpio_no),
sock_(ctx, zmqpp::socket_type::rep),
bus_push_(ctx, zmqpp::socket_type::push),
name_(name)
{
LOG() << "trying to bind to " << ("inproc://" + name);
sock_.bind("inproc://" + name);
bus_push_.connect("inproc://zmq-bus-pull");
}
PFGpioPin::~PFGpioPin()
{
}
PFGpioPin::PFGpioPin(PFGpioPin &&o) :
sock_(std::move(o.sock_)),
bus_push_(std::move(o.bus_push_))
{
this->gpio_no_ = o.gpio_no_;
this->name_ = o.name_;
this->direction_ = o.direction_;
}
PFGpioPin &PFGpioPin::operator=(PFGpioPin &&o)
{
sock_ = std::move(o.sock_);
bus_push_ = std::move(o.bus_push_);
this->gpio_no_ = o.gpio_no_;
this->name_ = o.name_;
this->direction_ = o.direction_;
return *this;
}
void PFGpioPin::handle_message()
{
zmqpp::message_t msg;
std::string frame1;
sock_.receive(msg);
msg >> frame1;
bool ok = false;
if (frame1 == "ON")
ok = turn_on();
else if (frame1 == "OFF")
ok = turn_off();
else if (frame1 == "TOGGLE")
ok = toggle();
sock_.send(ok ? "OK" : "KO");
// publish new state.
LOG() << "gpio nammed {" << name_ << " will publish ";
bus_push_.send(zmqpp::message() << ("S_" + name_) << (read_value() ? "ON" : "OFF"));
}
bool PFGpioPin::turn_on()
{
if (direction_ != Direction::Out)
return false;
pifacedigital_digital_write(gpio_no_, 1);
return true;
}
bool PFGpioPin::turn_off()
{
if (direction_ != Direction::Out)
return false;
pifacedigital_digital_write(gpio_no_, 0);
return true;
}
bool PFGpioPin::toggle()
{
if (direction_ != Direction::Out)
return false;
uint8_t v = pifacedigital_read_bit(gpio_no_, OUTPUT, 0);
if (v)
pifacedigital_digital_write(gpio_no_, 0);
else
pifacedigital_digital_write(gpio_no_, 1);
return true;
}
void PFGpioPin::set_direction(PFGpioPin::Direction d)
{
direction_ = d;
}
bool PFGpioPin::read_value()
{
// pin's direction matter here (not read from same register).
return pifacedigital_read_bit(gpio_no_, direction_ == Direction::Out ? OUTPUT : INPUT, 0);
}
<commit_msg>real time priority for GPIO provider thread<commit_after>#include <memory>
#include <zmqpp/message.hpp>
#include <boost/property_tree/ptree.hpp>
#include <tools/log.hpp>
#include <zmqpp/context.hpp>
#include <fcntl.h>
#include "pifacedigital.hpp"
#include "zmqpp/actor.hpp"
#include "../../../libpifacedigital/src/pifacedigital.h"
#include "../../../libmcp23s17/src/mcp23s17.h"
#include "tools/unixsyscall.hpp"
#include "exception/gpioexception.hpp"
#include <pthread.h>
/**
* pipe is pipe back to module manager.
* this function is called in its own thread.
*
* do signaling when ready
*/
extern "C" __attribute__((visibility("default"))) bool start_module(zmqpp::socket *pipe,
boost::property_tree::ptree cfg,
zmqpp::context &zmq_ctx)
{
PFGpioModule module(cfg, pipe, zmq_ctx);
std::cout << "Init ok (myname = " << cfg.get_child("name").data() << "... sending OK" << std::endl;
pipe->send(zmqpp::signal::ok);
// this thread need realtime priority so it doesn't miss interrupt.
struct sched_param p;
p.sched_priority = 20;
assert(pthread_setschedparam(pthread_self(), SCHED_RR, &p) == 0);
module.run();
std::cout << "module PFGpio shutying down" << std::endl;
return true;
}
PFGpioModule::PFGpioModule(const boost::property_tree::ptree &config,
zmqpp::socket *module_manager_pipe,
zmqpp::context &ctx) :
pipe_(*module_manager_pipe),
config_(config),
is_running_(true),
ctx_(ctx),
bus_push_(ctx_, zmqpp::socket_type::push)
{
process_config(config);
pifacedigital_open(0);
bus_push_.connect("inproc://zmq-bus-pull");
for (auto &gpio : gpios_)
{
reactor_.add(gpio.sock_, std::bind(&PFGpioPin::handle_message, &gpio));
}
reactor_.add(pipe_, std::bind(&PFGpioModule::handle_pipe, this));
assert(pifacedigital_enable_interrupts() == 0);
std::string path_to_gpio = "/sys/class/gpio/gpio" + std::to_string(GPIO_INTERRUPT_PIN) + "/value";
interrupt_fd_ = open(path_to_gpio.c_str(), O_RDONLY | O_NONBLOCK);
assert(interrupt_fd_ > 0);
pifacedigital_read_reg(0x11, 0);//flush
first_ = true; // Ignore GPIO Initial Event
reactor_.add(interrupt_fd_, std::bind(&PFGpioModule::handle_interrupt, this), zmqpp::poller::poll_pri);
}
void PFGpioModule::run()
{
while (is_running_)
{
reactor_.poll(-1);
}
}
void PFGpioModule::handle_pipe()
{
zmqpp::signal s;
pipe_.receive(s, true);
if (s == zmqpp::signal::stop)
is_running_ = false;
}
void PFGpioModule::handle_interrupt()
{
// get interrupt state.
std::array<char, 64> buffer;
if (::read(interrupt_fd_, &buffer[0], buffer.size()) < 0)
throw (GpioException(UnixSyscall::getErrorString("read", errno)));
if (::lseek(interrupt_fd_, 0, SEEK_SET) < 0)
throw (GpioException(UnixSyscall::getErrorString("lseek", errno)));
if (first_)
{
first_ = false;
return;
}
uint8_t states = pifacedigital_read_reg(0x11, 0);
for (int i = 0; i < 8; ++i)
{
if (((states >> i) & 0x01) == 0)
{
// this pin triggered interrupt
//LOG() << "PIN " << i << " IS IN INTERRUPT MODE";
//bus_push_.send(zmqpp::message() << "S_TEST" << (std::string("OMG INTERRUPT ON PIN " + std::to_string(i))));
// signal interrupt if needed (ie the pin is registered in config
std::string gpio_name;
if (get_input_pin_name(gpio_name, i))
{
bus_push_.send(zmqpp::message() << std::string ("S_INT:" + gpio_name));
}
}
}
// states = pifacedigital_read_reg(INPUT, 0);
// for (int i = 0; i < 8; ++i)
// {
// LOG() << "PIN " << i << " HAS VALUE: " << ((states >> i) & 0x01);
// }
// pifacedigital_read_reg(0x11, 0); // flush
}
bool PFGpioModule::get_input_pin_name(std::string &dest, int idx)
{
for (auto &gpio : gpios_)
{
if (gpio.gpio_no_ == idx && gpio.direction_ == PFGpioPin::Direction::In)
{
dest = gpio.name_;
return true;
}
}
return false;
}
void PFGpioModule::process_config(const boost::property_tree::ptree &cfg)
{
boost::property_tree::ptree module_config = cfg.get_child("module_config");
for (auto &node : module_config.get_child("gpios"))
{
boost::property_tree::ptree gpio_cfg = node.second;
std::string gpio_name = gpio_cfg.get_child("name").data();
int gpio_no = std::stoi(gpio_cfg.get_child("no").data());
std::string gpio_direction = gpio_cfg.get_child("direction").data();
LOG() << "Creating GPIO " << gpio_name << ", with no " << gpio_no;//<< ". direction = " << gpio_direction;
//export_gpio(gpio_no);
PFGpioPin pin(ctx_, gpio_name, gpio_no);
if (gpio_direction != "in" && gpio_direction != "out")
throw GpioException("Direction (" + gpio_direction + ") is invalid");
pin.set_direction(gpio_direction == "in" ? PFGpioPin::Direction::In : PFGpioPin::Direction::Out);
gpios_.push_back(std::move(pin));
}
}
PFGpioPin::PFGpioPin(zmqpp::context &ctx, const std::string &name, int gpio_no) :
gpio_no_(gpio_no),
sock_(ctx, zmqpp::socket_type::rep),
bus_push_(ctx, zmqpp::socket_type::push),
name_(name)
{
LOG() << "trying to bind to " << ("inproc://" + name);
sock_.bind("inproc://" + name);
bus_push_.connect("inproc://zmq-bus-pull");
}
PFGpioPin::~PFGpioPin()
{
}
PFGpioPin::PFGpioPin(PFGpioPin &&o) :
sock_(std::move(o.sock_)),
bus_push_(std::move(o.bus_push_))
{
this->gpio_no_ = o.gpio_no_;
this->name_ = o.name_;
this->direction_ = o.direction_;
}
PFGpioPin &PFGpioPin::operator=(PFGpioPin &&o)
{
sock_ = std::move(o.sock_);
bus_push_ = std::move(o.bus_push_);
this->gpio_no_ = o.gpio_no_;
this->name_ = o.name_;
this->direction_ = o.direction_;
return *this;
}
void PFGpioPin::handle_message()
{
zmqpp::message_t msg;
std::string frame1;
sock_.receive(msg);
msg >> frame1;
bool ok = false;
if (frame1 == "ON")
ok = turn_on();
else if (frame1 == "OFF")
ok = turn_off();
else if (frame1 == "TOGGLE")
ok = toggle();
sock_.send(ok ? "OK" : "KO");
// publish new state.
LOG() << "gpio nammed {" << name_ << " will publish ";
bus_push_.send(zmqpp::message() << ("S_" + name_) << (read_value() ? "ON" : "OFF"));
}
bool PFGpioPin::turn_on()
{
if (direction_ != Direction::Out)
return false;
pifacedigital_digital_write(gpio_no_, 1);
return true;
}
bool PFGpioPin::turn_off()
{
if (direction_ != Direction::Out)
return false;
pifacedigital_digital_write(gpio_no_, 0);
return true;
}
bool PFGpioPin::toggle()
{
if (direction_ != Direction::Out)
return false;
uint8_t v = pifacedigital_read_bit(gpio_no_, OUTPUT, 0);
if (v)
pifacedigital_digital_write(gpio_no_, 0);
else
pifacedigital_digital_write(gpio_no_, 1);
return true;
}
void PFGpioPin::set_direction(PFGpioPin::Direction d)
{
direction_ = d;
}
bool PFGpioPin::read_value()
{
// pin's direction matter here (not read from same register).
return pifacedigital_read_bit(gpio_no_, direction_ == Direction::Out ? OUTPUT : INPUT, 0);
}
<|endoftext|> |
<commit_before>///////// UI D2D1 Render code
#include "ui.hpp"
namespace ui {
//// -->
HRESULT Window::CreateDeviceIndependentResources() {
D2D1_FACTORY_OPTIONS options;
ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
HRESULT hr = S_OK;
if ((hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &factory)) <
0) {
return hr;
}
if ((hr = DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory5),
reinterpret_cast<IUnknown **>(&wfactory))) < 0) {
return hr;
}
return wfactory->CreateTextFormat(
L"Segeo UI", nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL, 12.0f * 96.0f / 72.0f, L"zh-CN",
(IDWriteTextFormat **)&wfmt);
}
HRESULT Window::CreateDeviceResources() {
if (render != nullptr) {
return S_OK;
}
RECT rect;
::GetClientRect(m_hWnd, &rect);
auto size = D2D1::SizeU(rect.right - rect.left, rect.bottom - rect.top);
HRESULT hr = S_OK;
if ((hr = factory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(m_hWnd, size), &render)) < 0) {
return hr;
}
if ((hr = render->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black),
&textbrush)) < 0) {
return hr;
}
if ((hr = render->CreateSolidColorBrush(D2D1::ColorF(0xFFC300),
&streaksbrush)) < 0) {
return hr;
}
return S_OK;
}
void Window::DiscardDeviceResources() {
//
Release(&textbrush);
Release(&streaksbrush);
}
D2D1_SIZE_U Window::CalculateD2DWindowSize() {
RECT rc;
::GetClientRect(m_hWnd, &rc);
D2D1_SIZE_U d2dWindowSize = {0};
d2dWindowSize.width = rc.right;
d2dWindowSize.height = rc.bottom;
return d2dWindowSize;
}
void Window::OnResize(UINT width, UINT height) {
if (render != nullptr) {
render->Resize(D2D1::SizeU(width, height));
}
}
HRESULT Window::OnRender() {
auto hr = CreateDeviceResources();
if (!SUCCEEDED(hr)) {
return hr;
}
auto dsz = render->GetSize();
render->BeginDraw();
render->SetTransform(D2D1::Matrix3x2F::Identity());
render->Clear(D2D1::ColorF(D2D1::ColorF::White, 1.0f));
AttributesTablesDraw(); ////
for (const auto &l : labels) {
render->DrawTextW(l.data(), l.length(), wfmt, l.layout(), textbrush,
D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT,
DWRITE_MEASURING_MODE_NATURAL);
}
render->EndDraw();
return S_OK;
}
void Window::AttributesTablesDraw() {
// Draw tables
if (tables.Empty()) {
return; ///
}
////////// -->
float offset = 80;
float w1 = 30;
float w2 = 60;
float keyoff = 180;
float xoff = 60;
for (const auto &e : tables.ats) {
render->DrawTextW(e.name.c_str(), (UINT32)e.name.size(), wfmt,
D2D1::RectF(xoff, offset, keyoff, offset + w1), textbrush,
D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT,
DWRITE_MEASURING_MODE_NATURAL);
render->DrawTextW(
e.value.c_str(), (UINT32)e.value.size(), wfmt,
D2D1::RectF(keyoff + 10, offset, keyoff + 400, offset + w1), textbrush,
D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT,
DWRITE_MEASURING_MODE_NATURAL);
offset += w1;
}
if (!tables.HasDepends()) {
return;
}
render->DrawTextW(tables.Characteristics().Name(),
(UINT32)tables.Characteristics().NameLength(), wfmt,
D2D1::RectF(xoff, offset, keyoff, offset + w2), textbrush,
D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT,
DWRITE_MEASURING_MODE_NATURAL);
render->DrawTextW(
tables.Depends().Name(), (UINT32)tables.Depends().NameLength(), wfmt,
D2D1::RectF(xoff, offset + w2, keyoff, offset + w2 + w2), textbrush,
D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT, DWRITE_MEASURING_MODE_NATURAL);
}
} // namespace ui<commit_msg>Fix render not release when D2DERR_RECREATE_TARGET<commit_after>///////// UI D2D1 Render code
#include "ui.hpp"
namespace ui {
//// -->
HRESULT Window::CreateDeviceIndependentResources() {
D2D1_FACTORY_OPTIONS options;
ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
HRESULT hr = S_OK;
if ((hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &factory)) <
0) {
return hr;
}
if ((hr = DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory5),
reinterpret_cast<IUnknown **>(&wfactory))) < 0) {
return hr;
}
return wfactory->CreateTextFormat(
L"Segeo UI", nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL, 12.0f * 96.0f / 72.0f, L"zh-CN",
(IDWriteTextFormat **)&wfmt);
}
HRESULT Window::CreateDeviceResources() {
if (render != nullptr) {
return S_OK;
}
RECT rect;
::GetClientRect(m_hWnd, &rect);
auto size = D2D1::SizeU(rect.right - rect.left, rect.bottom - rect.top);
HRESULT hr = S_OK;
if ((hr = factory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(m_hWnd, size), &render)) < 0) {
return hr;
}
if ((hr = render->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black),
&textbrush)) < 0) {
return hr;
}
if ((hr = render->CreateSolidColorBrush(D2D1::ColorF(0xFFC300),
&streaksbrush)) < 0) {
return hr;
}
return S_OK;
}
void Window::DiscardDeviceResources() {
//
Release(&render);
Release(&textbrush);
Release(&streaksbrush);
}
D2D1_SIZE_U Window::CalculateD2DWindowSize() {
RECT rc;
::GetClientRect(m_hWnd, &rc);
D2D1_SIZE_U d2dWindowSize = {0};
d2dWindowSize.width = rc.right;
d2dWindowSize.height = rc.bottom;
return d2dWindowSize;
}
void Window::OnResize(UINT width, UINT height) {
if (render != nullptr) {
render->Resize(D2D1::SizeU(width, height));
}
}
HRESULT Window::OnRender() {
auto hr = CreateDeviceResources();
if (!SUCCEEDED(hr)) {
return hr;
}
auto dsz = render->GetSize();
render->BeginDraw();
render->SetTransform(D2D1::Matrix3x2F::Identity());
render->Clear(D2D1::ColorF(D2D1::ColorF::White, 1.0f));
AttributesTablesDraw(); ////
for (const auto &l : labels) {
render->DrawTextW(l.data(), l.length(), wfmt, l.layout(), textbrush,
D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT,
DWRITE_MEASURING_MODE_NATURAL);
}
hr = render->EndDraw();
if (hr == D2DERR_RECREATE_TARGET) {
hr = S_OK;
DiscardDeviceResources();
}
return hr;
}
void Window::AttributesTablesDraw() {
// Draw tables
if (tables.Empty()) {
return; ///
}
////////// -->
float offset = 80;
float w1 = 30;
float w2 = 60;
float keyoff = 180;
float xoff = 60;
for (const auto &e : tables.ats) {
render->DrawTextW(e.name.c_str(), (UINT32)e.name.size(), wfmt,
D2D1::RectF(xoff, offset, keyoff, offset + w1), textbrush,
D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT,
DWRITE_MEASURING_MODE_NATURAL);
render->DrawTextW(
e.value.c_str(), (UINT32)e.value.size(), wfmt,
D2D1::RectF(keyoff + 10, offset, keyoff + 400, offset + w1), textbrush,
D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT,
DWRITE_MEASURING_MODE_NATURAL);
offset += w1;
}
if (!tables.HasDepends()) {
return;
}
render->DrawTextW(tables.Characteristics().Name(),
(UINT32)tables.Characteristics().NameLength(), wfmt,
D2D1::RectF(xoff, offset, keyoff, offset + w2), textbrush,
D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT,
DWRITE_MEASURING_MODE_NATURAL);
render->DrawTextW(
tables.Depends().Name(), (UINT32)tables.Depends().NameLength(), wfmt,
D2D1::RectF(xoff, offset + w2, keyoff, offset + w2 + w2), textbrush,
D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT, DWRITE_MEASURING_MODE_NATURAL);
}
} // namespace ui<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <iterator>
#include "retriever.h"
#include "../node.h"
#include "../node_util.h"
#include "../string_util.h"
#include "../tree.hh"
using std::ifstream;
using std::invalid_argument;
using std::runtime_error;
using std::string;
using std::cout;
using std::endl;
using std::vector;
//Global variable
vector<string> Tag, Def;
vector<string> VecStr;
//Declaration of functions
string format_string_location(string& s); //format the string
string without_white_spaces(string& s); //remove spaces from string
void DeclaDef_separator(string& s,vector<string>& DeclaDef);//separate Declaration from Definition
vector<string> Declaration_separator(string s); //Separate local array from global rarray
string TagDef_separator(string& s, vector<string>& Tag, vector<string>& Def); //separate Tag from Definition part and return the Grp version of the string_location
string ReplaceTagDef_by_Grp(string& s, int a); //Tag/Def is replaced by Grp to determine the priorities of the associations
vector<string> StoreOperators(string& s, int& HowMany); //isolate the operators of the definition part of the string location
vector<string::iterator> PositionSeparator(string s, int TagName_Number); //Find the position of each separator "|"
/*********************************
/SnsHistogramRetriever constructor
/*********************************/
SnsHistogramRetriever::SnsHistogramRetriever(const string &str): source(str)
{
// open the file
infile.open(source.c_str());
// check that open was successful
if(!infile.is_open())
throw invalid_argument("Could not open file: "+source);
}
/*********************************
/SnsHistogramRetriever destructor
/*********************************/
SnsHistogramRetriever::~SnsHistogramRetriever()
{
cout << "~TextPlainRetriever()" << endl;
// close the file
if(infile)
infile.close();
}
/*********.***********************
/* This is the method for retrieving data from a file.
/* Interpreting the string is left up to the implementing code.
/********************************/
void SnsHistogramRetriever::getData(const string &location, tree<Node> &tr)
{
string new_location;
string DefinitionGrpVersion; //use to determine priorities
vector<string> DeclaDef; //declaration and definition parts
vector<string> LocGlobArray; //local and global array (declaration part)
vector<string> Ope; //Operators of the defintion part
int OperatorNumber;
string DefinitionPart; //use to determine the operators
new_location = location;
// check that the argument is not an empty string
if(location.size()<=0)
throw invalid_argument("cannot parse empty string");
//Once upon a time, there was a string location named "location"
//"location" became new_location after loosing its white spaces
new_location = format_string_location(new_location);
//location decided to separate its declaration part (left side of the "D")
//from its definition part --> DeclaDef vector
DeclaDef_separator(new_location,DeclaDef);
//Separate declaration arrays (local and global)
LocGlobArray = Declaration_separator(DeclaDef[0]);
DefinitionPart = DeclaDef[1];
//Work on definition part
DefinitionGrpVersion = TagDef_separator(DeclaDef[1],Tag, Def);
//Store operators
OperatorNumber = Tag.size();
Ope = StoreOperators(DefinitionPart,OperatorNumber);
}
/*********************************
/SnsHistogramRetriever::MIME_TYPE
/*********************************/
const string SnsHistogramRetriever::MIME_TYPE("application/x-SNS-histogram");
string SnsHistogramRetriever::toString() const
{
return "["+MIME_TYPE+"] "+source;
}
/*********************************
/Format the string location
/*********************************/
std::string format_string_location(string& location)
{
return without_white_spaces(location);
}
//Remove white spaces
std::string without_white_spaces(string& location)
{
typedef std::string::size_type string_size;
string_size i=0;
std::string ret="";
while (i != location.size())
{
while (i != location.size() && isspace(location[i]))
{
++i;
}
//find end of next word
string_size j=i;
while (j != location.size() && !isspace(location[j]))
++j;
if (i != j)
{
ret+=location.substr(i,j-i);
i=j;
}
}
return ret;
}
/*********************************
/Separate Decla from Definition
/*********************************/
void DeclaDef_separator(string& new_location,vector<string>& VecStr)
{
typedef std::string::size_type string_size;
int Dposition = new_location.find("D");
string_size taille = new_location.size();
VecStr.push_back(new_location.substr(0,Dposition));
VecStr.push_back(new_location.substr(Dposition+1, taille-VecStr[0].size()-1));
return;
}
/*********************************
/Separate local from global array
/*********************************/
vector<string> Declaration_separator(string DeclarationStr)
{
std::vector<string> LocalArray_GlobalArray;
std::string str;
typedef string::size_type string_size;
string_size DeclarationStrSize = DeclarationStr.size();
int SeparatorPosition = DeclarationStr.find("][");
LocalArray_GlobalArray.push_back(DeclarationStr.substr(0,SeparatorPosition+1));
LocalArray_GlobalArray.push_back(DeclarationStr.substr(SeparatorPosition+1,DeclarationStrSize-LocalArray_GlobalArray[0].size()));
return LocalArray_GlobalArray;
}
/*********************************
/Separate Tag from Definition
/*********************************/
string TagDef_separator(string& DefinitionPart, vector<string>& Tag, vector<string>& Def)
{
std::vector<string> ret;
typedef string::iterator iter;
iter b = DefinitionPart.begin(), e = DefinitionPart.end(), a;
int CPosition, OpenBraPosition, CloseBraPosition = 1;
string separator = "|";
string StringLocationGroup = DefinitionPart;
static const string OpenBracket = "{";
static const string CloseBracket = "}";
int HowManyTimes = 0, i = 0, length = DefinitionPart.size();
while (b!=e)
{
if (find(b, DefinitionPart.end(), separator[0]) != DefinitionPart.end())
{
++HowManyTimes;
b = find(b, DefinitionPart.end(),separator[0]);
b=b+1;
}
b=b+1;
}
while (i < HowManyTimes)
{
CPosition = DefinitionPart.find(separator[0]);
OpenBraPosition = DefinitionPart.find(OpenBracket);
CloseBraPosition = DefinitionPart.find(CloseBracket);
//StringLocationGroup.erase(OpenBraPosition, CloseBraPosition);
//remove TagName|Definition by groupnumber
Tag.push_back( DefinitionPart.substr(OpenBraPosition+1,CPosition-OpenBraPosition-1));
Def.push_back( DefinitionPart.substr(CPosition+1,CloseBraPosition-CPosition-1));
DefinitionPart= DefinitionPart.substr(CloseBraPosition+1, length-CloseBraPosition-2);
++i;
}
return ReplaceTagDef_by_Grp(StringLocationGroup,HowManyTimes);
}
/*********************************
/Replace Tag/Def part by Grp#
/*********************************/
string ReplaceTagDef_by_Grp(string& StringLocationGroup, int HowManyTimes)
{
static const string separator = "|";
static const string OpenBracket = "{";
static const string CloseBracket = "}";
string part1, part2;
int OpenBraPosition, CloseBraPosition;
for (int j=0 ; j<HowManyTimes ; j++)
{
//cout << std::endl << std::endl << "j= " << j << std::endl << std::endl;
std::ostringstream Grp;
OpenBraPosition = StringLocationGroup.find(OpenBracket);
CloseBraPosition = StringLocationGroup.find(CloseBracket);
StringLocationGroup.erase(OpenBraPosition, CloseBraPosition+1-OpenBraPosition);
part1 = StringLocationGroup.substr(0,OpenBraPosition);
part2 = StringLocationGroup.substr(OpenBraPosition, StringLocationGroup.size());
Grp << "grp" << j ;
//cout << "grp = " << Grp.str() << std::endl;
StringLocationGroup = part1 + Grp.str() + part2;
//cout << "(after adding grp) s= " << s << std::endl;
}
return StringLocationGroup;
}
/*********************************
/Store operators
/*********************************/
vector<string> StoreOperators(string& StrS, int& HowMany)
{
typedef string::iterator iter;
std::vector<iter> VecIter; //vector of iterators
std::string::iterator a;
string operatorAND = "AND";
string operatorOR = "OR";
vector<string> Ope;
//Store each position of "|" into VecIter
VecIter = PositionSeparator(StrS,HowMany);
for (int i=0; i<HowMany-1; i++)
{
if (find(VecIter[i],VecIter[i+1],operatorAND[0])!=VecIter[i+1])
{
Ope.push_back("AND");
}
else
{
Ope.push_back("OR");
}
//cout << "Ope[" << i << "]= " << Ope[i]<< std::endl;
}
return Ope;
}
/*********************************
/Find iterator for each separator
/*********************************/
vector<string::iterator> PositionSeparator(string s, int TagName_Number)
{ std::vector<string::iterator> VecIter;
int i = 0;
typedef string::iterator iter;
iter b = s.begin();
string separator = "|";
while (i < TagName_Number)
{
VecIter.push_back(find(b, s.end(), separator[0]));
b = find(b,s.end(),separator[0])+1;
++i;
}
return VecIter;
}
<commit_msg>Added functions that parse parameters of the different loops defined ex: loop(1,2000,3) -> init=1 last=2000 increment=3<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <iterator>
#include <stdlib.h>
#include "retriever.h"
#include "../node.h"
#include "../node_util.h"
#include "../string_util.h"
#include "../tree.hh"
using std::ifstream;
using std::invalid_argument;
using std::runtime_error;
using std::string;
using std::cout;
using std::endl;
using std::vector;
//Global variable
vector<string> Tag, Def;
vector<string> VecStr;
struct Grp_parameters //parameters of the different definitions
{
int init, last, increment; //with loop(init,end,increment)
vector<int> value; //(value[0],value[1],....)
char c; //c=l for loop and c=p for (x,y,z,...)
};
vector<Grp_parameters> GrpPara;
//Declaration of functions
string format_string_location(string& s); //format the string
string without_white_spaces(string& s); //remove spaces from string
void DeclaDef_separator(string& s,vector<string>& DeclaDef);//separate Declaration from Definition
vector<string> Declaration_separator(string s); //Separate local array from global rarray
string TagDef_separator(string& s, vector<string>& Tag, vector<string>& Def); //separate Tag from Definition part and return the Grp version of the string_location
string ReplaceTagDef_by_Grp(string& s, int a); //Tag/Def is replaced by Grp to determine the priorities of the associations
vector<string> StoreOperators(string& s, int& HowMany); //isolate the operators of the definition part of the string location
vector<string::iterator> PositionSeparator(string s, int TagName_Number); //Find the position of each separator "|"
void GivePriorityToGrp ( string& s, int OperatorNumber, vector<int> GrpPriority, vector<int> InverseDef); //Give priority to each grp of the definition part
void DefinitionParametersFunction(vector<string> Def,int OperatorNumber);
void InitLastIncre (string& def, int i); //Isolate loop(init,last,increment)
/*********************************
/SnsHistogramRetriever constructor
/*********************************/
SnsHistogramRetriever::SnsHistogramRetriever(const string &str): source(str)
{
// open the file
infile.open(source.c_str());
// check that open was successful
if(!infile.is_open())
throw invalid_argument("Could not open file: "+source);
}
/*********************************
/SnsHistogramRetriever destructor
/*********************************/
SnsHistogramRetriever::~SnsHistogramRetriever()
{
cout << "~TextPlainRetriever()" << endl;
// close the file
if(infile)
infile.close();
}
/*********.***********************
/* This is the method for retrieving data from a file.
/* Interpreting the string is left up to the implementing code.
/********************************/
void SnsHistogramRetriever::getData(const string &location, tree<Node> &tr)
{
string new_location;
string DefinitionGrpVersion; //use to determine priorities
vector<string> DeclaDef; //declaration and definition parts
vector<string> LocGlobArray; //local and global array (declaration part)
vector<string> Ope; //Operators of the defintion part
int OperatorNumber;
string DefinitionPart; //use to determine the operators
vector<int> GrpPriority; //Vector of priority of each group
vector<int> InverseDef; //True=Inverse definition, False=keep it like it is
new_location = location;
// check that the argument is not an empty string
if(location.size()<=0)
throw invalid_argument("cannot parse empty string");
//Once upon a time, there was a string location named "location"
//"location" became new_location after loosing its white spaces
new_location = format_string_location(new_location);
//location decided to separate its declaration part (left side of the "D")
//from its definition part --> DeclaDef vector
DeclaDef_separator(new_location,DeclaDef);
//Separate declaration arrays (local and global)
LocGlobArray = Declaration_separator(DeclaDef[0]);
//Work on definition part
DefinitionPart = DeclaDef[1];
DefinitionGrpVersion = TagDef_separator(DeclaDef[1],Tag, Def);
cout << "DefinitionGrpVersion= " << DefinitionGrpVersion << endl; //REMOVE
//Store operators
OperatorNumber = Tag.size();
Ope = StoreOperators(DefinitionPart,OperatorNumber);
//Give to each grp its priority
GivePriorityToGrp(DefinitionGrpVersion, OperatorNumber, GrpPriority, InverseDef);
//Store parameters of the definition part into GrpPara[0], GrpPara[1]...
DefinitionParametersFunction(Def,OperatorNumber);
}
/*********************************
/SnsHistogramRetriever::MIME_TYPE
/*********************************/
const string SnsHistogramRetriever::MIME_TYPE("application/x-SNS-histogram");
string SnsHistogramRetriever::toString() const
{
return "["+MIME_TYPE+"] "+source;
}
/*********************************
/Format the string location
/*********************************/
std::string format_string_location(string& location)
{
return without_white_spaces(location);
}
//Remove white spaces
std::string without_white_spaces(string& location)
{
typedef std::string::size_type string_size;
string_size i=0;
std::string ret="";
while (i != location.size())
{
while (i != location.size() && isspace(location[i]))
{
++i;
}
//find end of next word
string_size j=i;
while (j != location.size() && !isspace(location[j]))
++j;
if (i != j)
{
ret+=location.substr(i,j-i);
i=j;
}
}
return ret;
}
/*********************************
/Separate Decla from Definition
/*********************************/
void DeclaDef_separator(string& new_location,vector<string>& VecStr)
{
typedef std::string::size_type string_size;
int Dposition = new_location.find("D");
string_size taille = new_location.size();
VecStr.push_back(new_location.substr(0,Dposition));
VecStr.push_back(new_location.substr(Dposition+1, taille-VecStr[0].size()-1));
return;
}
/*********************************
/Separate local from global array
/*********************************/
vector<string> Declaration_separator(string DeclarationStr)
{
std::vector<string> LocalArray_GlobalArray;
std::string str;
typedef string::size_type string_size;
string_size DeclarationStrSize = DeclarationStr.size();
int SeparatorPosition = DeclarationStr.find("][");
LocalArray_GlobalArray.push_back(DeclarationStr.substr(0,SeparatorPosition+1));
LocalArray_GlobalArray.push_back(DeclarationStr.substr(SeparatorPosition+1,DeclarationStrSize-LocalArray_GlobalArray[0].size()));
return LocalArray_GlobalArray;
}
/*********************************
/Separate Tag from Definition
/*********************************/
string TagDef_separator(string& DefinitionPart, vector<string>& Tag, vector<string>& Def)
{
std::vector<string> ret;
typedef string::iterator iter;
iter b = DefinitionPart.begin(), e = DefinitionPart.end(), a;
int CPosition, OpenBraPosition, CloseBraPosition = 1;
string separator = "|";
string StringLocationGroup = DefinitionPart;
static const string OpenBracket = "{";
static const string CloseBracket = "}";
int HowManyTimes = 0, i = 0, length = DefinitionPart.size();
while (b!=e)
{
if (find(b, DefinitionPart.end(), separator[0]) != DefinitionPart.end())
{
++HowManyTimes;
b = find(b, DefinitionPart.end(),separator[0]);
b=b+1;
}
b=b+1;
}
while (i < HowManyTimes)
{
CPosition = DefinitionPart.find(separator[0]);
OpenBraPosition = DefinitionPart.find(OpenBracket);
CloseBraPosition = DefinitionPart.find(CloseBracket);
//StringLocationGroup.erase(OpenBraPosition, CloseBraPosition);
//remove TagName|Definition by groupnumber
Tag.push_back( DefinitionPart.substr(OpenBraPosition+1,CPosition-OpenBraPosition-1));
Def.push_back( DefinitionPart.substr(CPosition+1,CloseBraPosition-CPosition-1));
DefinitionPart= DefinitionPart.substr(CloseBraPosition+1, length-CloseBraPosition-2);
++i;
}
return ReplaceTagDef_by_Grp(StringLocationGroup,HowManyTimes);
}
/*********************************
/Replace Tag/Def part by Grp#
/*********************************/
string ReplaceTagDef_by_Grp(string& StringLocationGroup, int HowManyTimes)
{
static const string separator = "|";
static const string OpenBracket = "{";
static const string CloseBracket = "}";
string part1, part2;
int OpenBraPosition, CloseBraPosition;
for (int j=0 ; j<HowManyTimes ; j++)
{
//cout << std::endl << std::endl << "j= " << j << std::endl << std::endl;
std::ostringstream Grp;
OpenBraPosition = StringLocationGroup.find(OpenBracket);
CloseBraPosition = StringLocationGroup.find(CloseBracket);
StringLocationGroup.erase(OpenBraPosition, CloseBraPosition+1-OpenBraPosition);
part1 = StringLocationGroup.substr(0,OpenBraPosition);
part2 = StringLocationGroup.substr(OpenBraPosition, StringLocationGroup.size());
Grp << "grp" << j ;
StringLocationGroup = part1 + Grp.str() + part2;
//cout << "(after adding grp) s= " << StringLocationGroup << std::endl; //REMOVE
}
return StringLocationGroup;
}
/*********************************
/Store operators
/*********************************/
vector<string> StoreOperators(string& StrS, int& HowMany)
{
typedef string::iterator iter;
std::vector<iter> VecIter; //vector of iterators
std::string::iterator a;
string operatorAND = "AND";
string operatorOR = "OR";
vector<string> Ope;
//Store each position of "|" into VecIter
VecIter = PositionSeparator(StrS,HowMany);
for (int i=0; i<HowMany-1; i++)
{
if (find(VecIter[i],VecIter[i+1],operatorAND[0])!=VecIter[i+1])
{
Ope.push_back("AND");
}
else
{
Ope.push_back("OR");
}
//cout << "Ope[" << i << "]= " << Ope[i]<< std::endl;
}
return Ope;
}
/*********************************
/Find iterator for each separator
/*********************************/
vector<string::iterator> PositionSeparator(string s, int TagName_Number)
{ std::vector<string::iterator> VecIter;
int i = 0;
typedef string::iterator iter;
iter b = s.begin();
string separator = "|";
while (i < TagName_Number)
{
VecIter.push_back(find(b, s.end(), separator[0]));
b = find(b,s.end(),separator[0])+1;
++i;
}
return VecIter;
}
/*********************************
/Give priority for each group
/*********************************/
void GivePriorityToGrp ( string& s, int OperatorNumber, vector<int> GrpPriority, vector<int> InverseDef)
{
int DefinitionString_size = s.size();
int GrpNumberLive = 0;
int Priority = 0;
//Initialization of vector<int> and vector<bool>
for (int i=0; i<OperatorNumber; i++)
{
GrpPriority.push_back(0);
InverseDef.push_back(0);
}
//move along the definition part and look for g,A,O,!,(,and ).
for (int j=0; j<DefinitionString_size; j++)
{
switch (s[j])
{
case 'g':
j=j+3; //move to end of grp#
GrpPriority[GrpNumberLive]=Priority;
++GrpNumberLive;
break;
case '!':
InverseDef[GrpNumberLive]=1;
break;
case '(':
++Priority;
break;
case ')':
--Priority;
break;
default:
//nothing
break;
}
}
/* //for debugging only //REMOVE
for (int j=0; j<OperatorNumber; j++)
{
cout<<"GrpPriority[" << j << "]= " << GrpPriority[j];
cout<<" ";
cout<<"InverseDef["<<j<<"]= "<<InverseDef[j]<<endl;
}*/
return;
}
/*********************************
/Store values of the definition
/*********************************/
void DefinitionParametersFunction(vector<string> Def,int HowManyDef)
{
Grp_parameters record;
string NewString;
//for debugging only //REMOVE
for (int i =0; i<HowManyDef;i++)
{
cout << "Def["<<i<<"]= " << Def[i]<<endl;
}
//find out first if it's a loop or a (....)
for (int i =0; i<HowManyDef;i++)
{
if (Def[i].find("loop") < Def[i].size())
{
record.c = 'l';
}
else
{
record.c = 'p';
}
GrpPara.push_back(record);
}
//isolate the variable
for (int i=0; i<HowManyDef;i++)
{
if (GrpPara[i].c == 'l') //loop
{
InitLastIncre(Def[i],i);
/* cout << "GrpPara["<<i<<"].init="<<GrpPara[i].init<<endl; //REMOVE
cout << "GrpPara["<<i<<"].last="<<GrpPara[i].last<<endl;
cout << "GrpPara["<<i<<"].increment="<<GrpPara[i].increment<<endl;
cout << " "<<endl;*/
}
else //(....)
{
}
}
return;
}
/*********************************
/Store Initial, last and increment
/*********************************/
void InitLastIncre (string& def, int i)
{
static const string sep=",";
int pos1, pos2;
string new_def;
//Remove "loop(" and ")"
def=def.substr(5,def.size()-6);
//store the info into GrpPara[i].init, end and increment
pos1 = def.find(sep);
new_def = def.substr(pos1+1,def.size()-pos1);
pos2 = new_def.find(sep);
GrpPara[i].init =atoi((def.substr(0,pos1)).c_str());
GrpPara[i].last =atoi((def.substr(pos1+1,pos2).c_str()));
GrpPara[i].increment = atoi((new_def.substr(pos2+1, new_def.size()-1).c_str()));
cout <<"def= " << def<<endl; //REMOVE
return;
}
<|endoftext|> |
<commit_before>//=============================================================================================================
/**
* @file settingscontrollergui.cpp
* @author Juan GPC <[email protected]>
* @since 0.1.0
* @date May, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Juan GPC. 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 MNE-CPP authors 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.
*
*
* @brief SettingsControllerGUI class definition.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "settingscontrollergui.h"
#include "mainwindow.h"
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QDir>
#include <QStandardPaths>
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace MNEANONYMIZE;
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
SettingsControllerGui::SettingsControllerGui(const QStringList& arguments)
: m_pWin(QSharedPointer<MainWindow> (new MainWindow(this)))
{
initParser();
parseInputs(arguments);
setupCommunication();
initializeOptionsState();
m_pWin->show();
if(m_fiInFileInfo.isFile())
{
readData();
}
}
void SettingsControllerGui::executeAnonymizer()
{
m_pAnonymizer->anonymizeFile();
// if(checkDeleteInputFile())
// {
// deleteInputFile();
// }
}
void SettingsControllerGui::readData()
{
//set output to a randomFilename
QString stringTempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
QString fileOutStr(QDir(stringTempDir).filePath(generateRandomFileName()));
m_pAnonymizer->setFileOut(fileOutStr);
m_pAnonymizer->anonymizeFile();
QFile fileOut(fileOutStr);
fileOut.remove();
m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
}
void SettingsControllerGui::fileInChanged(const QString& strInFile)
{
m_fiInFileInfo.setFile(strInFile);
m_pAnonymizer->setFileIn(m_fiInFileInfo.absoluteFilePath());
if(m_fiInFileInfo.isFile())
{
readData();
}
}
void SettingsControllerGui::fileOutChanged(const QString& strOutFile)
{
m_fiOutFileInfo.setFile(strOutFile);
m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
}
void SettingsControllerGui::setupCommunication()
{
//from view to model
QObject::connect(m_pWin.data(),&MainWindow::fileInChanged,
this,&SettingsControllerGui::fileInChanged);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
this,&SettingsControllerGui::fileOutChanged);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
//from model to view
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdFileVersion,
m_pWin.data(),&MainWindow::setLineEditIdFileVersion);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMeasurementDate,
m_pWin.data(),&MainWindow::setLineEditIdMeasurementDate);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMac,
m_pWin.data(),&MainWindow::setLineEditIdMacAddress);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileMeasurementDate,
m_pWin.data(),&MainWindow::setLineEditFileMeasurementDate);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileComment,
m_pWin.data(),&MainWindow::setLineEditFileComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileExperimenter,
m_pWin.data(),&MainWindow::setLineEditFileExperimenter);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectId,
m_pWin.data(),&MainWindow::setLineEditSubjectId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectFirstName,
m_pWin.data(),&MainWindow::setLineEditSubjectFirstName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectMiddleName,
m_pWin.data(),&MainWindow::setLineEditSubjectMiddleName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectLastName,
m_pWin.data(),&MainWindow::setLineEditSubjectLastName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectBirthday,
m_pWin.data(),&MainWindow::setLineEditSubjectBirthday);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectSex,
m_pWin.data(),&MainWindow::setLineEditSubjectSex);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHand,
m_pWin.data(),&MainWindow::setLineEditSubjectHand);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectWeight,
m_pWin.data(),&MainWindow::setLineEditSubjectHand);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHeight,
m_pWin.data(),&MainWindow::setLineEditSubjectHeight);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectComment,
m_pWin.data(),&MainWindow::setLineEditSubjectComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHisId,
m_pWin.data(),&MainWindow::setLineEditSubjectHisId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectId,
m_pWin.data(),&MainWindow::setLineEditProjectId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectName,
m_pWin.data(),&MainWindow::setLineEditProjectName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectAim,
m_pWin.data(),&MainWindow::setLineEditProjectAim);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectPersons,
m_pWin.data(),&MainWindow::setLineEditProjectPersons);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectComment,
m_pWin.data(),&MainWindow::setLineEditProjectComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::mriDataFoundInFile,
m_pWin.data(),&MainWindow::setLabelMriDataFoundVisible);
}
void SettingsControllerGui::initializeOptionsState()
{
m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
m_pWin->setCheckBoxBruteMode(m_pAnonymizer->getBruteMode());
// m_pWin->setCheckBoxDeleteInputFileAfter(m_bDeleteInputFileAfter);
// m_pWin->setCheckBoxAvoidDeleteConfirmation(m_bDeleteInputFileConfirmation);
m_pWin->setMeasurementDate(m_pAnonymizer->getMeasurementDate());
m_pWin->setCheckBoxMeasurementDateOffset(m_pAnonymizer->getUseMeasurementDayOffset());
m_pWin->setMeasurementDateOffset(m_pAnonymizer->getMeasurementDayOffset());
m_pWin->setCheckBoxSubjectBirthdayOffset(m_pAnonymizer->getUseSubjectBirthdayOffset());
m_pWin->setSubjectBirthdayOffset(m_pAnonymizer->getSubjectBirthdayOffset());
if(m_bHisIdSpecified)
{
m_pWin->setSubjectHis(m_pAnonymizer->getSubjectHisID());
}
}
<commit_msg>controller only reads when anonymizer is set<commit_after>//=============================================================================================================
/**
* @file settingscontrollergui.cpp
* @author Juan GPC <[email protected]>
* @since 0.1.0
* @date May, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Juan GPC. 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 MNE-CPP authors 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.
*
*
* @brief SettingsControllerGUI class definition.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "settingscontrollergui.h"
#include "mainwindow.h"
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QDir>
#include <QStandardPaths>
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace MNEANONYMIZE;
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
SettingsControllerGui::SettingsControllerGui(const QStringList& arguments)
: m_pWin(QSharedPointer<MainWindow> (new MainWindow(this)))
{
initParser();
parseInputs(arguments);
setupCommunication();
initializeOptionsState();
m_pWin->show();
if(m_pAnonymizer->isFileInSet())
{
readData();
}
}
void SettingsControllerGui::executeAnonymizer()
{
m_pAnonymizer->anonymizeFile();
}
void SettingsControllerGui::readData()
{
//set output to a randomFilename
QString stringTempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
QString fileOutStr(QDir(stringTempDir).filePath(generateRandomFileName()));
m_pAnonymizer->setFileOut(fileOutStr);
m_pAnonymizer->anonymizeFile();
QFile fileOut(fileOutStr);
fileOut.remove();
m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
}
void SettingsControllerGui::fileInChanged(const QString& strInFile)
{
m_fiInFileInfo.setFile(strInFile);
m_pAnonymizer->setFileIn(m_fiInFileInfo.absoluteFilePath());
if(m_fiInFileInfo.isFile())
{
readData();
}
}
void SettingsControllerGui::fileOutChanged(const QString& strOutFile)
{
m_fiOutFileInfo.setFile(strOutFile);
m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
}
void SettingsControllerGui::setupCommunication()
{
//from view to model
QObject::connect(m_pWin.data(),&MainWindow::fileInChanged,
this,&SettingsControllerGui::fileInChanged);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
this,&SettingsControllerGui::fileOutChanged);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
//from model to view
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdFileVersion,
m_pWin.data(),&MainWindow::setLineEditIdFileVersion);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMeasurementDate,
m_pWin.data(),&MainWindow::setLineEditIdMeasurementDate);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMac,
m_pWin.data(),&MainWindow::setLineEditIdMacAddress);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileMeasurementDate,
m_pWin.data(),&MainWindow::setLineEditFileMeasurementDate);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileComment,
m_pWin.data(),&MainWindow::setLineEditFileComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileExperimenter,
m_pWin.data(),&MainWindow::setLineEditFileExperimenter);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectId,
m_pWin.data(),&MainWindow::setLineEditSubjectId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectFirstName,
m_pWin.data(),&MainWindow::setLineEditSubjectFirstName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectMiddleName,
m_pWin.data(),&MainWindow::setLineEditSubjectMiddleName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectLastName,
m_pWin.data(),&MainWindow::setLineEditSubjectLastName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectBirthday,
m_pWin.data(),&MainWindow::setLineEditSubjectBirthday);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectSex,
m_pWin.data(),&MainWindow::setLineEditSubjectSex);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHand,
m_pWin.data(),&MainWindow::setLineEditSubjectHand);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectWeight,
m_pWin.data(),&MainWindow::setLineEditSubjectHand);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHeight,
m_pWin.data(),&MainWindow::setLineEditSubjectHeight);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectComment,
m_pWin.data(),&MainWindow::setLineEditSubjectComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHisId,
m_pWin.data(),&MainWindow::setLineEditSubjectHisId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectId,
m_pWin.data(),&MainWindow::setLineEditProjectId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectName,
m_pWin.data(),&MainWindow::setLineEditProjectName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectAim,
m_pWin.data(),&MainWindow::setLineEditProjectAim);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectPersons,
m_pWin.data(),&MainWindow::setLineEditProjectPersons);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectComment,
m_pWin.data(),&MainWindow::setLineEditProjectComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::mriDataFoundInFile,
m_pWin.data(),&MainWindow::setLabelMriDataFoundVisible);
}
void SettingsControllerGui::initializeOptionsState()
{
m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
m_pWin->setCheckBoxBruteMode(m_pAnonymizer->getBruteMode());
// m_pWin->setCheckBoxDeleteInputFileAfter(m_bDeleteInputFileAfter);
// m_pWin->setCheckBoxAvoidDeleteConfirmation(m_bDeleteInputFileConfirmation);
m_pWin->setMeasurementDate(m_pAnonymizer->getMeasurementDate());
m_pWin->setCheckBoxMeasurementDateOffset(m_pAnonymizer->getUseMeasurementDayOffset());
m_pWin->setMeasurementDateOffset(m_pAnonymizer->getMeasurementDayOffset());
m_pWin->setCheckBoxSubjectBirthdayOffset(m_pAnonymizer->getUseSubjectBirthdayOffset());
m_pWin->setSubjectBirthdayOffset(m_pAnonymizer->getSubjectBirthdayOffset());
if(m_bHisIdSpecified)
{
m_pWin->setSubjectHis(m_pAnonymizer->getSubjectHisID());
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
// Please see LICENSE.md in repository root for license information
// https://github.com/AtomicGameEngine/AtomicGameEngine
#include <Atomic/Atomic.h>
#include <Atomic/IO/Log.h>
#include <Atomic/Core/ProcessUtils.h>
#include <Atomic/Resource/ResourceCache.h>
#include "JSBind.h"
#include "JSBPackage.h"
#include "JSBModule.h"
#include "JSBFunction.h"
#include "JSBDoc.h"
namespace ToolCore
{
static String GetScriptType(JSBFunctionType* ftype)
{
String scriptType = "number";
if (ftype->type_->asPrimitiveType())
{
JSBPrimitiveType* ptype = ftype->type_->asPrimitiveType();
if (ptype->kind_ == JSBPrimitiveType::Bool)
scriptType = "boolean";
}
if (ftype->type_->asStringHashType() || ftype->type_->asStringType())
scriptType = "string";
if (ftype->type_->asEnumType())
scriptType = "Atomic." + ftype->type_->asEnumType()->enum_->GetName();
if (ftype->type_->asEnumType())
scriptType = "Atomic." + ftype->type_->asEnumType()->enum_->GetName();
if (ftype->type_->asClassType())
scriptType = "Atomic." + ftype->type_->asClassType()->class_->GetName();
return scriptType;
}
void JSBDoc::Begin()
{
source_ += "//Atomic JSDoc Definitions\n\n\n";
source_ += "/**\n * Atomic Game Engine\n * @namespace\n*/\n var " + package_->GetName() + " = {}\n\n";
}
void JSBDoc::End()
{
}
String JSBDoc::GenFunctionDoc(JSBFunction* function)
{
if (function->Skip())
return "";
String params;
Vector<JSBFunctionType*>& parameters = function->GetParameters();
for (unsigned i = 0; i < parameters.Size(); i++)
{
JSBFunctionType* ftype = parameters.At(i);
String scriptType = GetScriptType(ftype);
if (scriptType == "Atomic.Context")
continue;
// mark as optional
if (ftype->initializer_.Length())
scriptType += "=";
params += " * @param {" + scriptType + "} " + ftype->name_ + "\n";
}
String returns;
if (function->GetReturnType())
returns = " * @returns { " + GetScriptType(function->GetReturnType()) + "}\n";
String docString;
if (function->IsConstructor())
{
docString.AppendWithFormat("%s", params.CString());
}
else
{
docString.AppendWithFormat(" * %s\n * @memberof Atomic.%s.prototype\n%s%s\n",
function->GetDocString().CString(),
function->GetClass()->GetName().CString(),
params.CString(),
returns.CString());
}
return docString;
}
void JSBDoc::ExportModuleClasses(JSBModule* module)
{
Vector<SharedPtr<JSBClass>> classes = module->GetClasses();
if (!classes.Size())
return;
source_ += "\n";
for (unsigned i = 0; i < classes.Size(); i++)
{
JSBClass* klass = classes.At(i);
source_ += "/**\n * @class\n* @memberof Atomic\n";
if (klass->GetBaseClass())
source_ += " * @augments Atomic." + klass->GetBaseClass()->GetName()+ "\n";
// PROPERTIES
Vector<String> propertyNames;
klass->GetPropertyNames(propertyNames);
for (unsigned j = 0; j < propertyNames.Size(); j++)
{
JSBProperty* prop = klass->GetProperty(propertyNames[j]);
JSBFunctionType* ftype = NULL;
String desc;
if (prop->getter_ && !prop->getter_->Skip())
{
desc = prop->getter_->GetDocString();
ftype = prop->getter_->GetReturnType();
}
else if (prop->setter_ && !prop->setter_->Skip())
{
ftype = prop->setter_->GetParameters()[0];
}
if (prop->setter_ && prop->setter_->GetDocString().Length())
{
// overwrite getter docstring if it exsists
desc = prop->setter_->GetDocString();
}
if (!ftype)
continue;
String scriptType = GetScriptType(ftype);
String scriptName = prop->GetCasePropertyName();
if (desc.Length())
{
source_ += " * @property {" + scriptType + "} " + scriptName + " - " + desc + "\n";
}
else
{
source_ += " * @property {" + scriptType + "} " + scriptName + "\n";
}
}
JSBFunction* constructor = klass->GetConstructor();
if (constructor)
{
String docs = GenFunctionDoc(constructor);
source_ += docs;
}
source_ += "*/ \nfunction " + klass->GetName() + "() {};\n\n";
// FUNCTIONS
PODVector<JSBFunction*>& functions = klass->GetFunctions();
for (unsigned j = 0; j < functions.Size(); j++)
{
JSBFunction* func = functions[j];
if (func->IsConstructor() || func->IsDestructor() || func->Skip())
continue;
String docs = GenFunctionDoc(func);
String scriptName = func->GetName();
scriptName[0] = tolower(scriptName[0]);
if (scriptName == "delete")
scriptName = "__delete";
String docString;
docString.AppendWithFormat("/**\n %s */\n function %s() {};\n\n",
docs.CString(),
scriptName.CString());
source_ += docString;
}
}
}
void JSBDoc::ExportModuleConstants(JSBModule* module)
{
Vector<String>& constants = module->GetConstants().Keys();
if (!constants.Size())
return;
source_ += "\n";
for (unsigned i = 0; i < constants.Size(); i++)
{
const String& cname = constants.At(i);
source_ += "/**\n * @memberof Atomic\n * @type {number}\n */\nvar " + cname + ";\n";
}
source_ += "\n";
}
void JSBDoc::ExportModuleEnums(JSBModule* module)
{
Vector<SharedPtr<JSBEnum>> enums = module->GetEnums();
for (unsigned i = 0; i < enums.Size(); i++)
{
JSBEnum* _enum = enums.At(i);
source_ += "/**\n * @memberof Atomic\n * @readonly\n * @enum {number}\n */\n";
source_ += " var " + _enum->GetName() + " = {\n";
Vector<String>& values = _enum->GetValues();
for (unsigned j = 0; j < values.Size(); j++)
{
source_ += " " + values[j] + " : undefined";
if (j != values.Size() - 1)
source_ += ",\n";
}
source_ += "\n\n};\n\n";
}
}
void JSBDoc::WriteToFile(const String &path)
{
File file(package_->GetContext());
file.Open(path, FILE_WRITE);
file.Write(source_.CString(), source_.Length());
file.Close();
}
void JSBDoc::Emit(JSBPackage* package, const String& path)
{
package_ = package;
Vector<SharedPtr<JSBModule>>& modules = package->GetModules();
Begin();
for (unsigned i = 0; i < modules.Size(); i++)
{
ExportModuleEnums(modules[i]);
}
for (unsigned i = 0; i < modules.Size(); i++)
{
ExportModuleConstants(modules[i]);
}
for (unsigned i = 0; i < modules.Size(); i++)
{
source_ += "\n//----------------------------------------------------\n";
source_ += "// MODULE: " + modules[i]->GetName() + "\n";
source_ += "//----------------------------------------------------\n\n";
ExportModuleClasses(modules[i]);
}
End();
WriteToFile(path);
}
}
<commit_msg>Fix for gcc/clang compilers<commit_after>// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
// Please see LICENSE.md in repository root for license information
// https://github.com/AtomicGameEngine/AtomicGameEngine
#include <Atomic/Atomic.h>
#include <Atomic/IO/Log.h>
#include <Atomic/Core/ProcessUtils.h>
#include <Atomic/Resource/ResourceCache.h>
#include "JSBind.h"
#include "JSBPackage.h"
#include "JSBModule.h"
#include "JSBFunction.h"
#include "JSBDoc.h"
namespace ToolCore
{
static String GetScriptType(JSBFunctionType* ftype)
{
String scriptType = "number";
if (ftype->type_->asPrimitiveType())
{
JSBPrimitiveType* ptype = ftype->type_->asPrimitiveType();
if (ptype->kind_ == JSBPrimitiveType::Bool)
scriptType = "boolean";
}
if (ftype->type_->asStringHashType() || ftype->type_->asStringType())
scriptType = "string";
if (ftype->type_->asEnumType())
scriptType = "Atomic." + ftype->type_->asEnumType()->enum_->GetName();
if (ftype->type_->asEnumType())
scriptType = "Atomic." + ftype->type_->asEnumType()->enum_->GetName();
if (ftype->type_->asClassType())
scriptType = "Atomic." + ftype->type_->asClassType()->class_->GetName();
return scriptType;
}
void JSBDoc::Begin()
{
source_ += "//Atomic JSDoc Definitions\n\n\n";
source_ += "/**\n * Atomic Game Engine\n * @namespace\n*/\n var " + package_->GetName() + " = {}\n\n";
}
void JSBDoc::End()
{
}
String JSBDoc::GenFunctionDoc(JSBFunction* function)
{
if (function->Skip())
return "";
String params;
Vector<JSBFunctionType*>& parameters = function->GetParameters();
for (unsigned i = 0; i < parameters.Size(); i++)
{
JSBFunctionType* ftype = parameters.At(i);
String scriptType = GetScriptType(ftype);
if (scriptType == "Atomic.Context")
continue;
// mark as optional
if (ftype->initializer_.Length())
scriptType += "=";
params += " * @param {" + scriptType + "} " + ftype->name_ + "\n";
}
String returns;
if (function->GetReturnType())
returns = " * @returns { " + GetScriptType(function->GetReturnType()) + "}\n";
String docString;
if (function->IsConstructor())
{
docString.AppendWithFormat("%s", params.CString());
}
else
{
docString.AppendWithFormat(" * %s\n * @memberof Atomic.%s.prototype\n%s%s\n",
function->GetDocString().CString(),
function->GetClass()->GetName().CString(),
params.CString(),
returns.CString());
}
return docString;
}
void JSBDoc::ExportModuleClasses(JSBModule* module)
{
Vector<SharedPtr<JSBClass>> classes = module->GetClasses();
if (!classes.Size())
return;
source_ += "\n";
for (unsigned i = 0; i < classes.Size(); i++)
{
JSBClass* klass = classes.At(i);
source_ += "/**\n * @class\n* @memberof Atomic\n";
if (klass->GetBaseClass())
source_ += " * @augments Atomic." + klass->GetBaseClass()->GetName()+ "\n";
// PROPERTIES
Vector<String> propertyNames;
klass->GetPropertyNames(propertyNames);
for (unsigned j = 0; j < propertyNames.Size(); j++)
{
JSBProperty* prop = klass->GetProperty(propertyNames[j]);
JSBFunctionType* ftype = NULL;
String desc;
if (prop->getter_ && !prop->getter_->Skip())
{
desc = prop->getter_->GetDocString();
ftype = prop->getter_->GetReturnType();
}
else if (prop->setter_ && !prop->setter_->Skip())
{
ftype = prop->setter_->GetParameters()[0];
}
if (prop->setter_ && prop->setter_->GetDocString().Length())
{
// overwrite getter docstring if it exsists
desc = prop->setter_->GetDocString();
}
if (!ftype)
continue;
String scriptType = GetScriptType(ftype);
String scriptName = prop->GetCasePropertyName();
if (desc.Length())
{
source_ += " * @property {" + scriptType + "} " + scriptName + " - " + desc + "\n";
}
else
{
source_ += " * @property {" + scriptType + "} " + scriptName + "\n";
}
}
JSBFunction* constructor = klass->GetConstructor();
if (constructor)
{
String docs = GenFunctionDoc(constructor);
source_ += docs;
}
source_ += "*/ \nfunction " + klass->GetName() + "() {};\n\n";
// FUNCTIONS
PODVector<JSBFunction*>& functions = klass->GetFunctions();
for (unsigned j = 0; j < functions.Size(); j++)
{
JSBFunction* func = functions[j];
if (func->IsConstructor() || func->IsDestructor() || func->Skip())
continue;
String docs = GenFunctionDoc(func);
String scriptName = func->GetName();
scriptName[0] = tolower(scriptName[0]);
if (scriptName == "delete")
scriptName = "__delete";
String docString;
docString.AppendWithFormat("/**\n %s */\n function %s() {};\n\n",
docs.CString(),
scriptName.CString());
source_ += docString;
}
}
}
void JSBDoc::ExportModuleConstants(JSBModule* module)
{
const Vector<String>& constants = module->GetConstants().Keys();
if (!constants.Size())
return;
source_ += "\n";
for (unsigned i = 0; i < constants.Size(); i++)
{
const String& cname = constants.At(i);
source_ += "/**\n * @memberof Atomic\n * @type {number}\n */\nvar " + cname + ";\n";
}
source_ += "\n";
}
void JSBDoc::ExportModuleEnums(JSBModule* module)
{
Vector<SharedPtr<JSBEnum>> enums = module->GetEnums();
for (unsigned i = 0; i < enums.Size(); i++)
{
JSBEnum* _enum = enums.At(i);
source_ += "/**\n * @memberof Atomic\n * @readonly\n * @enum {number}\n */\n";
source_ += " var " + _enum->GetName() + " = {\n";
Vector<String>& values = _enum->GetValues();
for (unsigned j = 0; j < values.Size(); j++)
{
source_ += " " + values[j] + " : undefined";
if (j != values.Size() - 1)
source_ += ",\n";
}
source_ += "\n\n};\n\n";
}
}
void JSBDoc::WriteToFile(const String &path)
{
File file(package_->GetContext());
file.Open(path, FILE_WRITE);
file.Write(source_.CString(), source_.Length());
file.Close();
}
void JSBDoc::Emit(JSBPackage* package, const String& path)
{
package_ = package;
Vector<SharedPtr<JSBModule>>& modules = package->GetModules();
Begin();
for (unsigned i = 0; i < modules.Size(); i++)
{
ExportModuleEnums(modules[i]);
}
for (unsigned i = 0; i < modules.Size(); i++)
{
ExportModuleConstants(modules[i]);
}
for (unsigned i = 0; i < modules.Size(); i++)
{
source_ += "\n//----------------------------------------------------\n";
source_ += "// MODULE: " + modules[i]->GetName() + "\n";
source_ += "//----------------------------------------------------\n\n";
ExportModuleClasses(modules[i]);
}
End();
WriteToFile(path);
}
}
<|endoftext|> |
<commit_before>#include<iostream>
#include<string>
template<class T>
class Randomizer {
public:
Randomizer(T num1, T num2):_NUM1(num1), _NUM2(num2){}
T getRandom();
private:
T _NUM1, _NUM2;
};
template<class T>
T Randomizer<T>::getRandom() {
return(rand() % _NUM1 + _NUM2);
}
int main() {
/*Randomizer Code:
**Question : <http://stackoverflow.com/questions/37092913/if-vs-ifndef-vs-ifdef?noredirect=1>
**01101110 or 110 = πάντα ῥεῖ
**01101011 or 107 = tobi303*/
std::string str;
std::string winner;
Randomizer<long> randomCode(01101110, 01101011);
long randomNumber = randomCode.getRandom();
std::cout << "RANDOM NUMBER" << randomNumber << std::endl;
switch (randomNumber) {
case 01101110:
winner = "πάντα ῥεῖ";
std::cout << "WINNER IS " << winner;
break;
case 01101011:
winner = "tobi303";
std::cout << "WINNER IS " << winner;
break;
default:
if (randomNumber > 5000) {
winner = "πάντα ῥεῖ";
std::cout << "WINNER IS " << winner;
}
else {
winner = "tobi303";
std::cout << "WINNER IS " << winner;
}
}
std::cin >> str;
}
<commit_msg>Cleaning Up. Getting Ready for 1.1 Release<commit_after><|endoftext|> |
<commit_before>// This code is part of the Super Play Library (http://www.superplay.info),
// and may only be used under the terms contained in the LICENSE file,
// included with the Super Play Library.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
#include <TinySTL/stdint.h>
#include <math.h>
#include <stdlib.h>
#include "Utilities.h"
NAMESPACE(SPlay)
double Utilities::log2(double _fValue)
{
#ifdef WIN32
return log(_fValue) / log(2.0);
#else
return ::log2(_fValue);
#endif
}
int Utilities::getHash(const tinystl::string& _strString)
{
uint32_t iHash = 5381;
int t_c = static_cast<int>(_strString.size());
for (int iLoop = 0; iLoop < t_c; ++iLoop)
{
iHash = ((iHash << 5) + iHash) + _strString[iLoop];
}
return iHash;
}
int Utilities::convertStringToInt(const tinystl::string& _strString)
{
return static_cast<int>(strtol(_strString.c_str(), NULL, 0));
}
ENDNAMESPACE
<commit_msg>ANDROID log2 issue<commit_after>// This code is part of the Super Play Library (http://www.superplay.info),
// and may only be used under the terms contained in the LICENSE file,
// included with the Super Play Library.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
#include <TinySTL/stdint.h>
#include <math.h>
#include <stdlib.h>
#include "Utilities.h"
NAMESPACE(SPlay)
double Utilities::log2(double _fValue)
{
#if defined __linux__ && !defined ANDROID
return ::log2(_fValue);
#else
return log(_fValue) / log(2.0);
#endif
}
int Utilities::getHash(const tinystl::string& _strString)
{
uint32_t iHash = 5381;
int t_c = static_cast<int>(_strString.size());
for (int iLoop = 0; iLoop < t_c; ++iLoop)
{
iHash = ((iHash << 5) + iHash) + _strString[iLoop];
}
return iHash;
}
int Utilities::convertStringToInt(const tinystl::string& _strString)
{
return static_cast<int>(strtol(_strString.c_str(), NULL, 0));
}
ENDNAMESPACE
<|endoftext|> |
<commit_before>#include "Math/GenVector/Transform3D.h"
#include "Math/Math_vectypes.hxx"
#include "RandomNumberEngine.h"
#include "benchmark/benchmark.h"
template <typename T>
using Point = ROOT::Math::PositionVector3D<ROOT::Math::Cartesian3D<T>, ROOT::Math::DefaultCoordinateSystemTag>;
template <typename T>
using Vector = ROOT::Math::DisplacementVector3D<ROOT::Math::Cartesian3D<T>, ROOT::Math::DefaultCoordinateSystemTag>;
template <typename T>
using Plane = ROOT::Math::Impl::Plane3D<T>;
Point<T> sp1(p_x(ggen), p_y(ggen), p_z(ggen));
Point<T> sp2(p_x(ggen), p_y(ggen), p_z(ggen));
Point<T> sp3(p_x(ggen), p_y(ggen), p_z(ggen));
Point<T> sp4(p_x(ggen), p_y(ggen), p_z(ggen));
Point<T> sp5(p_x(ggen), p_y(ggen), p_z(ggen));
Point<T> sp6(p_x(ggen), p_y(ggen), p_z(ggen));
template <typename T>
static void BM_Transform3D(benchmark::State &state)
{
while (state.KeepRunning()) {
ROOT::Math::Impl::Transform3D<T> st(sp1, sp2, sp3, sp4, sp5, sp6);
st.Translation();
}
}
// BENCHMARK_TEMPLATE(BM_Transform3D, double)->Range(8, 8<<10)->Complexity(benchmark::o1);
// BENCHMARK_TEMPLATE(BM_Transform3D, float)->Range(8, 8<<10)->Complexity(benchmark::o1);
// BENCHMARK_TEMPLATE(BM_Transform3D, ROOT::Double_v)->Range(8, 8<<10)->Complexity(benchmark::o1);
// BENCHMARK_TEMPLATE(BM_Transform3D, ROOT::Float_v)->Range(8, 8<<10)->Complexity(benchmark::o1);
template <typename T>
using Point = ROOT::Math::PositionVector3D<ROOT::Math::Cartesian3D<T>, ROOT::Math::DefaultCoordinateSystemTag>;
template <typename T>
static void BM_Point3D(benchmark::State &state)
{
while (state.KeepRunning()) Point<T> sp1, sp2, sp3, sp4, sp5, sp6;
}
BENCHMARK_TEMPLATE(BM_Point3D, double)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Point3D, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
template <typename T>
static void BM_Point3D_Gen(benchmark::State &state)
{
while (state.KeepRunning()) {
Point<T> sp1(p_x(ggen), p_y(ggen), p_z(ggen));
}
}
BENCHMARK_TEMPLATE(BM_Point3D_Gen, double)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Point3D_Gen, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
template <typename T>
static void BM_Plane3D(benchmark::State &state)
{
const double a(p0(ggen)), b(p1(ggen)), c(p2(ggen)), d(p3(ggen));
while (state.KeepRunning()) {
Plane<T> sc_plane(a, b, c, d);
}
}
BENCHMARK_TEMPLATE(BM_Plane3D, double)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Plane3D, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Plane3D, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
template <typename T>
static void BM_Plane3D_Hessian(benchmark::State &state)
{
const double a(p0(ggen)), b(p1(ggen)), c(p2(ggen)), d(p3(ggen));
while (state.KeepRunning()) {
Plane<T> sc_plane(a, b, c, d);
sc_plane.HesseDistance();
}
}
BENCHMARK_TEMPLATE(BM_Plane3D_Hessian, double)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Plane3D_Hessian, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
template <typename T>
static void BM_Plane3D_Normal(benchmark::State &state)
{
const double a(p0(ggen)), b(p1(ggen)), c(p2(ggen)), d(p3(ggen));
while (state.KeepRunning()) {
Plane<T> sc_plane(a, b, c, d);
sc_plane.Normal();
}
}
BENCHMARK_TEMPLATE(BM_Plane3D_Normal, double)->Range(8, 8 << 10)->Complexity(benchmark::o1);
;
BENCHMARK_TEMPLATE(BM_Plane3D_Normal, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Plane3D_Normal, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
<commit_msg>Enable more benchmarks.<commit_after>#include "Math/GenVector/Transform3D.h"
#include "Math/Math_vectypes.hxx"
#include "RandomNumberEngine.h"
#include "benchmark/benchmark.h"
template <typename T>
using Point = ROOT::Math::PositionVector3D<ROOT::Math::Cartesian3D<T>, ROOT::Math::DefaultCoordinateSystemTag>;
template <typename T>
using Vector = ROOT::Math::DisplacementVector3D<ROOT::Math::Cartesian3D<T>, ROOT::Math::DefaultCoordinateSystemTag>;
template <typename T>
using Plane = ROOT::Math::Impl::Plane3D<T>;
Point<T> sp1(p_x(ggen), p_y(ggen), p_z(ggen));
Point<T> sp2(p_x(ggen), p_y(ggen), p_z(ggen));
Point<T> sp3(p_x(ggen), p_y(ggen), p_z(ggen));
Point<T> sp4(p_x(ggen), p_y(ggen), p_z(ggen));
Point<T> sp5(p_x(ggen), p_y(ggen), p_z(ggen));
Point<T> sp6(p_x(ggen), p_y(ggen), p_z(ggen));
template <typename T>
static void BM_Transform3D(benchmark::State &state)
{
while (state.KeepRunning()) {
ROOT::Math::Impl::Transform3D<T> st(sp1, sp2, sp3, sp4, sp5, sp6);
st.Translation();
}
}
BENCHMARK_TEMPLATE(BM_Transform3D, double)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Transform3D, float)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Transform3D, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Transform3D, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
template <typename T>
using Point = ROOT::Math::PositionVector3D<ROOT::Math::Cartesian3D<T>, ROOT::Math::DefaultCoordinateSystemTag>;
template <typename T>
static void BM_Point3D(benchmark::State &state)
{
while (state.KeepRunning()) Point<T> sp1, sp2, sp3, sp4, sp5, sp6;
}
BENCHMARK_TEMPLATE(BM_Point3D, double)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Point3D, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
template <typename T>
static void BM_Point3D_Gen(benchmark::State &state)
{
while (state.KeepRunning()) {
Point<T> sp1(p_x(ggen), p_y(ggen), p_z(ggen));
}
}
BENCHMARK_TEMPLATE(BM_Point3D_Gen, double)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Point3D_Gen, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
template <typename T>
static void BM_Plane3D(benchmark::State &state)
{
const double a(p0(ggen)), b(p1(ggen)), c(p2(ggen)), d(p3(ggen));
while (state.KeepRunning()) {
Plane<T> sc_plane(a, b, c, d);
}
}
BENCHMARK_TEMPLATE(BM_Plane3D, double)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Plane3D, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Plane3D, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
template <typename T>
static void BM_Plane3D_Hessian(benchmark::State &state)
{
const double a(p0(ggen)), b(p1(ggen)), c(p2(ggen)), d(p3(ggen));
while (state.KeepRunning()) {
Plane<T> sc_plane(a, b, c, d);
sc_plane.HesseDistance();
}
}
BENCHMARK_TEMPLATE(BM_Plane3D_Hessian, double)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Plane3D_Hessian, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
template <typename T>
static void BM_Plane3D_Normal(benchmark::State &state)
{
const double a(p0(ggen)), b(p1(ggen)), c(p2(ggen)), d(p3(ggen));
while (state.KeepRunning()) {
Plane<T> sc_plane(a, b, c, d);
sc_plane.Normal();
}
}
BENCHMARK_TEMPLATE(BM_Plane3D_Normal, double)->Range(8, 8 << 10)->Complexity(benchmark::o1);
;
BENCHMARK_TEMPLATE(BM_Plane3D_Normal, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
BENCHMARK_TEMPLATE(BM_Plane3D_Normal, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1);
<|endoftext|> |
<commit_before>#include<iostream>
#include<vector>
using namespace std;
int unimodal(vector<int> v){
bool fin=false;
int tamanio=v.size()-1;
int indice=tamanio/2;
while(!fin){
if(v.at(indice-1)<v.at(indice))
if(v.at(indice+1)<v.at(indice))
fin=true;
else
indice+=(tamanio-indice)/2;
else
indice=(tamanio-indice)/2;
}
return indice;
}
int main(){
vector<int> array;
array.push_back(1);
array.push_back(10);
array.push_back(3);
cout << "El vector contiene: " << endl;
for(int i=0; i < array.size(); i++)
cout << array.at(i) << endl;
int valor = unimodal(array);
cout << "Maximo es: " << array.at(valor) << endl;
}
<commit_msg>fernando<commit_after>#include<iostream>
#include<vector>
using namespace std;
int unimodal(vector<int> v){
bool fin=false;
int tamanio=v.size()-1;
int indice=tamanio/2;
int aux;
int contador=0;
while(!fin){
if(v.at(indice-1)<v.at(indice))
if(v.at(indice+1)<v.at(indice))
fin=true;
else
indice+=(tamanio-indice)/2;
else{
aux=tamanio;
tamanio=indice;
indice=(aux-indice)/2;
}
contador++;
}
cout << "El contador es: " << contador << endl;
return indice;
}
int main(){
vector<int> array;
int tamanio=16;
int posicion=9;
for (int i=0, j=0; i<tamanio;i++,j--){
if(i<=posicion)
array.push_back(i);
else
array.push_back(j);
}
cout << "El vector contiene: " << endl;
for(int i=0; i < array.size(); i++)
cout << array.at(i) << endl;
int valor = unimodal(array);
cout << "Maximo es: " << array.at(valor) << endl;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
* University of Southern California,
* Karlsruhe Institute of Technology
* Jan Issac ([email protected])
*
* 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* @date 04/14/2014
* @author Jan Issac ([email protected])
* Max-Planck-Institute for Intelligent Systems, University of Southern California (USC),
* Karlsruhe Institute of Technology (KIT)
*/
#ifndef ONI_VICON_RECORDER_VICON_RECORDER_HPP
#define ONI_VICON_RECORDER_VICON_RECORDER_HPP
#include <iostream>
#include <fstream>
#include <cassert>
#include <ctime>
#include <iomanip>
#include <set>
#include <vector>
#include <boost/thread/shared_mutex.hpp>
#include <vicon_sdk/vicon_client.h>
#include <actionlib/server/simple_action_server.h>
#include <oni_vicon_recorder/ConnectToViconAction.h>
#include <oni_vicon_recorder/VerifyObjectExists.h>
#include <oni_vicon_recorder/ViconObjectPose.h>
#include <oni_vicon_recorder/ViconObjects.h>
#include "oni_vicon_recorder/frame_time_tracker.hpp"
/**
* @class ViconRecorder records a subset of the vicon data
*
* Recorded file format
*
* Each line contains data of a single frame. Each line is build up as follows
*
* - (unsigned int) Recording frame number (starting from zero)
* - (unsigned int) FrameNumber
* - (unsigned int) Output_GetTimecode.Hours;
* - (unsigned int) Output_GetTimecode.Minutes;
* - (unsigned int) Output_GetTimecode.Seconds;
* - (unsigned int) Output_GetTimecode.Frames;
* - (unsigned int) Output_GetTimecode.SubFrame;
* - (TimecodeStandard::Enum) Output_GetTimecode.Standard;
* - (unsigned int) Output_GetTimecode.SubFramesPerFrame;
* - (unsigned int) Output_GetTimecode.UserBits;
*
* - (double) Output_GetSegmentGlobalTranslation.Translation[ 0 ]
* - (double) Output_GetSegmentGlobalTranslation.Translation[ 1 ]
* - (double) Output_GetSegmentGlobalTranslation.Translation[ 2 ]
*
* - (double) Output_GetSegmentGlobalRotationMatrix.Rotation[ 0 ]
* - (double) Output_GetSegmentGlobalRotationMatrix.Rotation[ 1 ]
* - (double) Output_GetSegmentGlobalRotationMatrix.Rotation[ 2 ]
* - (double) Output_GetSegmentGlobalRotationMatrix.Rotation[ 3 ]
* - (double) Output_GetSegmentGlobalRotationMatrix.Rotation[ 4 ]
* - (double) Output_GetSegmentGlobalRotationMatrix.Rotation[ 5 ]
* - (double) Output_GetSegmentGlobalRotationMatrix.Rotation[ 6 ]
* - (double) Output_GetSegmentGlobalRotationMatrix.Rotation[ 7 ]
* - (double) Output_GetSegmentGlobalRotationMatrix.Rotation[ 8 ]
*
* - (double) Output_GetSegmentGlobalRotationQuaternion.Rotation[ 0 ]
* - (double) Output_GetSegmentGlobalRotationQuaternion.Rotation[ 1 ]
* - (double) Output_GetSegmentGlobalRotationQuaternion.Rotation[ 2 ]
* - (double) Output_GetSegmentGlobalRotationQuaternion.Rotation[ 3 ]
*
* - (double) Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 0 ]
* - (double) Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 1 ]
* - (double) Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 2 ]
* "\n"
*/
class ViconRecorderStub
{
public:
ViconRecorderStub(ros::NodeHandle& node_handle,
const std::string& vicon_objects_srv_name,
const std::string& object_verification_srv_name,
const std::string& vicon_frame_srv_name,
int float_precision = 5);
~ViconRecorderStub();
public: /* Action Callbacks */
void connectCB(const oni_vicon_recorder::ConnectToViconGoalConstPtr& goal);
public: /* Service Callbacks */
bool viconObjectsCB(oni_vicon_recorder::ViconObjects::Request& request,
oni_vicon_recorder::ViconObjects::Response& response);
bool objectExistsCB(oni_vicon_recorder::VerifyObjectExists::Request& request,
oni_vicon_recorder::VerifyObjectExists::Response& response);
private:
int float_precision_;
bool connected_;
boost::shared_mutex iteration_mutex_;
std::string hostname_;
std::string multicast_address_;
std::string object_;
bool connect_to_multicast_;
bool multicast_enabled_;
actionlib::SimpleActionServer<
oni_vicon_recorder::ConnectToViconAction> connect_to_vicon_as_;
ros::ServiceServer vicon_objects_srv_;
ros::ServiceServer object_verification_srv_;
};
class ViconRecorder
{
public:
ViconRecorder(
ros::NodeHandle& node_handle,
FrameTimeTracker::Ptr frame_time_tracker,
int float_precision = 5);
~ViconRecorder();
bool startRecording(const std::string& file, const std::string& object_name);
bool stopRecording();
u_int64_t countFrames() const;
bool isRecording() const;
void closeConnection();
std::ofstream& beginRecord(std::ofstream& ofs) const;
std::ofstream& record(std::ofstream& ofs) const;
std::ofstream& endRecord(std::ofstream& ofs) const;
public: /* Action Callbacks */
void connectCB(const oni_vicon_recorder::ConnectToViconGoalConstPtr& goal);
public: /* Service Callbacks */
bool viconObjectsCB(oni_vicon_recorder::ViconObjects::Request& request,
oni_vicon_recorder::ViconObjects::Response& response);
bool objectExistsCB(oni_vicon_recorder::VerifyObjectExists::Request& request,
oni_vicon_recorder::VerifyObjectExists::Response& response);
bool viconObjectPose(oni_vicon_recorder::ViconObjectPose::Request& request,
oni_vicon_recorder::ViconObjectPose::Response& response);
bool waitForFrame(double wait_time_in_sec = 3.);
private:
/**
* @brief getViconObject() Gets the set of defined objects/subjects in the vicon system
*
* @return objects set
*/
std::set<std::string> getViconObjects();
/**
* @brief recordFrame Records current Vicon frame
*/
bool recordFrame();
private:
int float_precision_;
bool connected_;
bool recording_;
u_int64_t frames_;
boost::shared_mutex iteration_mutex_;
std::ofstream ofs_;
std::string object_name_;
std::string hostname_;
std::string multicast_address_;
std::string object_;
bool connect_to_multicast_;
bool multicast_enabled_;
ViconDataStreamSDK::CPP::Client vicon_client_;
actionlib::SimpleActionServer<
oni_vicon_recorder::ConnectToViconAction> connect_to_vicon_as_;
ros::ServiceServer vicon_objects_srv_;
ros::ServiceServer vicon_object_pose_srv_;
ros::ServiceServer object_exists_srv_;
FrameTimeTracker::Ptr frame_time_tracker_;
};
#endif
<commit_msg>Vicon recording format doc updated<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
* University of Southern California,
* Karlsruhe Institute of Technology
* Jan Issac ([email protected])
*
* 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* @date 04/14/2014
* @author Jan Issac ([email protected])
* Max-Planck-Institute for Intelligent Systems, University of Southern California (USC),
* Karlsruhe Institute of Technology (KIT)
*/
#ifndef ONI_VICON_RECORDER_VICON_RECORDER_HPP
#define ONI_VICON_RECORDER_VICON_RECORDER_HPP
#include <iostream>
#include <fstream>
#include <cassert>
#include <ctime>
#include <iomanip>
#include <set>
#include <vector>
#include <boost/thread/shared_mutex.hpp>
#include <vicon_sdk/vicon_client.h>
#include <actionlib/server/simple_action_server.h>
#include <oni_vicon_recorder/ConnectToViconAction.h>
#include <oni_vicon_recorder/VerifyObjectExists.h>
#include <oni_vicon_recorder/ViconObjectPose.h>
#include <oni_vicon_recorder/ViconObjects.h>
#include "oni_vicon_recorder/frame_time_tracker.hpp"
/**
* @class ViconRecorder records a set of the vicon data
*
* Recorded file format
*
* Each line contains data of a single frame. Each line is build up as follows
*
* - (unsigned int) Recording frame number (starting from zero)
* - (unsigned int) FrameNumber
*
* - (double) Output_GetSegmentGlobalTranslation.Translation[ 0 ]
* - (double) Output_GetSegmentGlobalTranslation.Translation[ 1 ]
* - (double) Output_GetSegmentGlobalTranslation.Translation[ 2 ]
*
* - (double) Output_GetSegmentGlobalRotationQuaternion.Rotation[ 0 ]
* - (double) Output_GetSegmentGlobalRotationQuaternion.Rotation[ 1 ]
* - (double) Output_GetSegmentGlobalRotationQuaternion.Rotation[ 2 ]
* - (double) Output_GetSegmentGlobalRotationQuaternion.Rotation[ 3 ]
*
*/
class ViconRecorderStub
{
public:
ViconRecorderStub(ros::NodeHandle& node_handle,
const std::string& vicon_objects_srv_name,
const std::string& object_verification_srv_name,
const std::string& vicon_frame_srv_name,
int float_precision = 5);
~ViconRecorderStub();
public: /* Action Callbacks */
void connectCB(const oni_vicon_recorder::ConnectToViconGoalConstPtr& goal);
public: /* Service Callbacks */
bool viconObjectsCB(oni_vicon_recorder::ViconObjects::Request& request,
oni_vicon_recorder::ViconObjects::Response& response);
bool objectExistsCB(oni_vicon_recorder::VerifyObjectExists::Request& request,
oni_vicon_recorder::VerifyObjectExists::Response& response);
private:
int float_precision_;
bool connected_;
boost::shared_mutex iteration_mutex_;
std::string hostname_;
std::string multicast_address_;
std::string object_;
bool connect_to_multicast_;
bool multicast_enabled_;
actionlib::SimpleActionServer<
oni_vicon_recorder::ConnectToViconAction> connect_to_vicon_as_;
ros::ServiceServer vicon_objects_srv_;
ros::ServiceServer object_verification_srv_;
};
class ViconRecorder
{
public:
ViconRecorder(
ros::NodeHandle& node_handle,
FrameTimeTracker::Ptr frame_time_tracker,
int float_precision = 5);
~ViconRecorder();
bool startRecording(const std::string& file, const std::string& object_name);
bool stopRecording();
u_int64_t countFrames() const;
bool isRecording() const;
void closeConnection();
std::ofstream& beginRecord(std::ofstream& ofs) const;
std::ofstream& record(std::ofstream& ofs) const;
std::ofstream& endRecord(std::ofstream& ofs) const;
public: /* Action Callbacks */
void connectCB(const oni_vicon_recorder::ConnectToViconGoalConstPtr& goal);
public: /* Service Callbacks */
bool viconObjectsCB(oni_vicon_recorder::ViconObjects::Request& request,
oni_vicon_recorder::ViconObjects::Response& response);
bool objectExistsCB(oni_vicon_recorder::VerifyObjectExists::Request& request,
oni_vicon_recorder::VerifyObjectExists::Response& response);
bool viconObjectPose(oni_vicon_recorder::ViconObjectPose::Request& request,
oni_vicon_recorder::ViconObjectPose::Response& response);
bool waitForFrame(double wait_time_in_sec = 3.);
private:
/**
* @brief getViconObject() Gets the set of defined objects/subjects in the vicon system
*
* @return objects set
*/
std::set<std::string> getViconObjects();
/**
* @brief recordFrame Records current Vicon frame
*/
bool recordFrame();
private:
int float_precision_;
bool connected_;
bool recording_;
u_int64_t frames_;
boost::shared_mutex iteration_mutex_;
std::ofstream ofs_;
std::string object_name_;
std::string hostname_;
std::string multicast_address_;
std::string object_;
bool connect_to_multicast_;
bool multicast_enabled_;
ViconDataStreamSDK::CPP::Client vicon_client_;
actionlib::SimpleActionServer<
oni_vicon_recorder::ConnectToViconAction> connect_to_vicon_as_;
ros::ServiceServer vicon_objects_srv_;
ros::ServiceServer vicon_object_pose_srv_;
ros::ServiceServer object_exists_srv_;
FrameTimeTracker::Ptr frame_time_tracker_;
};
#endif
<|endoftext|> |
<commit_before>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2009 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/ClientRegistrar>
#include "TelepathyQt4/client-registrar-internal.h"
#include "TelepathyQt4/_gen/client-registrar.moc.hpp"
#include "TelepathyQt4/_gen/client-registrar-internal.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Account>
#include <TelepathyQt4/Channel>
#include <TelepathyQt4/ChannelRequest>
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/PendingClientOperation>
#include <TelepathyQt4/PendingReady>
namespace Tp
{
ClientAdaptor::ClientAdaptor(const QStringList &interfaces,
QObject *parent)
: QDBusAbstractAdaptor(parent),
mInterfaces(interfaces)
{
}
ClientAdaptor::~ClientAdaptor()
{
}
QHash<QPair<QString, QString>, QList<ClientHandlerAdaptor *> > ClientHandlerAdaptor::mAdaptorsForConnection;
ClientHandlerAdaptor::ClientHandlerAdaptor(const QDBusConnection &bus,
AbstractClientHandler *client,
QObject *parent)
: QDBusAbstractAdaptor(parent),
mBus(bus),
mClient(client)
{
QList<ClientHandlerAdaptor *> &handlerAdaptors =
mAdaptorsForConnection[qMakePair(mBus.name(), mBus.baseService())];
handlerAdaptors.append(this);
}
ClientHandlerAdaptor::~ClientHandlerAdaptor()
{
QPair<QString, QString> busId = qMakePair(mBus.name(), mBus.baseService());
QList<ClientHandlerAdaptor *> &handlerAdaptors =
mAdaptorsForConnection[busId];
handlerAdaptors.removeOne(this);
if (handlerAdaptors.isEmpty()) {
mAdaptorsForConnection.remove(busId);
}
}
void ClientHandlerAdaptor::HandleChannels(const QDBusObjectPath &accountPath,
const QDBusObjectPath &connectionPath,
const Tp::ChannelDetailsList &channelDetailsList,
const Tp::ObjectPathList &requestsSatisfied,
qulonglong userActionTime_t,
const QVariantMap &handlerInfo,
const QDBusMessage &message)
{
debug() << "HandleChannels: account:" << accountPath.path() <<
", connection:" << connectionPath.path();
AccountPtr account = Account::create(mBus,
TELEPATHY_ACCOUNT_MANAGER_BUS_NAME,
accountPath.path());
QString connectionBusName = connectionPath.path().mid(1).replace('/', '.');
ConnectionPtr connection = Connection::create(mBus, connectionBusName,
connectionPath.path());
QList<ChannelPtr> channels;
ChannelPtr channel;
foreach (const ChannelDetails &channelDetails, channelDetailsList) {
channel = Channel::create(connection, channelDetails.channel.path(),
channelDetails.properties);
channels.append(channel);
}
QList<ChannelRequestPtr> channelRequests;
ChannelRequestPtr channelRequest;
foreach (const QDBusObjectPath &path, requestsSatisfied) {
channelRequest = ChannelRequest::create(mBus,
path.path(), QVariantMap());
channelRequests.append(channelRequest);
}
// FIXME See http://bugs.freedesktop.org/show_bug.cgi?id=21690
QDateTime userActionTime;
if (userActionTime_t != 0) {
userActionTime = QDateTime::fromTime_t((uint) userActionTime_t);
}
PendingClientOperation *operation = new PendingClientOperation(mBus,
message, this);
connect(operation,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onOperationFinished(Tp::PendingOperation*)));
mClient->handleChannels(operation, account, connection, channels,
channelRequests, userActionTime, handlerInfo);
mOperations.insert(operation, channels);
}
void ClientHandlerAdaptor::onOperationFinished(PendingOperation *op)
{
if (!op->isError()) {
debug() << "HandleChannels operation finished successfully, "
"updating handled channels";
QList<ChannelPtr> channels =
mOperations.value(dynamic_cast<PendingClientOperation*>(op));
foreach (const ChannelPtr &channel, channels) {
mHandledChannels.insert(channel);
connect(channel.data(),
SIGNAL(invalidated(Tp::DBusProxy *,
const QString &, const QString &)),
SLOT(onChannelInvalidated(Tp::DBusProxy *)));
}
}
mOperations.remove(dynamic_cast<PendingClientOperation*>(op));
}
void ClientHandlerAdaptor::onChannelInvalidated(DBusProxy *proxy)
{
ChannelPtr channel(dynamic_cast<Channel*>(proxy));
mHandledChannels.remove(channel);
}
ClientHandlerRequestsAdaptor::ClientHandlerRequestsAdaptor(
const QDBusConnection &bus,
AbstractClientHandler *client,
QObject *parent)
: QDBusAbstractAdaptor(parent),
mBus(bus),
mClient(client)
{
}
ClientHandlerRequestsAdaptor::~ClientHandlerRequestsAdaptor()
{
}
void ClientHandlerRequestsAdaptor::AddRequest(
const QDBusObjectPath &request,
const QVariantMap &requestProperties,
const QDBusMessage &message)
{
debug() << "AddRequest:" << request.path();
mBus.send(message.createReply());
mClient->addRequest(ChannelRequest::create(mBus,
request.path(), requestProperties));
}
void ClientHandlerRequestsAdaptor::RemoveRequest(
const QDBusObjectPath &request,
const QString &errorName, const QString &errorMessage,
const QDBusMessage &message)
{
debug() << "RemoveRequest:" << request.path() << "-" << errorName
<< "-" << errorMessage;
mBus.send(message.createReply());
mClient->removeRequest(ChannelRequest::create(mBus,
request.path(), QVariantMap()), errorName, errorMessage);
}
struct ClientRegistrar::Private
{
Private(const QDBusConnection &bus)
: bus(bus)
{
}
QDBusConnection bus;
QHash<AbstractClientPtr, QString> clients;
QHash<AbstractClientPtr, QObject*> clientObjects;
QSet<QString> services;
};
QHash<QPair<QString, QString>, ClientRegistrar*> ClientRegistrar::registrarForConnection;
ClientRegistrarPtr ClientRegistrar::create()
{
QDBusConnection bus = QDBusConnection::sessionBus();
return create(bus);
}
ClientRegistrarPtr ClientRegistrar::create(const QDBusConnection &bus)
{
QPair<QString, QString> busId =
qMakePair(bus.name(), bus.baseService());
if (registrarForConnection.contains(busId)) {
return ClientRegistrarPtr(
registrarForConnection.value(busId));
}
return ClientRegistrarPtr(new ClientRegistrar(bus));
}
ClientRegistrar::ClientRegistrar(const QDBusConnection &bus)
: mPriv(new Private(bus))
{
registrarForConnection.insert(qMakePair(bus.name(),
bus.baseService()), this);
}
ClientRegistrar::~ClientRegistrar()
{
registrarForConnection.remove(qMakePair(mPriv->bus.name(),
mPriv->bus.baseService()));
unregisterClients();
delete mPriv;
}
QDBusConnection ClientRegistrar::dbusConnection() const
{
return mPriv->bus;
}
QList<AbstractClientPtr> ClientRegistrar::registeredClients() const
{
return mPriv->clients.keys();
}
bool ClientRegistrar::registerClient(const AbstractClientPtr &client,
const QString &clientName, bool unique)
{
if (!client) {
warning() << "Unable to register a null client";
return false;
}
if (mPriv->clients.contains(client)) {
debug() << "Client already registered";
return true;
}
QString busName = QLatin1String("org.freedesktop.Telepathy.Client.");
busName.append(clientName);
if (unique) {
// o.f.T.Client.<unique_bus_name>_<pointer> should be enough to identify
// an unique identifier
busName.append(QString(".%1._%2")
.arg(mPriv->bus.baseService()
.replace(':', '_')
.replace('.', "._"))
.arg((intptr_t) client.data()));
}
if (mPriv->services.contains(busName) ||
!mPriv->bus.registerService(busName)) {
warning() << "Unable to register client: busName" <<
busName << "already registered";
return false;
}
QObject *object = new QObject(this);
QStringList interfaces;
AbstractClientHandler *handler =
dynamic_cast<AbstractClientHandler*>(client.data());
if (handler) {
// export o.f.T.Client.Handler
new ClientHandlerAdaptor(mPriv->bus, handler, object);
interfaces.append(
QLatin1String("org.freedesktop.Telepathy.Client.Handler"));
if (handler->wantsRequestNotification()) {
// export o.f.T.Client.Interface.Requests
new ClientHandlerRequestsAdaptor(mPriv->bus, handler, object);
interfaces.append(
QLatin1String(
"org.freedesktop.Telepathy.Client.Interface.Requests"));
}
}
// TODO add more adaptors when they exist
if (interfaces.isEmpty()) {
warning() << "Client does not implement any known interface";
// cleanup
mPriv->bus.unregisterService(busName);
return false;
}
// export o.f,T,Client interface
new ClientAdaptor(interfaces, object);
QString objectPath = QString("/%1").arg(busName);
objectPath.replace('.', '/');
if (!mPriv->bus.registerObject(objectPath, object)) {
// this shouldn't happen, but let's make sure
warning() << "Unable to register client: objectPath" <<
objectPath << "already registered";
// cleanup
delete object;
mPriv->bus.unregisterService(busName);
return false;
}
debug() << "Client registered - busName:" << busName <<
"objectPath:" << objectPath << "interfaces:" << interfaces;
mPriv->services.insert(busName);
mPriv->clients.insert(client, objectPath);
mPriv->clientObjects.insert(client, object);
return true;
}
bool ClientRegistrar::unregisterClient(const AbstractClientPtr &client)
{
if (!mPriv->clients.contains(client)) {
warning() << "Trying to unregister an unregistered client";
return false;
}
QString objectPath = mPriv->clients.value(client);
mPriv->bus.unregisterObject(objectPath);
mPriv->clients.remove(client);
QObject *object = mPriv->clientObjects.value(client);
// delete object here and it's children (adaptors), to make sure if adaptor
// is keeping a static list of adaptors per connection, the list is updated.
delete object;
mPriv->clientObjects.remove(client);
QString busName = objectPath.mid(1).replace('/', '.');
mPriv->bus.unregisterService(busName);
mPriv->services.remove(busName);
debug() << "Client unregistered - busName:" << busName <<
"objectPath:" << objectPath;
return true;
}
void ClientRegistrar::unregisterClients()
{
// copy the hash as it will be modified
QHash<AbstractClientPtr, QString> clients = mPriv->clients;
QHash<AbstractClientPtr, QString>::const_iterator end =
clients.constEnd();
QHash<AbstractClientPtr, QString>::const_iterator it =
clients.constBegin();
while (it != end) {
unregisterClient(it.key());
++it;
}
}
} // Tp
<commit_msg>ClientRegistrar: Added docs.<commit_after>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2009 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/ClientRegistrar>
#include "TelepathyQt4/client-registrar-internal.h"
#include "TelepathyQt4/_gen/client-registrar.moc.hpp"
#include "TelepathyQt4/_gen/client-registrar-internal.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Account>
#include <TelepathyQt4/Channel>
#include <TelepathyQt4/ChannelRequest>
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/PendingClientOperation>
#include <TelepathyQt4/PendingReady>
namespace Tp
{
ClientAdaptor::ClientAdaptor(const QStringList &interfaces,
QObject *parent)
: QDBusAbstractAdaptor(parent),
mInterfaces(interfaces)
{
}
ClientAdaptor::~ClientAdaptor()
{
}
QHash<QPair<QString, QString>, QList<ClientHandlerAdaptor *> > ClientHandlerAdaptor::mAdaptorsForConnection;
ClientHandlerAdaptor::ClientHandlerAdaptor(const QDBusConnection &bus,
AbstractClientHandler *client,
QObject *parent)
: QDBusAbstractAdaptor(parent),
mBus(bus),
mClient(client)
{
QList<ClientHandlerAdaptor *> &handlerAdaptors =
mAdaptorsForConnection[qMakePair(mBus.name(), mBus.baseService())];
handlerAdaptors.append(this);
}
ClientHandlerAdaptor::~ClientHandlerAdaptor()
{
QPair<QString, QString> busId = qMakePair(mBus.name(), mBus.baseService());
QList<ClientHandlerAdaptor *> &handlerAdaptors =
mAdaptorsForConnection[busId];
handlerAdaptors.removeOne(this);
if (handlerAdaptors.isEmpty()) {
mAdaptorsForConnection.remove(busId);
}
}
void ClientHandlerAdaptor::HandleChannels(const QDBusObjectPath &accountPath,
const QDBusObjectPath &connectionPath,
const Tp::ChannelDetailsList &channelDetailsList,
const Tp::ObjectPathList &requestsSatisfied,
qulonglong userActionTime_t,
const QVariantMap &handlerInfo,
const QDBusMessage &message)
{
debug() << "HandleChannels: account:" << accountPath.path() <<
", connection:" << connectionPath.path();
AccountPtr account = Account::create(mBus,
TELEPATHY_ACCOUNT_MANAGER_BUS_NAME,
accountPath.path());
QString connectionBusName = connectionPath.path().mid(1).replace('/', '.');
ConnectionPtr connection = Connection::create(mBus, connectionBusName,
connectionPath.path());
QList<ChannelPtr> channels;
ChannelPtr channel;
foreach (const ChannelDetails &channelDetails, channelDetailsList) {
channel = Channel::create(connection, channelDetails.channel.path(),
channelDetails.properties);
channels.append(channel);
}
QList<ChannelRequestPtr> channelRequests;
ChannelRequestPtr channelRequest;
foreach (const QDBusObjectPath &path, requestsSatisfied) {
channelRequest = ChannelRequest::create(mBus,
path.path(), QVariantMap());
channelRequests.append(channelRequest);
}
// FIXME See http://bugs.freedesktop.org/show_bug.cgi?id=21690
QDateTime userActionTime;
if (userActionTime_t != 0) {
userActionTime = QDateTime::fromTime_t((uint) userActionTime_t);
}
PendingClientOperation *operation = new PendingClientOperation(mBus,
message, this);
connect(operation,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onOperationFinished(Tp::PendingOperation*)));
mClient->handleChannels(operation, account, connection, channels,
channelRequests, userActionTime, handlerInfo);
mOperations.insert(operation, channels);
}
void ClientHandlerAdaptor::onOperationFinished(PendingOperation *op)
{
if (!op->isError()) {
debug() << "HandleChannels operation finished successfully, "
"updating handled channels";
QList<ChannelPtr> channels =
mOperations.value(dynamic_cast<PendingClientOperation*>(op));
foreach (const ChannelPtr &channel, channels) {
mHandledChannels.insert(channel);
connect(channel.data(),
SIGNAL(invalidated(Tp::DBusProxy *,
const QString &, const QString &)),
SLOT(onChannelInvalidated(Tp::DBusProxy *)));
}
}
mOperations.remove(dynamic_cast<PendingClientOperation*>(op));
}
void ClientHandlerAdaptor::onChannelInvalidated(DBusProxy *proxy)
{
ChannelPtr channel(dynamic_cast<Channel*>(proxy));
mHandledChannels.remove(channel);
}
ClientHandlerRequestsAdaptor::ClientHandlerRequestsAdaptor(
const QDBusConnection &bus,
AbstractClientHandler *client,
QObject *parent)
: QDBusAbstractAdaptor(parent),
mBus(bus),
mClient(client)
{
}
ClientHandlerRequestsAdaptor::~ClientHandlerRequestsAdaptor()
{
}
void ClientHandlerRequestsAdaptor::AddRequest(
const QDBusObjectPath &request,
const QVariantMap &requestProperties,
const QDBusMessage &message)
{
debug() << "AddRequest:" << request.path();
mBus.send(message.createReply());
mClient->addRequest(ChannelRequest::create(mBus,
request.path(), requestProperties));
}
void ClientHandlerRequestsAdaptor::RemoveRequest(
const QDBusObjectPath &request,
const QString &errorName, const QString &errorMessage,
const QDBusMessage &message)
{
debug() << "RemoveRequest:" << request.path() << "-" << errorName
<< "-" << errorMessage;
mBus.send(message.createReply());
mClient->removeRequest(ChannelRequest::create(mBus,
request.path(), QVariantMap()), errorName, errorMessage);
}
struct ClientRegistrar::Private
{
Private(const QDBusConnection &bus)
: bus(bus)
{
}
QDBusConnection bus;
QHash<AbstractClientPtr, QString> clients;
QHash<AbstractClientPtr, QObject*> clientObjects;
QSet<QString> services;
};
/**
* \class ClientRegistrar
* \ingroup clientclient
* \headerfile <TelepathyQt4/client-registrar.h> <TelepathyQt4/ClientRegistrar>
*
* Object responsible for registering
* <a href="http://telepathy.freedesktop.org">Telepathy</a>
* clients (Observer, Approver, Handler).
*
* Clients should inherit AbstractClientObserver, AbstractClientApprover,
* AbstractClientHandler or some combination of these, by using multiple
* inheritance, and register themselves using registerClient().
*
* See the individual classes descriptions for more details.
*
* \section usage_sec Usage
*
* \subsection create_sec Creating a client registrar object
*
* One way to create a ClientRegistrar object is to just call the create method.
* For example:
*
* \code ClientRegistrarPtr cr = ClientRegistrar::create(); \endcode
*
* You can also provide a D-Bus connection as a QDBusConnection:
*
* \code ClientRegistrarPtr cr = ClientRegistrar::create(QDBusConnection::sessionBus()); \endcode
*
* \subsection registering_sec Registering a client
*
* To register a client, just call registerClient with a given AbstractClientPtr
* pointing to a valid AbstractClient instance.
*
* \code
*
* class MyClient : public AbstractClientObserver, public AbstractClientHandler
* {
* ...
* };
*
* ...
*
* ClientRegistrarPtr cr = ClientRegistrar::create();
* SharedPtr<MyClient> client = SharedPtr<MyClient>(new MyClient(...));
* cr->registerClient(AbstractClientPtr::dynamicCast(client), "myclient");
*
* \endcode
*
* \sa AbstractClientObserver, AbstractClientApprover, AbstractClientHandler
*/
QHash<QPair<QString, QString>, ClientRegistrar*> ClientRegistrar::registrarForConnection;
/**
* Create a new client registrar object using QDBusConnection::sessionBus().
*
* ClientRegistrar instances are unique per D-Bus connection. The returned
* ClientRegistrarPtr will point to the same ClientRegistrar instance on
* successive calls, unless the instance had already been destroyed, in which
* case a new instance will be returned.
*
* \return A ClientRegistrarPtr object pointing to the ClientRegistrar.
*/
ClientRegistrarPtr ClientRegistrar::create()
{
QDBusConnection bus = QDBusConnection::sessionBus();
return create(bus);
}
/**
* Create a new client registrar object using the given \a bus.
*
* ClientRegistrar instances are unique per D-Bus connection. The returned
* ClientRegistrarPtr will point to the same ClientRegistrar instance on
* successive calls with the same \a bus, unless the instance
* had already been destroyed, in which case a new instance will be returned.
*
* \param bus QDBusConnection to use.
* \return A ClientRegistrarPtr object pointing to the ClientRegistrar.
*/
ClientRegistrarPtr ClientRegistrar::create(const QDBusConnection &bus)
{
QPair<QString, QString> busId =
qMakePair(bus.name(), bus.baseService());
if (registrarForConnection.contains(busId)) {
return ClientRegistrarPtr(
registrarForConnection.value(busId));
}
return ClientRegistrarPtr(new ClientRegistrar(bus));
}
/**
* Construct a new client registrar object using the given \a bus.
*
* \param bus QDBusConnection to use.
*/
ClientRegistrar::ClientRegistrar(const QDBusConnection &bus)
: mPriv(new Private(bus))
{
registrarForConnection.insert(qMakePair(bus.name(),
bus.baseService()), this);
}
/**
* Class destructor.
*/
ClientRegistrar::~ClientRegistrar()
{
registrarForConnection.remove(qMakePair(mPriv->bus.name(),
mPriv->bus.baseService()));
unregisterClients();
delete mPriv;
}
/**
* Return the D-Bus connection being used by this client registrar.
*
* \return QDBusConnection being used.
*/
QDBusConnection ClientRegistrar::dbusConnection() const
{
return mPriv->bus;
}
/**
* Return a list of clients registered using registerClient on this client registrar.
*
* \return A list of registered clients.
* \sa registerClient()
*/
QList<AbstractClientPtr> ClientRegistrar::registeredClients() const
{
return mPriv->clients.keys();
}
/**
* Register a client on D-Bus.
*
* The client registrar will be responsible for proper exporting the client
* D-Bus interfaces, based on inheritance.
*
* If each of a client instance should be able to manipulate channels
* separately, set unique to true.
*
* The client name MUST be a non-empty string of ASCII digits, letters, dots
* and/or underscores, starting with a letter, and without sets of
* two consecutive dots or a dot followed by a digit.
*
* This method will do nothing if the client is already registered, and \c true
* will be returned.
*
* To unregister a client use unregisterClient().
*
* \param client The client to register.
* \param clientName The client name used to register.
* \param unique Whether each of a client instance is able to manipulate
* channels separately.
* \return \c true if client was successfully registered, \c false otherwise.
* \sa registeredClients(), unregisterClient()
*/
bool ClientRegistrar::registerClient(const AbstractClientPtr &client,
const QString &clientName, bool unique)
{
if (!client) {
warning() << "Unable to register a null client";
return false;
}
if (mPriv->clients.contains(client)) {
debug() << "Client already registered";
return true;
}
QString busName = QLatin1String("org.freedesktop.Telepathy.Client.");
busName.append(clientName);
if (unique) {
// o.f.T.Client.<unique_bus_name>_<pointer> should be enough to identify
// an unique identifier
busName.append(QString(".%1._%2")
.arg(mPriv->bus.baseService()
.replace(':', '_')
.replace('.', "._"))
.arg((intptr_t) client.data()));
}
if (mPriv->services.contains(busName) ||
!mPriv->bus.registerService(busName)) {
warning() << "Unable to register client: busName" <<
busName << "already registered";
return false;
}
QObject *object = new QObject(this);
QStringList interfaces;
AbstractClientHandler *handler =
dynamic_cast<AbstractClientHandler*>(client.data());
if (handler) {
// export o.f.T.Client.Handler
new ClientHandlerAdaptor(mPriv->bus, handler, object);
interfaces.append(
QLatin1String("org.freedesktop.Telepathy.Client.Handler"));
if (handler->wantsRequestNotification()) {
// export o.f.T.Client.Interface.Requests
new ClientHandlerRequestsAdaptor(mPriv->bus, handler, object);
interfaces.append(
QLatin1String(
"org.freedesktop.Telepathy.Client.Interface.Requests"));
}
}
// TODO add more adaptors when they exist
if (interfaces.isEmpty()) {
warning() << "Client does not implement any known interface";
// cleanup
mPriv->bus.unregisterService(busName);
return false;
}
// export o.f,T,Client interface
new ClientAdaptor(interfaces, object);
QString objectPath = QString("/%1").arg(busName);
objectPath.replace('.', '/');
if (!mPriv->bus.registerObject(objectPath, object)) {
// this shouldn't happen, but let's make sure
warning() << "Unable to register client: objectPath" <<
objectPath << "already registered";
// cleanup
delete object;
mPriv->bus.unregisterService(busName);
return false;
}
debug() << "Client registered - busName:" << busName <<
"objectPath:" << objectPath << "interfaces:" << interfaces;
mPriv->services.insert(busName);
mPriv->clients.insert(client, objectPath);
mPriv->clientObjects.insert(client, object);
return true;
}
/**
* Unregister a client registered using registerClient on this client registrar.
*
* If \a client was not registered previously, \c false will be returned.
*
* \param client The client to unregister.
* \return \c true if client was successfully unregistered, \c false otherwise.
* \sa registeredClients(), registerClient()
*/
bool ClientRegistrar::unregisterClient(const AbstractClientPtr &client)
{
if (!mPriv->clients.contains(client)) {
warning() << "Trying to unregister an unregistered client";
return false;
}
QString objectPath = mPriv->clients.value(client);
mPriv->bus.unregisterObject(objectPath);
mPriv->clients.remove(client);
QObject *object = mPriv->clientObjects.value(client);
// delete object here and it's children (adaptors), to make sure if adaptor
// is keeping a static list of adaptors per connection, the list is updated.
delete object;
mPriv->clientObjects.remove(client);
QString busName = objectPath.mid(1).replace('/', '.');
mPriv->bus.unregisterService(busName);
mPriv->services.remove(busName);
debug() << "Client unregistered - busName:" << busName <<
"objectPath:" << objectPath;
return true;
}
/**
* Unregister all clients registered using registerClient on this client registrar.
*
* \sa registeredClients(), registerClient(), unregisterClient()
*/
void ClientRegistrar::unregisterClients()
{
// copy the hash as it will be modified
QHash<AbstractClientPtr, QString> clients = mPriv->clients;
QHash<AbstractClientPtr, QString>::const_iterator end =
clients.constEnd();
QHash<AbstractClientPtr, QString>::const_iterator it =
clients.constBegin();
while (it != end) {
unregisterClient(it.key());
++it;
}
}
} // Tp
<|endoftext|> |
<commit_before>#include "browser/views/inspectable_web_contents_view_views.h"
#include "browser/inspectable_web_contents_impl.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
namespace brightray {
namespace {
class DevToolsWindowDelegate : public views::ClientView,
public views::WidgetDelegate {
public:
DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
views::View* view,
views::Widget* widget)
: views::ClientView(widget_, view),
shell_(shell),
view_(view),
widget_(widget),
title_(base::ASCIIToUTF16("Developer Tools")) {
// A WidgetDelegate should be deleted on DeleteDelegate.
set_owned_by_client();
}
virtual ~DevToolsWindowDelegate() {}
// views::WidgetDelegate:
virtual void DeleteDelegate() OVERRIDE { delete this; }
virtual views::View* GetInitiallyFocusedView() OVERRIDE { return view_; }
virtual bool CanResize() const OVERRIDE { return true; }
virtual bool CanMaximize() const OVERRIDE { return false; }
virtual base::string16 GetWindowTitle() const OVERRIDE { return title_; }
virtual views::Widget* GetWidget() OVERRIDE { return widget_; }
virtual const views::Widget* GetWidget() const OVERRIDE { return widget_; }
virtual views::View* GetContentsView() OVERRIDE { return view_; }
virtual views::ClientView* CreateClientView(views::Widget* widget) { return this; }
// views::ClientView:
virtual bool CanClose() OVERRIDE {
shell_->inspectable_web_contents()->CloseDevTools();
return false;
}
private:
InspectableWebContentsViewViews* shell_;
views::View* view_;
views::Widget* widget_;
base::string16 title_;
DISALLOW_COPY_AND_ASSIGN(DevToolsWindowDelegate);
};
} // namespace
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContentsImpl* inspectable_web_contents) {
return new InspectableWebContentsViewViews(inspectable_web_contents);
}
InspectableWebContentsViewViews::InspectableWebContentsViewViews(
InspectableWebContentsImpl* inspectable_web_contents)
: inspectable_web_contents_(inspectable_web_contents),
devtools_window_web_view_(NULL),
contents_web_view_(new views::WebView(NULL)),
devtools_web_view_(new views::WebView(NULL)),
devtools_visible_(false) {
set_owned_by_client();
devtools_web_view_->SetVisible(false);
contents_web_view_->SetWebContents(inspectable_web_contents_->GetWebContents());
AddChildView(devtools_web_view_);
AddChildView(contents_web_view_);
}
InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
if (devtools_window_)
inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
}
views::View* InspectableWebContentsViewViews::GetView() {
return this;
}
views::View* InspectableWebContentsViewViews::GetWebView() {
return contents_web_view_;
}
void InspectableWebContentsViewViews::ShowDevTools() {
if (devtools_visible_)
return;
devtools_visible_ = true;
if (devtools_window_) {
devtools_window_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
devtools_window_->SetBounds(inspectable_web_contents()->GetDevToolsBounds());
devtools_window_->Show();
} else {
devtools_web_view_->SetVisible(true);
devtools_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
devtools_web_view_->RequestFocus();
Layout();
}
}
void InspectableWebContentsViewViews::CloseDevTools() {
if (!devtools_visible_)
return;
devtools_visible_ = false;
if (devtools_window_) {
inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
devtools_window_.reset();
devtools_window_web_view_ = NULL;
} else {
devtools_web_view_->SetVisible(false);
devtools_web_view_->SetWebContents(NULL);
Layout();
}
}
bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
return devtools_visible_;
}
void InspectableWebContentsViewViews::SetIsDocked(bool docked) {
CloseDevTools();
if (!docked) {
devtools_window_.reset(new views::Widget);
devtools_window_web_view_ = new views::WebView(NULL);
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.delegate = new DevToolsWindowDelegate(this,
devtools_window_web_view_,
devtools_window_.get());
params.top_level = true;
params.remove_standard_frame = true;
devtools_window_->Init(params);
}
ShowDevTools();
}
void InspectableWebContentsViewViews::SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) {
strategy_.CopyFrom(strategy);
Layout();
}
void InspectableWebContentsViewViews::Layout() {
if (!devtools_web_view_->visible()) {
contents_web_view_->SetBoundsRect(GetContentsBounds());
return;
}
gfx::Size container_size(width(), height());
gfx::Rect old_devtools_bounds(devtools_web_view_->bounds());
gfx::Rect old_contents_bounds(contents_web_view_->bounds());
gfx::Rect new_devtools_bounds;
gfx::Rect new_contents_bounds;
ApplyDevToolsContentsResizingStrategy(strategy_, container_size,
old_devtools_bounds, old_contents_bounds,
&new_devtools_bounds, &new_contents_bounds);
// DevTools cares about the specific position, so we have to compensate RTL
// layout here.
new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));
devtools_web_view_->SetBoundsRect(new_devtools_bounds);
contents_web_view_->SetBoundsRect(new_contents_bounds);
}
} // namespace brightray
<commit_msg>win: Fix window frame on detached window.<commit_after>#include "browser/views/inspectable_web_contents_view_views.h"
#include "browser/inspectable_web_contents_impl.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
namespace brightray {
namespace {
class DevToolsWindowDelegate : public views::ClientView,
public views::WidgetDelegate {
public:
DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
views::View* view,
views::Widget* widget)
: views::ClientView(widget_, view),
shell_(shell),
view_(view),
widget_(widget),
title_(base::ASCIIToUTF16("Developer Tools")) {
// A WidgetDelegate should be deleted on DeleteDelegate.
set_owned_by_client();
}
virtual ~DevToolsWindowDelegate() {}
// views::WidgetDelegate:
virtual void DeleteDelegate() OVERRIDE { delete this; }
virtual views::View* GetInitiallyFocusedView() OVERRIDE { return view_; }
virtual bool CanResize() const OVERRIDE { return true; }
virtual bool CanMaximize() const OVERRIDE { return false; }
virtual base::string16 GetWindowTitle() const OVERRIDE { return title_; }
virtual views::Widget* GetWidget() OVERRIDE { return widget_; }
virtual const views::Widget* GetWidget() const OVERRIDE { return widget_; }
virtual views::View* GetContentsView() OVERRIDE { return view_; }
virtual views::ClientView* CreateClientView(views::Widget* widget) { return this; }
// views::ClientView:
virtual bool CanClose() OVERRIDE {
shell_->inspectable_web_contents()->CloseDevTools();
return false;
}
private:
InspectableWebContentsViewViews* shell_;
views::View* view_;
views::Widget* widget_;
base::string16 title_;
DISALLOW_COPY_AND_ASSIGN(DevToolsWindowDelegate);
};
} // namespace
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContentsImpl* inspectable_web_contents) {
return new InspectableWebContentsViewViews(inspectable_web_contents);
}
InspectableWebContentsViewViews::InspectableWebContentsViewViews(
InspectableWebContentsImpl* inspectable_web_contents)
: inspectable_web_contents_(inspectable_web_contents),
devtools_window_web_view_(NULL),
contents_web_view_(new views::WebView(NULL)),
devtools_web_view_(new views::WebView(NULL)),
devtools_visible_(false) {
set_owned_by_client();
devtools_web_view_->SetVisible(false);
contents_web_view_->SetWebContents(inspectable_web_contents_->GetWebContents());
AddChildView(devtools_web_view_);
AddChildView(contents_web_view_);
}
InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
if (devtools_window_)
inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
}
views::View* InspectableWebContentsViewViews::GetView() {
return this;
}
views::View* InspectableWebContentsViewViews::GetWebView() {
return contents_web_view_;
}
void InspectableWebContentsViewViews::ShowDevTools() {
if (devtools_visible_)
return;
devtools_visible_ = true;
if (devtools_window_) {
devtools_window_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
devtools_window_->SetBounds(inspectable_web_contents()->GetDevToolsBounds());
devtools_window_->Show();
} else {
devtools_web_view_->SetVisible(true);
devtools_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
devtools_web_view_->RequestFocus();
Layout();
}
}
void InspectableWebContentsViewViews::CloseDevTools() {
if (!devtools_visible_)
return;
devtools_visible_ = false;
if (devtools_window_) {
inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
devtools_window_.reset();
devtools_window_web_view_ = NULL;
} else {
devtools_web_view_->SetVisible(false);
devtools_web_view_->SetWebContents(NULL);
Layout();
}
}
bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
return devtools_visible_;
}
void InspectableWebContentsViewViews::SetIsDocked(bool docked) {
CloseDevTools();
if (!docked) {
devtools_window_.reset(new views::Widget);
devtools_window_web_view_ = new views::WebView(NULL);
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.delegate = new DevToolsWindowDelegate(this,
devtools_window_web_view_,
devtools_window_.get());
params.top_level = true;
params.bounds = inspectable_web_contents()->GetDevToolsBounds();
#if defined(USE_X11)
// In X11 the window frame is drawn by the application.
params.remove_standard_frame = true;
#endif
devtools_window_->Init(params);
}
ShowDevTools();
}
void InspectableWebContentsViewViews::SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) {
strategy_.CopyFrom(strategy);
Layout();
}
void InspectableWebContentsViewViews::Layout() {
if (!devtools_web_view_->visible()) {
contents_web_view_->SetBoundsRect(GetContentsBounds());
return;
}
gfx::Size container_size(width(), height());
gfx::Rect old_devtools_bounds(devtools_web_view_->bounds());
gfx::Rect old_contents_bounds(contents_web_view_->bounds());
gfx::Rect new_devtools_bounds;
gfx::Rect new_contents_bounds;
ApplyDevToolsContentsResizingStrategy(strategy_, container_size,
old_devtools_bounds, old_contents_bounds,
&new_devtools_bounds, &new_contents_bounds);
// DevTools cares about the specific position, so we have to compensate RTL
// layout here.
new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));
devtools_web_view_->SetBoundsRect(new_devtools_bounds);
contents_web_view_->SetBoundsRect(new_contents_bounds);
}
} // namespace brightray
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <type_traits>
#include <random>
#include <algorithm>
#include <functional>
#include <limits>
#include <type_traits>
#include <af/array.h>
#include <af/dim4.hpp>
#include <af/defines.h>
#include <Array.hpp>
#include <random.hpp>
namespace cpu
{
using namespace std;
template<typename T>
using is_arithmetic_t = typename enable_if< is_arithmetic<T>::value, function<T()>>::type;
template<typename T>
using is_complex_t = typename enable_if< is_complex<T>::value, function<T()>>::type;
template<typename T>
using is_floating_point_t = typename enable_if< is_floating_point<T>::value, function<T()>>::type;
template<typename T, typename GenType>
is_arithmetic_t<T>
urand(GenType &generator)
{
typedef typename conditional< is_floating_point<T>::value,
uniform_real_distribution<T>,
#if OS_WIN
uniform_int_distribution<unsigned>>::type dist;
#else
uniform_int_distribution<T >> ::type dist;
#endif
return bind(dist(), generator);
}
template<typename T, typename GenType>
is_complex_t<T>
urand(GenType &generator)
{
auto func = urand<typename T::value_type>(generator);
return [func] () { return T(func(), func());};
}
template<typename T, typename GenType>
is_floating_point_t<T>
nrand(GenType &generator)
{
return bind(normal_distribution<T>(), generator);
}
template<typename T, typename GenType>
is_complex_t<T>
nrand(GenType &generator)
{
auto func = nrand<typename T::value_type>(generator);
return [func] () { return T(func(), func());};
}
static default_random_engine generator;
static unsigned long long gen_seed = 0;
static bool is_first = true;
#define GLOBAL 1
template<typename T>
Array<T> randn(const af::dim4 &dims)
{
static unsigned long long my_seed = 0;
if (is_first) {
setSeed(gen_seed);
my_seed = gen_seed;
}
static auto gen = nrand<T>(generator);
if (my_seed != gen_seed) {
gen = nrand<T>(generator);
my_seed = gen_seed;
}
Array<T> outArray = createEmptyArray<T>(dims);
T *outPtr = outArray.get();
for (int i = 0; i < (int)outArray.elements(); i++) {
outPtr[i] = gen();
}
return outArray;
}
template<typename T>
Array<T> randu(const af::dim4 &dims)
{
static unsigned long long my_seed = 0;
if (is_first) {
setSeed(gen_seed);
my_seed = gen_seed;
}
static auto gen = urand<T>(generator);
if (my_seed != gen_seed) {
gen = urand<T>(generator);
my_seed = gen_seed;
}
Array<T> outArray = createEmptyArray<T>(dims);
T *outPtr = outArray.get();
for (int i = 0; i < (int)outArray.elements(); i++) {
outPtr[i] = gen();
}
return outArray;
}
#define INSTANTIATE_UNIFORM(T) \
template Array<T> randu<T> (const af::dim4 &dims);
INSTANTIATE_UNIFORM(float)
INSTANTIATE_UNIFORM(double)
INSTANTIATE_UNIFORM(cfloat)
INSTANTIATE_UNIFORM(cdouble)
INSTANTIATE_UNIFORM(int)
INSTANTIATE_UNIFORM(uint)
INSTANTIATE_UNIFORM(intl)
INSTANTIATE_UNIFORM(uintl)
INSTANTIATE_UNIFORM(uchar)
#define INSTANTIATE_NORMAL(T) \
template Array<T> randn<T>(const af::dim4 &dims);
INSTANTIATE_NORMAL(float)
INSTANTIATE_NORMAL(double)
INSTANTIATE_NORMAL(cfloat)
INSTANTIATE_NORMAL(cdouble)
template<>
Array<char> randu(const af::dim4 &dims)
{
static unsigned long long my_seed = 0;
if (is_first) {
setSeed(gen_seed);
my_seed = gen_seed;
}
static auto gen = urand<float>(generator);
if (my_seed != gen_seed) {
gen = urand<float>(generator);
my_seed = gen_seed;
}
Array<char> outArray = createEmptyArray<char>(dims);
char *outPtr = outArray.get();
for (int i = 0; i < (int)outArray.elements(); i++) {
outPtr[i] = gen() > 0.5;
}
return outArray;
}
void setSeed(const uintl seed)
{
generator.seed(seed);
is_first = false;
gen_seed = seed;
}
uintl getSeed()
{
return gen_seed;
}
}
<commit_msg>Async random on CPU backend<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <type_traits>
#include <random>
#include <algorithm>
#include <functional>
#include <limits>
#include <type_traits>
#include <af/array.h>
#include <af/dim4.hpp>
#include <af/defines.h>
#include <Array.hpp>
#include <random.hpp>
#include <platform.hpp>
#include <async_queue.hpp>
namespace cpu
{
using namespace std;
template<typename T>
using is_arithmetic_t = typename enable_if< is_arithmetic<T>::value, function<T()>>::type;
template<typename T>
using is_complex_t = typename enable_if< is_complex<T>::value, function<T()>>::type;
template<typename T>
using is_floating_point_t = typename enable_if< is_floating_point<T>::value, function<T()>>::type;
template<typename T, typename GenType>
is_arithmetic_t<T>
urand(GenType &generator)
{
typedef typename conditional< is_floating_point<T>::value,
uniform_real_distribution<T>,
#if OS_WIN
uniform_int_distribution<unsigned>>::type dist;
#else
uniform_int_distribution<T >> ::type dist;
#endif
return bind(dist(), generator);
}
template<typename T, typename GenType>
is_complex_t<T>
urand(GenType &generator)
{
auto func = urand<typename T::value_type>(generator);
return [func] () { return T(func(), func());};
}
template<typename T, typename GenType>
is_floating_point_t<T>
nrand(GenType &generator)
{
return bind(normal_distribution<T>(), generator);
}
template<typename T, typename GenType>
is_complex_t<T>
nrand(GenType &generator)
{
auto func = nrand<typename T::value_type>(generator);
return [func] () { return T(func(), func());};
}
static default_random_engine generator;
static unsigned long long gen_seed = 0;
static bool is_first = true;
#define GLOBAL 1
template<typename T>
void randn_(Array<T> out)
{
static unsigned long long my_seed = 0;
if (is_first) {
setSeed(gen_seed);
my_seed = gen_seed;
}
static auto gen = nrand<T>(generator);
if (my_seed != gen_seed) {
gen = nrand<T>(generator);
my_seed = gen_seed;
}
T *outPtr = out.get();
for (int i = 0; i < (int)out.elements(); i++) {
outPtr[i] = gen();
}
}
template<typename T>
Array<T> randn(const af::dim4 &dims)
{
Array<T> outArray = createEmptyArray<T>(dims);
getQueue().enqueue(randn_<T>, outArray);
return outArray;
}
template<typename T>
void randu_(Array<T> out)
{
static unsigned long long my_seed = 0;
if (is_first) {
setSeed(gen_seed);
my_seed = gen_seed;
}
static auto gen = urand<T>(generator);
if (my_seed != gen_seed) {
gen = urand<T>(generator);
my_seed = gen_seed;
}
T *outPtr = out.get();
for (int i = 0; i < (int)out.elements(); i++) {
outPtr[i] = gen();
}
}
template<>
void randu_(Array<char> out)
{
static unsigned long long my_seed = 0;
if (is_first) {
setSeed(gen_seed);
my_seed = gen_seed;
}
static auto gen = urand<float>(generator);
if (my_seed != gen_seed) {
gen = urand<float>(generator);
my_seed = gen_seed;
}
char *outPtr = out.get();
for (int i = 0; i < (int)out.elements(); i++) {
outPtr[i] = gen() > 0.5;
}
}
template<typename T>
Array<T> randu(const af::dim4 &dims)
{
Array<T> outArray = createEmptyArray<T>(dims);
getQueue().enqueue(randu_<T>, outArray);
return outArray;
}
#define INSTANTIATE_UNIFORM(T) \
template Array<T> randu<T> (const af::dim4 &dims);
INSTANTIATE_UNIFORM(float)
INSTANTIATE_UNIFORM(double)
INSTANTIATE_UNIFORM(cfloat)
INSTANTIATE_UNIFORM(cdouble)
INSTANTIATE_UNIFORM(int)
INSTANTIATE_UNIFORM(uint)
INSTANTIATE_UNIFORM(intl)
INSTANTIATE_UNIFORM(uintl)
INSTANTIATE_UNIFORM(uchar)
INSTANTIATE_UNIFORM(char)
#define INSTANTIATE_NORMAL(T) \
template Array<T> randn<T>(const af::dim4 &dims);
INSTANTIATE_NORMAL(float)
INSTANTIATE_NORMAL(double)
INSTANTIATE_NORMAL(cfloat)
INSTANTIATE_NORMAL(cdouble)
void setSeed(const uintl seed)
{
auto f = [=](const uintl seed){
generator.seed(seed);
is_first = false;
gen_seed = seed;
};
getQueue().enqueue(f, seed);
}
uintl getSeed()
{
getQueue().sync();
return gen_seed;
}
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>
#include <roomba_clean_actions/basic_cleanAction.h>
#include <roomba_serial/SendButton.h>
#include <roomba_serial/SetMode.h>
#include <roomba_serial/Sensors.h>
#include <ctime>
class basic_cleanAction {
protected:
ros::NodeHandle nh_;
ros::ServiceClient client = nh_.serviceClient<roomba_serial::Sensors>("GetSensors");
actionlib::SimpleActionServer<roomba_clean_actions::basic_cleanAction> cleanserv_;
std::string action_name_;
roomba_clean_actions::basic_cleanFeedback feedback_;
roomba_clean_actions::basic_cleanResult result_;
ros::Publisher button_pub = nh_.advertise<roomba_serial::SendButton>("BUTTON_OUT", 100);
ros::Publisher mode_pub = nh_.advertise<roomba_serial::SetMode>("MODE_CHANGES", 100);
public:
basic_cleanAction(std::string name) :
cleanserv_(nh_, name, boost::bind(&basic_cleanAction::executeCB, this, _1), false), action_name_(name) {
cleanserv_.start();
ROS_INFO("Clean server started.");
}
~basic_cleanAction(void) {
}
void executeCB(const roomba_clean_actions::basic_cleanGoalConstPtr &goal) {
ROS_INFO("Got goal of %d seconds", goal->seconds);
ros::Rate r(1);
roomba_serial::SendButton dock;
dock.buttoncode = 10;
roomba_serial::Sensors sensorServer;
int distance = 0;
float charge;
sensorServer.request.request = 0;
bool success = true;
time_t base = time(NULL);
time_t curr = base;
roomba_serial::SetMode mode;
roomba_serial::SendButton button;
mode.modecode = 2; // Safe mode, to start cleaning cycle
button.buttoncode = 2;
bool running = false;
mode_pub.publish(mode);
r.sleep();
while(!running) {
if(cleanserv_.isPreemptRequested() || !ros::ok()) {
button_pub.publish(dock);
ROS_INFO("%s: Preempted, now docking", action_name_.c_str());
cleanserv_.setPreempted();
success = false;
break;
}
button_pub.publish(button);
r.sleep();
client.call(sensorServer);
running = (sensorServer.response.current < -150);
ROS_INFO("Current into battery is %d mA", sensorServer.response.current);
for(int i = 0; i < 10; i++) {
r.sleep();
}
}
while(curr < base + goal->seconds) {
if(cleanserv_.isPreemptRequested() || !ros::ok()) {
button_pub.publish(dock);
ROS_INFO("%s: Preempted, now docking", action_name_.c_str());
cleanserv_.setPreempted();
success = false;
break;
}
curr = time(NULL);
if(client.call(sensorServer)) {
distance = distance + sensorServer.response.distance;
charge = (float) (sensorServer.response.charge / sensorServer.response.capacity);
}
else {
ROS_INFO("%s: Didn't get sensor response, sending stale data.", action_name_.c_str());
}
feedback_.seconds = (uint16_t) (curr - base);
feedback_.millimeters = distance;
feedback_.battery_charge = charge;
cleanserv_.publishFeedback(feedback_);
r.sleep();
}
button_pub.publish(dock);
bool charging = false;
while(!charging) {
while(!client.call(sensorServer)) {r.sleep();}
charging = (sensorServer.response.current > 0);
feedback_.millimeters = distance + sensorServer.response.distance;
feedback_.battery_charge = (float) (sensorServer.response.charge / sensorServer.response.capacity);
feedback_.seconds = time(NULL) - base;
cleanserv_.publishFeedback(feedback_);
r.sleep();
}
result_.seconds = feedback_.seconds;
result_.millimeters = feedback_.millimeters;
result_.battery_charge = feedback_.battery_charge;
cleanserv_.setSucceeded(result_);
}
};
int main(int argc, char** argv) {
ros::init(argc, argv, "basic_clean");
basic_cleanAction bc(ros::this_node::getName());
ros::spin();
}
<commit_msg>Moved current check to after wait loop in startup<commit_after>#include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>
#include <roomba_clean_actions/basic_cleanAction.h>
#include <roomba_serial/SendButton.h>
#include <roomba_serial/SetMode.h>
#include <roomba_serial/Sensors.h>
#include <ctime>
class basic_cleanAction {
protected:
ros::NodeHandle nh_;
ros::ServiceClient client = nh_.serviceClient<roomba_serial::Sensors>("GetSensors");
actionlib::SimpleActionServer<roomba_clean_actions::basic_cleanAction> cleanserv_;
std::string action_name_;
roomba_clean_actions::basic_cleanFeedback feedback_;
roomba_clean_actions::basic_cleanResult result_;
ros::Publisher button_pub = nh_.advertise<roomba_serial::SendButton>("BUTTON_OUT", 100);
ros::Publisher mode_pub = nh_.advertise<roomba_serial::SetMode>("MODE_CHANGES", 100);
public:
basic_cleanAction(std::string name) :
cleanserv_(nh_, name, boost::bind(&basic_cleanAction::executeCB, this, _1), false), action_name_(name) {
cleanserv_.start();
ROS_INFO("Clean server started.");
}
~basic_cleanAction(void) {
}
void executeCB(const roomba_clean_actions::basic_cleanGoalConstPtr &goal) {
ROS_INFO("Got goal of %d seconds", goal->seconds);
ros::Rate r(1);
roomba_serial::SendButton dock;
dock.buttoncode = 10;
roomba_serial::Sensors sensorServer;
int distance = 0;
float charge;
sensorServer.request.request = 0;
bool success = true;
time_t base = time(NULL);
time_t curr = base;
roomba_serial::SetMode mode;
roomba_serial::SendButton button;
mode.modecode = 2; // Safe mode, to start cleaning cycle
button.buttoncode = 2;
bool running = false;
mode_pub.publish(mode);
r.sleep();
while(!running) {
if(cleanserv_.isPreemptRequested() || !ros::ok()) {
button_pub.publish(dock);
ROS_INFO("%s: Preempted, now docking", action_name_.c_str());
cleanserv_.setPreempted();
success = false;
break;
}
button_pub.publish(button);
r.sleep();
client.call(sensorServer);
ROS_INFO("Current into battery is %d mA", sensorServer.response.current);
for(int i = 0; i < 5; i++) {
r.sleep();
}
running = (sensorServer.response.current < -150);
}
ROS_INFO("Roomba Away!");
while(curr < base + goal->seconds) {
if(cleanserv_.isPreemptRequested() || !ros::ok()) {
button_pub.publish(dock);
ROS_INFO("%s: Preempted, now docking", action_name_.c_str());
cleanserv_.setPreempted();
success = false;
break;
}
curr = time(NULL);
if(client.call(sensorServer)) {
distance = distance + sensorServer.response.distance;
charge = (float) (sensorServer.response.charge / sensorServer.response.capacity);
}
else {
ROS_INFO("%s: Didn't get sensor response, sending stale data.", action_name_.c_str());
}
feedback_.seconds = (uint16_t) (curr - base);
feedback_.millimeters = distance;
feedback_.battery_charge = charge;
cleanserv_.publishFeedback(feedback_);
r.sleep();
}
button_pub.publish(dock);
bool charging = false;
while(!charging) {
while(!client.call(sensorServer)) {r.sleep();}
charging = (sensorServer.response.current > 0);
feedback_.millimeters = distance + sensorServer.response.distance;
feedback_.battery_charge = (float) (sensorServer.response.charge / sensorServer.response.capacity);
feedback_.seconds = time(NULL) - base;
cleanserv_.publishFeedback(feedback_);
r.sleep();
}
result_.seconds = feedback_.seconds;
result_.millimeters = feedback_.millimeters;
result_.battery_charge = feedback_.battery_charge;
cleanserv_.setSucceeded(result_);
}
};
int main(int argc, char** argv) {
ros::init(argc, argv, "basic_clean");
basic_cleanAction bc(ros::this_node::getName());
ros::spin();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.
* Copyright (C) 2014 furan
*
* 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 "Lexer.h"
#include <cstring>
#include <string>
constexpr const char AND[] = "AND";
constexpr const char MAYBE[] = "MAYBE";
constexpr const char OR[] = "OR";
constexpr const char NOT[] = "NOT";
constexpr const char XOR[] = "XOR";
constexpr char DOUBLEQUOTE = '"';
constexpr char SINGLEQUOTE = '\'';
constexpr char LEFT_SQUARE_BRACKET = '[';
constexpr char RIGHT_SQUARE_BRACKET = ']';
Lexer::Lexer(char* input)
: contentReader(ContentReader(input)),
currentSymbol(contentReader.NextSymbol()) { }
Token
Lexer::NextToken()
{
std::string lexeme;
LexerState currentState = LexerState::INIT;
Token token;
char quote;
auto upState = currentState;
std::string symbol;
std::string lcSymbol;
while (true) {
symbol.clear();
symbol += currentSymbol.symbol;
switch (currentState) {
case LexerState::INIT:
switch(currentSymbol.symbol) {
case LEFT_SQUARE_BRACKET:
lexeme += currentSymbol.symbol;
currentState = LexerState::INIT_SQUARE_BRACKET;
currentSymbol = contentReader.NextSymbol();
break;
case SINGLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
quote = SINGLEQUOTE;
currentSymbol = contentReader.NextSymbol();
break;
case DOUBLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
quote = DOUBLEQUOTE;
currentSymbol = contentReader.NextSymbol();
break;
case '\0':
currentState = LexerState::EOFILE;
break;
default:
switch (currentSymbol.symbol) {
case ' ':
case '\n':
case '\t':
case '\r':
currentState = LexerState::INIT;
currentSymbol = contentReader.NextSymbol();
break;
case '(':
case ')':
case '&':
case '|':
case '!':
lexeme += currentSymbol.symbol;
currentState = LexerState::SYMBOL_OP;
currentSymbol = contentReader.NextSymbol();
break;
default:
lexeme += currentSymbol.symbol;
if (lexeme.size() >= 1024) {
std::string msj = "Symbol " + symbol + " not expected";
throw LexicalException(msj);
}
currentState = LexerState::TOKEN;
currentSymbol = contentReader.NextSymbol();
break;
}
}
break;
case LexerState::TOKEN:
switch(currentSymbol.symbol) {
case DOUBLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
quote = DOUBLEQUOTE;
currentSymbol = contentReader.NextSymbol();
break;
case SINGLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
quote = SINGLEQUOTE;
currentSymbol = contentReader.NextSymbol();
break;
default:
if (!IsSymbolOp(currentSymbol.symbol) && currentSymbol.symbol != ' ' && currentSymbol.symbol != '\0') {
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN;
currentSymbol = contentReader.NextSymbol();
} else {
token.set_lexeme(lexeme);
token.set_type(TokenType::Id);
IsStringOperator(token);
return token;
}
}
break;
case LexerState::TOKEN_QUOTE:
switch (currentSymbol.symbol) {
case '\\':
lexeme += currentSymbol.symbol;
currentState = LexerState::ESCAPE;
currentSymbol = contentReader.NextSymbol();
break;
case '\0': {
std::string msj = "Symbol double quote expected";
throw LexicalException(msj);
}
default:
if (currentSymbol.symbol == quote) {
lexeme += currentSymbol.symbol;
upState == LexerState::INIT_SQUARE_BRACKET ? currentState = LexerState::END_SQUARE_BRACKET : currentState = LexerState::TOKEN;
currentSymbol = contentReader.NextSymbol();
} else {
lexeme += currentSymbol.symbol;
currentSymbol = contentReader.NextSymbol();
}
}
break;
case LexerState::ESCAPE:
switch(currentSymbol.symbol) {
case '\0': {
std::string msj = "Symbol EOF not expected";
throw LexicalException(msj);
}
default:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
currentSymbol = contentReader.NextSymbol();
break;
}
break;
case LexerState::INIT_SQUARE_BRACKET:
switch (currentSymbol.symbol) {
case DOUBLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
upState = LexerState::INIT_SQUARE_BRACKET;
quote = DOUBLEQUOTE;
currentSymbol = contentReader.NextSymbol();
continue;
case SINGLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
upState = LexerState::INIT_SQUARE_BRACKET;
quote = SINGLEQUOTE;
currentSymbol = contentReader.NextSymbol();
continue;
default:
if (currentSymbol.symbol != RIGHT_SQUARE_BRACKET && currentSymbol.symbol != '\0') {
lexeme += currentSymbol.symbol;
currentSymbol = contentReader.NextSymbol();
continue;
}
}
/* FALLTHROUGH */
case LexerState::END_SQUARE_BRACKET:
switch (currentSymbol.symbol) {
case RIGHT_SQUARE_BRACKET:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN;
currentSymbol = contentReader.NextSymbol();
break;
case ',':
lexeme += currentSymbol.symbol;
currentState = LexerState::INIT_SQUARE_BRACKET;
currentSymbol = contentReader.NextSymbol();
break;
default:
std::string msj = "Symbol ] expected";
throw LexicalException(msj);
}
break;
case LexerState::SYMBOL_OP:
token.set_lexeme(lexeme);
switch(lexeme.at(0)) {
case '(':
token.set_type(TokenType::LeftParenthesis);
break;
case ')':
token.set_type(TokenType::RightParenthesis);
break;
case '&':
token.set_type(TokenType::And);
break;
case '|':
token.set_type(TokenType::Or);
break;
case '!':
token.set_type(TokenType::Not);
break;
}
return token;
case LexerState::EOFILE:
token.set_type(TokenType::EndOfFile);
return token;
default:
break;
}
}
return token;
}
void
Lexer::IsStringOperator(Token& token) const
{
auto lexeme = token.get_lexeme();
if (!lexeme.empty()) {
switch (lexeme.at(0)) {
case 'a':
case 'A':
if (strcasecmp(lexeme.data(), AND) == 0) {
token.set_type(TokenType::And);
}
break;
case 'm':
case 'M':
if (strcasecmp(lexeme.data(), MAYBE) == 0) {
token.set_type(TokenType::Maybe);
}
break;
case 'o':
case 'O':
if (strcasecmp(lexeme.data(), OR) == 0) {
token.set_type(TokenType::Or);
}
break;
case 'n':
case 'N':
if (strcasecmp(lexeme.data(), NOT) == 0) {
token.set_type(TokenType::Not);
}
break;
case 'x':
case 'X':
if (strcasecmp(lexeme.data(), XOR) == 0) {
token.set_type(TokenType::Xor);
}
break;
default:
return;
}
}
}
bool
Lexer::IsSymbolOp(char c) const
{
switch (c) {
case '(':
case ')':
case '&':
case '|':
case '~':
return true;
default:
return false;
}
}
<commit_msg>Fix negation operator<commit_after>/*
* Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.
* Copyright (C) 2014 furan
*
* 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 "Lexer.h"
#include <cstring>
#include <string>
constexpr const char AND[] = "AND";
constexpr const char MAYBE[] = "MAYBE";
constexpr const char OR[] = "OR";
constexpr const char NOT[] = "NOT";
constexpr const char XOR[] = "XOR";
constexpr char DOUBLEQUOTE = '"';
constexpr char SINGLEQUOTE = '\'';
constexpr char LEFT_SQUARE_BRACKET = '[';
constexpr char RIGHT_SQUARE_BRACKET = ']';
Lexer::Lexer(char* input)
: contentReader(ContentReader(input)),
currentSymbol(contentReader.NextSymbol()) { }
Token
Lexer::NextToken()
{
std::string lexeme;
LexerState currentState = LexerState::INIT;
Token token;
char quote;
auto upState = currentState;
std::string symbol;
std::string lcSymbol;
while (true) {
symbol.clear();
symbol += currentSymbol.symbol;
switch (currentState) {
case LexerState::INIT:
switch(currentSymbol.symbol) {
case LEFT_SQUARE_BRACKET:
lexeme += currentSymbol.symbol;
currentState = LexerState::INIT_SQUARE_BRACKET;
currentSymbol = contentReader.NextSymbol();
break;
case SINGLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
quote = SINGLEQUOTE;
currentSymbol = contentReader.NextSymbol();
break;
case DOUBLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
quote = DOUBLEQUOTE;
currentSymbol = contentReader.NextSymbol();
break;
case '\0':
currentState = LexerState::EOFILE;
break;
default:
switch (currentSymbol.symbol) {
case ' ':
case '\n':
case '\t':
case '\r':
currentState = LexerState::INIT;
currentSymbol = contentReader.NextSymbol();
break;
case '(':
case ')':
case '&':
case '|':
case '!':
lexeme += currentSymbol.symbol;
currentState = LexerState::SYMBOL_OP;
currentSymbol = contentReader.NextSymbol();
break;
default:
lexeme += currentSymbol.symbol;
if (lexeme.size() >= 1024) {
std::string msj = "Symbol " + symbol + " not expected";
throw LexicalException(msj);
}
currentState = LexerState::TOKEN;
currentSymbol = contentReader.NextSymbol();
break;
}
}
break;
case LexerState::TOKEN:
switch(currentSymbol.symbol) {
case DOUBLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
quote = DOUBLEQUOTE;
currentSymbol = contentReader.NextSymbol();
break;
case SINGLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
quote = SINGLEQUOTE;
currentSymbol = contentReader.NextSymbol();
break;
default:
if (!IsSymbolOp(currentSymbol.symbol) && currentSymbol.symbol != ' ' && currentSymbol.symbol != '\0') {
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN;
currentSymbol = contentReader.NextSymbol();
} else {
token.set_lexeme(lexeme);
token.set_type(TokenType::Id);
IsStringOperator(token);
return token;
}
}
break;
case LexerState::TOKEN_QUOTE:
switch (currentSymbol.symbol) {
case '\\':
lexeme += currentSymbol.symbol;
currentState = LexerState::ESCAPE;
currentSymbol = contentReader.NextSymbol();
break;
case '\0': {
std::string msj = "Symbol double quote expected";
throw LexicalException(msj);
}
default:
if (currentSymbol.symbol == quote) {
lexeme += currentSymbol.symbol;
upState == LexerState::INIT_SQUARE_BRACKET ? currentState = LexerState::END_SQUARE_BRACKET : currentState = LexerState::TOKEN;
currentSymbol = contentReader.NextSymbol();
} else {
lexeme += currentSymbol.symbol;
currentSymbol = contentReader.NextSymbol();
}
}
break;
case LexerState::ESCAPE:
switch(currentSymbol.symbol) {
case '\0': {
std::string msj = "Symbol EOF not expected";
throw LexicalException(msj);
}
default:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
currentSymbol = contentReader.NextSymbol();
break;
}
break;
case LexerState::INIT_SQUARE_BRACKET:
switch (currentSymbol.symbol) {
case DOUBLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
upState = LexerState::INIT_SQUARE_BRACKET;
quote = DOUBLEQUOTE;
currentSymbol = contentReader.NextSymbol();
continue;
case SINGLEQUOTE:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN_QUOTE;
upState = LexerState::INIT_SQUARE_BRACKET;
quote = SINGLEQUOTE;
currentSymbol = contentReader.NextSymbol();
continue;
default:
if (currentSymbol.symbol != RIGHT_SQUARE_BRACKET && currentSymbol.symbol != '\0') {
lexeme += currentSymbol.symbol;
currentSymbol = contentReader.NextSymbol();
continue;
}
}
/* FALLTHROUGH */
case LexerState::END_SQUARE_BRACKET:
switch (currentSymbol.symbol) {
case RIGHT_SQUARE_BRACKET:
lexeme += currentSymbol.symbol;
currentState = LexerState::TOKEN;
currentSymbol = contentReader.NextSymbol();
break;
case ',':
lexeme += currentSymbol.symbol;
currentState = LexerState::INIT_SQUARE_BRACKET;
currentSymbol = contentReader.NextSymbol();
break;
default:
std::string msj = "Symbol ] expected";
throw LexicalException(msj);
}
break;
case LexerState::SYMBOL_OP:
token.set_lexeme(lexeme);
switch(lexeme.at(0)) {
case '(':
token.set_type(TokenType::LeftParenthesis);
break;
case ')':
token.set_type(TokenType::RightParenthesis);
break;
case '&':
token.set_type(TokenType::And);
break;
case '|':
token.set_type(TokenType::Or);
break;
case '!':
token.set_type(TokenType::Not);
break;
}
return token;
case LexerState::EOFILE:
token.set_type(TokenType::EndOfFile);
return token;
default:
break;
}
}
return token;
}
void
Lexer::IsStringOperator(Token& token) const
{
auto lexeme = token.get_lexeme();
if (!lexeme.empty()) {
switch (lexeme.at(0)) {
case 'a':
case 'A':
if (strcasecmp(lexeme.data(), AND) == 0) {
token.set_type(TokenType::And);
}
break;
case 'm':
case 'M':
if (strcasecmp(lexeme.data(), MAYBE) == 0) {
token.set_type(TokenType::Maybe);
}
break;
case 'o':
case 'O':
if (strcasecmp(lexeme.data(), OR) == 0) {
token.set_type(TokenType::Or);
}
break;
case 'n':
case 'N':
if (strcasecmp(lexeme.data(), NOT) == 0) {
token.set_type(TokenType::Not);
}
break;
case 'x':
case 'X':
if (strcasecmp(lexeme.data(), XOR) == 0) {
token.set_type(TokenType::Xor);
}
break;
default:
return;
}
}
}
bool
Lexer::IsSymbolOp(char c) const
{
switch (c) {
case '(':
case ')':
case '&':
case '|':
case '!':
return true;
default:
return false;
}
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// interface headers
#include "HUDuiTypeIn.h"
// system implementation headers
#include <ctype.h>
// common implementation headers
#include "FontManager.h"
#include "bzUnicode.h"
//
// HUDuiTypeIn
//
HUDuiTypeIn::HUDuiTypeIn()
: HUDuiControl(), maxLength(0), cursorPos(string.c_str())
{
allowEdit = true; // allow editing by default
obfuscate = false;
}
HUDuiTypeIn::~HUDuiTypeIn()
{
}
void HUDuiTypeIn::setObfuscation(bool on)
{
obfuscate = on;
}
int HUDuiTypeIn::getMaxLength() const
{
return maxLength;
}
std::string HUDuiTypeIn::getString() const
{
return string;
}
void HUDuiTypeIn::setMaxLength(int _maxLength)
{
maxLength = _maxLength;
string = string.substr(0, maxLength);
if (cursorPos.getCount() > maxLength)
{
cursorPos = string.c_str();
while (*cursorPos)
++cursorPos;
}
onSetFont();
}
void HUDuiTypeIn::setString(const std::string& _string)
{
string = _string;
cursorPos = string.c_str();
while (*cursorPos)
++cursorPos;
onSetFont();
}
// allows composing, otherwise not
void HUDuiTypeIn::setEditing(bool _allowEdit)
{
allowEdit = _allowEdit;
}
bool HUDuiTypeIn::doKeyPress(const BzfKeyEvent& key)
{
static unsigned int backspace = '\b'; // ^H
static unsigned int whitespace = ' ';
if (HUDuiControl::doKeyPress(key))
return true;
if (!allowEdit) return false; //or return true ??
unsigned int c = key.chr;
if (c == 0) switch (key.button) {
case BzfKeyEvent::Left: {
int pos = cursorPos.getCount();
// uhh...there's not really any way to reverse over a multibyte string
// do this the hard way: reset to the beginning and advance to the current
// position, minus a character.
if (pos > 0) {
--pos;
cursorPos = string.c_str();
while (cursorPos.getCount() < pos && (*cursorPos))
++cursorPos;
}
return true;
}
case BzfKeyEvent::Right:
if (*cursorPos)
++cursorPos;
return true;
case BzfKeyEvent::Home:
cursorPos = string.c_str();
return true;
case BzfKeyEvent::End:
while (*cursorPos)
++cursorPos;
return true;
case BzfKeyEvent::Backspace:
c = backspace;
break;
case BzfKeyEvent::Delete:
if (*cursorPos) {
++cursorPos;
c = backspace;
} else {
return true;
}
break;
default:
return false;
}
if (!iswprint(c) && c != backspace)
return false;
if (c == backspace) {
int pos = cursorPos.getCount();
if (pos == 1) {
goto noRoom;
} else {
// copy up to cursor position - 1
cursorPos = string.c_str();
--pos;
while (cursorPos.getCount() < pos)
++cursorPos;
std::string temp = string.substr(0, cursorPos.getBufferFromHere() - string.c_str());
// skip the deleted character
++cursorPos;
// copy the remainder
pos = (int)(cursorPos.getBufferFromHere() - string.c_str());
temp += string.substr(pos, string.length() - pos);
string = temp;
// new buffer, restart cursor
pos = cursorPos.getCount();
cursorPos = string.c_str();
while (cursorPos.getCount() < (pos - 1))
++cursorPos;
}
onSetFont();
} else {
if (iswspace(c))
c = whitespace;
CountUTF8StringItr cusi(string.c_str());
while (*cusi) ++cusi;
if (cusi.getCount() >= maxLength) goto noRoom;
bzUTF8Char ch(c);
int pos = (int)(cursorPos.getBufferFromHere() - string.c_str());
// copy to the current cursor location
std::string temp = string.substr(0, pos);
// insert the new character
temp += ch.str();
// copy the rest of the string
temp += string.substr(pos, string.length());
string = temp;
// new buffer, restart cursor
pos = cursorPos.getCount();
cursorPos = string.c_str();
while (cursorPos.getCount() < pos)
++cursorPos;
// bump the cursor
++cursorPos;
onSetFont();
}
return true;
noRoom:
// ring bell?
return true;
}
bool HUDuiTypeIn::doKeyRelease(const BzfKeyEvent& key)
{
if (key.chr == '\t' || !iswprint(key.chr)) // ignore non-printing and tab
return false;
// slurp up releases
return true;
}
void HUDuiTypeIn::doRender()
{
if (getFontFace() < 0) return;
// render string
glColor3fv(hasFocus() ? textColor : dimTextColor);
FontManager &fm = FontManager::instance();
std::string renderStr;
if (obfuscate) {
renderStr.append(string.size(), '*');
} else {
renderStr = string;
}
fm.drawString(getX(), getY(), 0, getFontFace(), getFontSize(), renderStr.c_str());
// find the position of where to draw the input cursor
float start = fm.getStringWidth(getFontFace(), getFontSize(),
renderStr.substr(0, cursorPos.getBufferFromHere() - string.c_str()).c_str());
if (hasFocus() && allowEdit) {
fm.drawString(getX() + start, getY(), 0, getFontFace(), getFontSize(), "_");
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Render obfuscated multibyte strings correctly.<commit_after>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// interface headers
#include "HUDuiTypeIn.h"
// system implementation headers
#include <ctype.h>
// common implementation headers
#include "FontManager.h"
#include "bzUnicode.h"
//
// HUDuiTypeIn
//
HUDuiTypeIn::HUDuiTypeIn()
: HUDuiControl(), maxLength(0), cursorPos(string.c_str())
{
allowEdit = true; // allow editing by default
obfuscate = false;
}
HUDuiTypeIn::~HUDuiTypeIn()
{
}
void HUDuiTypeIn::setObfuscation(bool on)
{
obfuscate = on;
}
int HUDuiTypeIn::getMaxLength() const
{
return maxLength;
}
std::string HUDuiTypeIn::getString() const
{
return string;
}
void HUDuiTypeIn::setMaxLength(int _maxLength)
{
maxLength = _maxLength;
string = string.substr(0, maxLength);
if (cursorPos.getCount() > maxLength)
{
cursorPos = string.c_str();
while (*cursorPos)
++cursorPos;
}
onSetFont();
}
void HUDuiTypeIn::setString(const std::string& _string)
{
string = _string;
cursorPos = string.c_str();
while (*cursorPos)
++cursorPos;
onSetFont();
}
// allows composing, otherwise not
void HUDuiTypeIn::setEditing(bool _allowEdit)
{
allowEdit = _allowEdit;
}
bool HUDuiTypeIn::doKeyPress(const BzfKeyEvent& key)
{
static unsigned int backspace = '\b'; // ^H
static unsigned int whitespace = ' ';
if (HUDuiControl::doKeyPress(key))
return true;
if (!allowEdit) return false; //or return true ??
unsigned int c = key.chr;
if (c == 0) switch (key.button) {
case BzfKeyEvent::Left: {
int pos = cursorPos.getCount();
// uhh...there's not really any way to reverse over a multibyte string
// do this the hard way: reset to the beginning and advance to the current
// position, minus a character.
if (pos > 0) {
--pos;
cursorPos = string.c_str();
while (cursorPos.getCount() < pos && (*cursorPos))
++cursorPos;
}
return true;
}
case BzfKeyEvent::Right:
if (*cursorPos)
++cursorPos;
return true;
case BzfKeyEvent::Home:
cursorPos = string.c_str();
return true;
case BzfKeyEvent::End:
while (*cursorPos)
++cursorPos;
return true;
case BzfKeyEvent::Backspace:
c = backspace;
break;
case BzfKeyEvent::Delete:
if (*cursorPos) {
++cursorPos;
c = backspace;
} else {
return true;
}
break;
default:
return false;
}
if (!iswprint(c) && c != backspace)
return false;
if (c == backspace) {
int pos = cursorPos.getCount();
if (pos == 1) {
goto noRoom;
} else {
// copy up to cursor position - 1
cursorPos = string.c_str();
--pos;
while (cursorPos.getCount() < pos)
++cursorPos;
std::string temp = string.substr(0, cursorPos.getBufferFromHere() - string.c_str());
// skip the deleted character
++cursorPos;
// copy the remainder
pos = (int)(cursorPos.getBufferFromHere() - string.c_str());
temp += string.substr(pos, string.length() - pos);
string = temp;
// new buffer, restart cursor
pos = cursorPos.getCount();
cursorPos = string.c_str();
while (cursorPos.getCount() < (pos - 1))
++cursorPos;
}
onSetFont();
} else {
if (iswspace(c))
c = whitespace;
CountUTF8StringItr cusi(string.c_str());
while (*cusi) ++cusi;
if (cusi.getCount() >= maxLength) goto noRoom;
bzUTF8Char ch(c);
int pos = (int)(cursorPos.getBufferFromHere() - string.c_str());
// copy to the current cursor location
std::string temp = string.substr(0, pos);
// insert the new character
temp += ch.str();
// copy the rest of the string
temp += string.substr(pos, string.length());
string = temp;
// new buffer, restart cursor
pos = cursorPos.getCount();
cursorPos = string.c_str();
while (cursorPos.getCount() < pos)
++cursorPos;
// bump the cursor
++cursorPos;
onSetFont();
}
return true;
noRoom:
// ring bell?
return true;
}
bool HUDuiTypeIn::doKeyRelease(const BzfKeyEvent& key)
{
if (key.chr == '\t' || !iswprint(key.chr)) // ignore non-printing and tab
return false;
// slurp up releases
return true;
}
void HUDuiTypeIn::doRender()
{
if (getFontFace() < 0) return;
// render string
glColor3fv(hasFocus() ? textColor : dimTextColor);
FontManager &fm = FontManager::instance();
std::string renderStr;
if (obfuscate) {
CountUTF8StringItr cusi(string.c_str());
while (*cusi) ++cusi;
renderStr.append(cusi.getCount(), '*');
} else {
renderStr = string;
}
fm.drawString(getX(), getY(), 0, getFontFace(), getFontSize(), renderStr.c_str());
// find the position of where to draw the input cursor
float start = fm.getStringWidth(getFontFace(), getFontSize(),
renderStr.substr(0, cursorPos.getBufferFromHere() - string.c_str()).c_str());
if (hasFocus() && allowEdit) {
fm.drawString(getX() + start, getY(), 0, getFontFace(), getFontSize(), "_");
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// object that creates and contains a spawn position
#include "common.h"
#include "SpawnPosition.h"
#include "FlagInfo.h"
#include "TeamBases.h"
#include "WorldInfo.h"
#include "PlayerInfo.h"
#include "PlayerState.h"
// FIXME: from bzfs.cxx
extern int getCurMaxPlayers();
extern bool areFoes(TeamColor team1, TeamColor team2);
extern BasesList bases;
extern WorldInfo *world;
extern PlayerInfo player[];
extern PlayerState lastState[];
SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :
curMaxPlayers(getCurMaxPlayers())
{
team = player[playerId].getTeam();
azimuth = (float)bzfrand() * 2.0f * M_PI;
if (player[playerId].shouldRestartAtBase() &&
(team >= RedTeam) && (team <= PurpleTeam) &&
(bases.find(team) != bases.end())) {
TeamBases &teamBases = bases[team];
const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));
base.getRandomPosition(pos[0], pos[1], pos[2]);
player[playerId].setRestartOnBase(false);
} else {
const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);
const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS);
safeSWRadius = (BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5;
safeDistance = tankRadius * 20; // FIXME: is this a good value?
const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);
const float maxWorldHeight = world->getMaxWorldHeight();
ObstacleLocation *building;
// keep track of how much time we spend searching for a location
TimeKeeper start = TimeKeeper::getCurrent();
int inAirAttempts = 50;
int tries = 0;
float minProximity = size / 3.0f;
float bestDist = -1.0f;
float testPos[3];
bool foundspot = false;
while (!foundspot) {
if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {
if (notNearEdges) {
// don't spawn close to map edges in CTF mode
testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;
testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;
} else {
testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
}
testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);
}
tries++;
int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (onGroundOnly) {
if (type == NOT_IN_BUILDING)
foundspot = true;
} else {
if ((type == NOT_IN_BUILDING) && (pos[2] > 0.0f)) {
testPos[2] = 0.0f;
//Find any intersection regardless of z
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, maxWorldHeight);
}
// in a building? try climbing on roof until on top
int lastType = type;
int retriesRemaining = 100; // don't climb forever
while (type != NOT_IN_BUILDING) {
testPos[2] = building->pos[2] + building->size[2] + 0.0001f;
tries++;
lastType = type;
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (--retriesRemaining <= 0) {
DEBUG1("Warning: getSpawnLocation had to climb too many buildings\n");
break;
}
}
// ok, when not on top of pyramid or teleporter
if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) {
foundspot = true;
}
// only try up in the sky so many times
if (--inAirAttempts <= 0) {
onGroundOnly = true;
}
}
// check every now and then if we have already used up 10ms of time
if (tries >= 50) {
tries = 0;
if (TimeKeeper::getCurrent() - start > 0.01f) {
if (bestDist < 0.0f) { // haven't found a single spot
//Just drop the sucka in, and pray
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = maxWorldHeight;
DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n");
}
break;
}
}
// check if spot is safe enough
if (foundspot && !isImminentlyDangerous()) {
float enemyAngle;
float dist = enemyProximityCheck(enemyAngle);
if (dist > bestDist) { // best so far
bestDist = dist;
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = testPos[2];
azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI);
}
if (bestDist < minProximity) { // not good enough, keep looking
foundspot = false;
minProximity *= 0.99f; // relax requirements a little
}
}
}
delete building;
}
}
SpawnPosition::~SpawnPosition()
{
}
const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth,
const float deviation) const
{
// determine angle from source to dest
// (X) using only x & y, resultant will be z rotation
float dx = testPos[0] - enemyPos[0];
float dy = testPos[1] - enemyPos[1];
float angActual;
if (dx == 0) {
// avoid divide by zero error
angActual = (float)tan(dy / (1 / 1e12f));
} else {
angActual = (float)tan(dy / dx);
}
// see if our heading angle is within the bounds set by deviation
// (X) only compare to z-rotation since that's all we're using
if (((angActual + deviation / 2) > enemyAzimuth) &&
((angActual - deviation / 2) < enemyAzimuth)) {
return true;
} else {
return false;
}
}
const bool SpawnPosition::isImminentlyDangerous() const
{
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {
std::string pflag = flag[player[i].getFlag()].flag.type->flagAbbv;
float *enemyPos = lastState[i].pos;
float enemyAngle = lastState[i].azimuth;
// check for dangerous flags, etc
// FIXME: any more?
if (pflag == "L") { // don't spawn in the line of sight of an L
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { // he's looking within 20 degrees of spawn point
return true; // eek, don't spawn here
}
} else if (pflag == "SW") { // don't spawn next to a SW
if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW
return true; // eek, don't spawn here
}
}
// don't spawn in the line of sight of a normal-shot tank within a certain distance
if (distanceFrom(enemyPos) < safeDistance) { // within danger zone?
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { //and he's looking at me
return true;
}
}
}
}
// TODO: should check world weapons also
return false;
}
const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const
{
float worstDist = 1e12f; // huge number
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {
float *enemyPos = lastState[i].pos;
if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {
float x = enemyPos[0] - testPos[0];
float y = enemyPos[1] - testPos[1];
float distSq = x * x + y * y;
if (distSq < worstDist) {
worstDist = distSq;
enemyAngle = lastState[i].azimuth;
}
}
}
}
return sqrtf(worstDist);
}
const float SpawnPosition::distanceFrom(const float* farPos) const
{
float dx = farPos[0] - testPos[0];
float dy = farPos[1] - testPos[1];
float dz = farPos[2] - testPos[2];
return (float)sqrt(dx*dx + dy*dy + dz*dz);
}<commit_msg>nl @ eof<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// object that creates and contains a spawn position
#include "common.h"
#include "SpawnPosition.h"
#include "FlagInfo.h"
#include "TeamBases.h"
#include "WorldInfo.h"
#include "PlayerInfo.h"
#include "PlayerState.h"
// FIXME: from bzfs.cxx
extern int getCurMaxPlayers();
extern bool areFoes(TeamColor team1, TeamColor team2);
extern BasesList bases;
extern WorldInfo *world;
extern PlayerInfo player[];
extern PlayerState lastState[];
SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :
curMaxPlayers(getCurMaxPlayers())
{
team = player[playerId].getTeam();
azimuth = (float)bzfrand() * 2.0f * M_PI;
if (player[playerId].shouldRestartAtBase() &&
(team >= RedTeam) && (team <= PurpleTeam) &&
(bases.find(team) != bases.end())) {
TeamBases &teamBases = bases[team];
const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));
base.getRandomPosition(pos[0], pos[1], pos[2]);
player[playerId].setRestartOnBase(false);
} else {
const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);
const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS);
safeSWRadius = (BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5;
safeDistance = tankRadius * 20; // FIXME: is this a good value?
const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);
const float maxWorldHeight = world->getMaxWorldHeight();
ObstacleLocation *building;
// keep track of how much time we spend searching for a location
TimeKeeper start = TimeKeeper::getCurrent();
int inAirAttempts = 50;
int tries = 0;
float minProximity = size / 3.0f;
float bestDist = -1.0f;
float testPos[3];
bool foundspot = false;
while (!foundspot) {
if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {
if (notNearEdges) {
// don't spawn close to map edges in CTF mode
testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;
testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;
} else {
testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
}
testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);
}
tries++;
int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (onGroundOnly) {
if (type == NOT_IN_BUILDING)
foundspot = true;
} else {
if ((type == NOT_IN_BUILDING) && (pos[2] > 0.0f)) {
testPos[2] = 0.0f;
//Find any intersection regardless of z
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, maxWorldHeight);
}
// in a building? try climbing on roof until on top
int lastType = type;
int retriesRemaining = 100; // don't climb forever
while (type != NOT_IN_BUILDING) {
testPos[2] = building->pos[2] + building->size[2] + 0.0001f;
tries++;
lastType = type;
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (--retriesRemaining <= 0) {
DEBUG1("Warning: getSpawnLocation had to climb too many buildings\n");
break;
}
}
// ok, when not on top of pyramid or teleporter
if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) {
foundspot = true;
}
// only try up in the sky so many times
if (--inAirAttempts <= 0) {
onGroundOnly = true;
}
}
// check every now and then if we have already used up 10ms of time
if (tries >= 50) {
tries = 0;
if (TimeKeeper::getCurrent() - start > 0.01f) {
if (bestDist < 0.0f) { // haven't found a single spot
//Just drop the sucka in, and pray
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = maxWorldHeight;
DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n");
}
break;
}
}
// check if spot is safe enough
if (foundspot && !isImminentlyDangerous()) {
float enemyAngle;
float dist = enemyProximityCheck(enemyAngle);
if (dist > bestDist) { // best so far
bestDist = dist;
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = testPos[2];
azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI);
}
if (bestDist < minProximity) { // not good enough, keep looking
foundspot = false;
minProximity *= 0.99f; // relax requirements a little
}
}
}
delete building;
}
}
SpawnPosition::~SpawnPosition()
{
}
const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth,
const float deviation) const
{
// determine angle from source to dest
// (X) using only x & y, resultant will be z rotation
float dx = testPos[0] - enemyPos[0];
float dy = testPos[1] - enemyPos[1];
float angActual;
if (dx == 0) {
// avoid divide by zero error
angActual = (float)tan(dy / (1 / 1e12f));
} else {
angActual = (float)tan(dy / dx);
}
// see if our heading angle is within the bounds set by deviation
// (X) only compare to z-rotation since that's all we're using
if (((angActual + deviation / 2) > enemyAzimuth) &&
((angActual - deviation / 2) < enemyAzimuth)) {
return true;
} else {
return false;
}
}
const bool SpawnPosition::isImminentlyDangerous() const
{
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {
std::string pflag = flag[player[i].getFlag()].flag.type->flagAbbv;
float *enemyPos = lastState[i].pos;
float enemyAngle = lastState[i].azimuth;
// check for dangerous flags, etc
// FIXME: any more?
if (pflag == "L") { // don't spawn in the line of sight of an L
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { // he's looking within 20 degrees of spawn point
return true; // eek, don't spawn here
}
} else if (pflag == "SW") { // don't spawn next to a SW
if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW
return true; // eek, don't spawn here
}
}
// don't spawn in the line of sight of a normal-shot tank within a certain distance
if (distanceFrom(enemyPos) < safeDistance) { // within danger zone?
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { //and he's looking at me
return true;
}
}
}
}
// TODO: should check world weapons also
return false;
}
const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const
{
float worstDist = 1e12f; // huge number
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {
float *enemyPos = lastState[i].pos;
if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {
float x = enemyPos[0] - testPos[0];
float y = enemyPos[1] - testPos[1];
float distSq = x * x + y * y;
if (distSq < worstDist) {
worstDist = distSq;
enemyAngle = lastState[i].azimuth;
}
}
}
}
return sqrtf(worstDist);
}
const float SpawnPosition::distanceFrom(const float* farPos) const
{
float dx = farPos[0] - testPos[0];
float dy = farPos[1] - testPos[1];
float dz = farPos[2] - testPos[2];
return (float)sqrt(dx*dx + dy*dy + dz*dz);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_webrequest_time_tracker.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_warning_set.h"
#include "chrome/browser/profiles/profile_manager.h"
using content::BrowserThread;
// TODO(mpcomplete): tweak all these constants.
namespace {
// The number of requests we keep track of at a time.
const size_t kMaxRequestsLogged = 100u;
// If a request completes faster than this amount (in ms), then we ignore it.
// Any delays on such a request was negligible.
const int kMinRequestTimeToCareMs = 10;
// Thresholds above which we consider a delay caused by an extension to be "too
// much". This is given in percentage of total request time that was spent
// waiting on the extension.
const double kThresholdModerateDelay = 0.20;
const double kThresholdExcessiveDelay = 0.50;
// If this many requests (of the past kMaxRequestsLogged) have had "too much"
// delay, then we will warn the user.
const size_t kNumModerateDelaysBeforeWarning = 50u;
const size_t kNumExcessiveDelaysBeforeWarning = 10u;
// Default implementation for ExtensionWebRequestTimeTrackerDelegate
// that sets a warning in the extension service of |profile|.
class DefaultDelegate : public ExtensionWebRequestTimeTrackerDelegate {
public:
virtual ~DefaultDelegate() {}
// Implementation of ExtensionWebRequestTimeTrackerDelegate.
virtual void NotifyExcessiveDelays(
void* profile,
size_t num_delayed_messages,
size_t total_num_messages,
const std::set<std::string>& extension_ids) OVERRIDE;
virtual void NotifyModerateDelays(
void* profile,
size_t num_delayed_messages,
size_t total_num_messages,
const std::set<std::string>& extension_ids) OVERRIDE;
};
void DefaultDelegate::NotifyExcessiveDelays(
void* profile,
size_t num_delayed_messages,
size_t total_num_messages,
const std::set<std::string>& extension_ids) {
// TODO(battre) Enable warning the user if extensions misbehave as soon as we
// have data that allows us to decide on reasonable limits for triggering the
// warnings.
// BrowserThread::PostTask(
// BrowserThread::UI,
// FROM_HERE,
// base::Bind(&ExtensionWarningSet::NotifyWarningsOnUI,
// profile,
// extension_ids,
// ExtensionWarningSet::kNetworkDelay));
}
void DefaultDelegate::NotifyModerateDelays(
void* profile,
size_t num_delayed_messages,
size_t total_num_messages,
const std::set<std::string>& extension_ids) {
// TODO(battre) Enable warning the user if extensions misbehave as soon as we
// have data that allows us to decide on reasonable limits for triggering the
// warnings.
// BrowserThread::PostTask(
// BrowserThread::UI,
// FROM_HERE,
// base::Bind(&ExtensionWarningSet::NotifyWarningsOnUI,
// profile,
// extension_ids,
// ExtensionWarningSet::kNetworkDelay));
}
} // namespace
ExtensionWebRequestTimeTracker::RequestTimeLog::RequestTimeLog()
: profile(NULL), completed(false) {
}
ExtensionWebRequestTimeTracker::RequestTimeLog::~RequestTimeLog() {
}
ExtensionWebRequestTimeTracker::ExtensionWebRequestTimeTracker()
: delegate_(new DefaultDelegate) {
}
ExtensionWebRequestTimeTracker::~ExtensionWebRequestTimeTracker() {
}
void ExtensionWebRequestTimeTracker::LogRequestStartTime(
int64 request_id,
const base::Time& start_time,
const GURL& url,
void* profile) {
// Trim old completed request logs.
while (request_ids_.size() > kMaxRequestsLogged) {
int64 to_remove = request_ids_.front();
request_ids_.pop();
std::map<int64, RequestTimeLog>::iterator iter =
request_time_logs_.find(to_remove);
if (iter != request_time_logs_.end() && iter->second.completed) {
request_time_logs_.erase(iter);
moderate_delays_.erase(to_remove);
excessive_delays_.erase(to_remove);
}
}
request_ids_.push(request_id);
if (request_time_logs_.find(request_id) != request_time_logs_.end()) {
RequestTimeLog& log = request_time_logs_[request_id];
DCHECK(!log.completed);
return;
}
RequestTimeLog& log = request_time_logs_[request_id];
log.request_start_time = start_time;
log.url = url;
log.profile = profile;
}
void ExtensionWebRequestTimeTracker::LogRequestEndTime(
int64 request_id, const base::Time& end_time) {
if (request_time_logs_.find(request_id) == request_time_logs_.end())
return;
RequestTimeLog& log = request_time_logs_[request_id];
if (log.completed)
return;
log.request_duration = end_time - log.request_start_time;
log.completed = true;
if (log.extension_block_durations.empty())
return;
UMA_HISTOGRAM_TIMES("Extensions.NetworkDelay", log.block_duration);
Analyze(request_id);
}
std::set<std::string> ExtensionWebRequestTimeTracker::GetExtensionIds(
const RequestTimeLog& log) const {
std::set<std::string> result;
for (std::map<std::string, base::TimeDelta>::const_iterator i =
log.extension_block_durations.begin();
i != log.extension_block_durations.end();
++i) {
result.insert(i->first);
}
return result;
}
void ExtensionWebRequestTimeTracker::Analyze(int64 request_id) {
RequestTimeLog& log = request_time_logs_[request_id];
// Ignore really short requests. Time spent on these is negligible, and any
// extra delay the extension adds is likely to be noise.
if (log.request_duration.InMilliseconds() < kMinRequestTimeToCareMs)
return;
double percentage =
log.block_duration.InMillisecondsF() /
log.request_duration.InMillisecondsF();
VLOG(1) << "WR percent " << request_id << ": " << log.url << ": " <<
log.block_duration.InMilliseconds() << "/" <<
log.request_duration.InMilliseconds() << " = " << percentage;
// TODO(mpcomplete): blame a specific extension. Maybe go through the list
// of recent requests and find the extension that has caused the most delays.
if (percentage > kThresholdExcessiveDelay) {
excessive_delays_.insert(request_id);
if (excessive_delays_.size() > kNumExcessiveDelaysBeforeWarning) {
VLOG(1) << "WR excessive delays:" << excessive_delays_.size();
if (delegate_.get()) {
delegate_->NotifyExcessiveDelays(log.profile,
excessive_delays_.size(),
request_ids_.size(),
GetExtensionIds(log));
}
}
} else if (percentage > kThresholdModerateDelay) {
moderate_delays_.insert(request_id);
if (moderate_delays_.size() + excessive_delays_.size() >
kNumModerateDelaysBeforeWarning) {
VLOG(1) << "WR moderate delays:" << moderate_delays_.size();
if (delegate_.get()) {
delegate_->NotifyModerateDelays(
log.profile,
moderate_delays_.size() + excessive_delays_.size(),
request_ids_.size(),
GetExtensionIds(log));
}
}
}
}
void ExtensionWebRequestTimeTracker::IncrementExtensionBlockTime(
const std::string& extension_id,
int64 request_id,
const base::TimeDelta& block_time) {
if (request_time_logs_.find(request_id) == request_time_logs_.end())
return;
RequestTimeLog& log = request_time_logs_[request_id];
log.extension_block_durations[extension_id] += block_time;
}
void ExtensionWebRequestTimeTracker::IncrementTotalBlockTime(
int64 request_id,
const base::TimeDelta& block_time) {
if (request_time_logs_.find(request_id) == request_time_logs_.end())
return;
RequestTimeLog& log = request_time_logs_[request_id];
log.block_duration += block_time;
}
void ExtensionWebRequestTimeTracker::SetRequestCanceled(int64 request_id) {
// Canceled requests won't actually hit the network, so we can't compare
// their request time to the time spent waiting on the extension. Just ignore
// them.
// TODO(mpcomplete): may want to count cancels as "bonuses" for an extension.
// i.e. if it slows down 50% of requests but cancels 25% of the rest, that
// might average out to only being "25% slow".
request_time_logs_.erase(request_id);
}
void ExtensionWebRequestTimeTracker::SetRequestRedirected(int64 request_id) {
// When a request is redirected, we have no way of knowing how long the
// request would have taken, so we can't say how much an extension slowed
// down this request. Just ignore it.
request_time_logs_.erase(request_id);
}
void ExtensionWebRequestTimeTracker::SetDelegate(
ExtensionWebRequestTimeTrackerDelegate* delegate) {
delegate_.reset(delegate);
}
<commit_msg>Add UMA histogram on percentage of network duration spent waiting on extension<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_webrequest_time_tracker.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_warning_set.h"
#include "chrome/browser/profiles/profile_manager.h"
using content::BrowserThread;
// TODO(mpcomplete): tweak all these constants.
namespace {
// The number of requests we keep track of at a time.
const size_t kMaxRequestsLogged = 100u;
// If a request completes faster than this amount (in ms), then we ignore it.
// Any delays on such a request was negligible.
const int kMinRequestTimeToCareMs = 10;
// Thresholds above which we consider a delay caused by an extension to be "too
// much". This is given in percentage of total request time that was spent
// waiting on the extension.
const double kThresholdModerateDelay = 0.20;
const double kThresholdExcessiveDelay = 0.50;
// If this many requests (of the past kMaxRequestsLogged) have had "too much"
// delay, then we will warn the user.
const size_t kNumModerateDelaysBeforeWarning = 50u;
const size_t kNumExcessiveDelaysBeforeWarning = 10u;
// Default implementation for ExtensionWebRequestTimeTrackerDelegate
// that sets a warning in the extension service of |profile|.
class DefaultDelegate : public ExtensionWebRequestTimeTrackerDelegate {
public:
virtual ~DefaultDelegate() {}
// Implementation of ExtensionWebRequestTimeTrackerDelegate.
virtual void NotifyExcessiveDelays(
void* profile,
size_t num_delayed_messages,
size_t total_num_messages,
const std::set<std::string>& extension_ids) OVERRIDE;
virtual void NotifyModerateDelays(
void* profile,
size_t num_delayed_messages,
size_t total_num_messages,
const std::set<std::string>& extension_ids) OVERRIDE;
};
void DefaultDelegate::NotifyExcessiveDelays(
void* profile,
size_t num_delayed_messages,
size_t total_num_messages,
const std::set<std::string>& extension_ids) {
// TODO(battre) Enable warning the user if extensions misbehave as soon as we
// have data that allows us to decide on reasonable limits for triggering the
// warnings.
// BrowserThread::PostTask(
// BrowserThread::UI,
// FROM_HERE,
// base::Bind(&ExtensionWarningSet::NotifyWarningsOnUI,
// profile,
// extension_ids,
// ExtensionWarningSet::kNetworkDelay));
}
void DefaultDelegate::NotifyModerateDelays(
void* profile,
size_t num_delayed_messages,
size_t total_num_messages,
const std::set<std::string>& extension_ids) {
// TODO(battre) Enable warning the user if extensions misbehave as soon as we
// have data that allows us to decide on reasonable limits for triggering the
// warnings.
// BrowserThread::PostTask(
// BrowserThread::UI,
// FROM_HERE,
// base::Bind(&ExtensionWarningSet::NotifyWarningsOnUI,
// profile,
// extension_ids,
// ExtensionWarningSet::kNetworkDelay));
}
} // namespace
ExtensionWebRequestTimeTracker::RequestTimeLog::RequestTimeLog()
: profile(NULL), completed(false) {
}
ExtensionWebRequestTimeTracker::RequestTimeLog::~RequestTimeLog() {
}
ExtensionWebRequestTimeTracker::ExtensionWebRequestTimeTracker()
: delegate_(new DefaultDelegate) {
}
ExtensionWebRequestTimeTracker::~ExtensionWebRequestTimeTracker() {
}
void ExtensionWebRequestTimeTracker::LogRequestStartTime(
int64 request_id,
const base::Time& start_time,
const GURL& url,
void* profile) {
// Trim old completed request logs.
while (request_ids_.size() > kMaxRequestsLogged) {
int64 to_remove = request_ids_.front();
request_ids_.pop();
std::map<int64, RequestTimeLog>::iterator iter =
request_time_logs_.find(to_remove);
if (iter != request_time_logs_.end() && iter->second.completed) {
request_time_logs_.erase(iter);
moderate_delays_.erase(to_remove);
excessive_delays_.erase(to_remove);
}
}
request_ids_.push(request_id);
if (request_time_logs_.find(request_id) != request_time_logs_.end()) {
RequestTimeLog& log = request_time_logs_[request_id];
DCHECK(!log.completed);
return;
}
RequestTimeLog& log = request_time_logs_[request_id];
log.request_start_time = start_time;
log.url = url;
log.profile = profile;
}
void ExtensionWebRequestTimeTracker::LogRequestEndTime(
int64 request_id, const base::Time& end_time) {
if (request_time_logs_.find(request_id) == request_time_logs_.end())
return;
RequestTimeLog& log = request_time_logs_[request_id];
if (log.completed)
return;
log.request_duration = end_time - log.request_start_time;
log.completed = true;
if (log.extension_block_durations.empty())
return;
UMA_HISTOGRAM_TIMES("Extensions.NetworkDelay", log.block_duration);
Analyze(request_id);
}
std::set<std::string> ExtensionWebRequestTimeTracker::GetExtensionIds(
const RequestTimeLog& log) const {
std::set<std::string> result;
for (std::map<std::string, base::TimeDelta>::const_iterator i =
log.extension_block_durations.begin();
i != log.extension_block_durations.end();
++i) {
result.insert(i->first);
}
return result;
}
void ExtensionWebRequestTimeTracker::Analyze(int64 request_id) {
RequestTimeLog& log = request_time_logs_[request_id];
// Ignore really short requests. Time spent on these is negligible, and any
// extra delay the extension adds is likely to be noise.
if (log.request_duration.InMilliseconds() < kMinRequestTimeToCareMs)
return;
double percentage =
log.block_duration.InMillisecondsF() /
log.request_duration.InMillisecondsF();
UMA_HISTOGRAM_PERCENTAGE("Extensions.NetworkDelayPercentage",
static_cast<int>(100*percentage));
VLOG(1) << "WR percent " << request_id << ": " << log.url << ": " <<
log.block_duration.InMilliseconds() << "/" <<
log.request_duration.InMilliseconds() << " = " << percentage;
// TODO(mpcomplete): blame a specific extension. Maybe go through the list
// of recent requests and find the extension that has caused the most delays.
if (percentage > kThresholdExcessiveDelay) {
excessive_delays_.insert(request_id);
if (excessive_delays_.size() > kNumExcessiveDelaysBeforeWarning) {
VLOG(1) << "WR excessive delays:" << excessive_delays_.size();
if (delegate_.get()) {
delegate_->NotifyExcessiveDelays(log.profile,
excessive_delays_.size(),
request_ids_.size(),
GetExtensionIds(log));
}
}
} else if (percentage > kThresholdModerateDelay) {
moderate_delays_.insert(request_id);
if (moderate_delays_.size() + excessive_delays_.size() >
kNumModerateDelaysBeforeWarning) {
VLOG(1) << "WR moderate delays:" << moderate_delays_.size();
if (delegate_.get()) {
delegate_->NotifyModerateDelays(
log.profile,
moderate_delays_.size() + excessive_delays_.size(),
request_ids_.size(),
GetExtensionIds(log));
}
}
}
}
void ExtensionWebRequestTimeTracker::IncrementExtensionBlockTime(
const std::string& extension_id,
int64 request_id,
const base::TimeDelta& block_time) {
if (request_time_logs_.find(request_id) == request_time_logs_.end())
return;
RequestTimeLog& log = request_time_logs_[request_id];
log.extension_block_durations[extension_id] += block_time;
}
void ExtensionWebRequestTimeTracker::IncrementTotalBlockTime(
int64 request_id,
const base::TimeDelta& block_time) {
if (request_time_logs_.find(request_id) == request_time_logs_.end())
return;
RequestTimeLog& log = request_time_logs_[request_id];
log.block_duration += block_time;
}
void ExtensionWebRequestTimeTracker::SetRequestCanceled(int64 request_id) {
// Canceled requests won't actually hit the network, so we can't compare
// their request time to the time spent waiting on the extension. Just ignore
// them.
// TODO(mpcomplete): may want to count cancels as "bonuses" for an extension.
// i.e. if it slows down 50% of requests but cancels 25% of the rest, that
// might average out to only being "25% slow".
request_time_logs_.erase(request_id);
}
void ExtensionWebRequestTimeTracker::SetRequestRedirected(int64 request_id) {
// When a request is redirected, we have no way of knowing how long the
// request would have taken, so we can't say how much an extension slowed
// down this request. Just ignore it.
request_time_logs_.erase(request_id);
}
void ExtensionWebRequestTimeTracker::SetDelegate(
ExtensionWebRequestTimeTrackerDelegate* delegate) {
delegate_.reset(delegate);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This test performs a series false positive checks using a list of URLs
// against a known set of SafeBrowsing data.
//
// It uses a normal SafeBrowsing database to create a bloom filter where it
// looks up all the URLs in the url file. A URL that has a prefix found in the
// bloom filter and found in the database is considered a hit: a valid lookup
// that will result in a gethash request. A URL that has a prefix found in the
// bloom filter but not in the database is a miss: a false positive lookup that
// will result in an unnecessary gethash request.
//
// By varying the size of the bloom filter and using a constant set of
// SafeBrowsing data, we can check a known set of URLs against the filter and
// determine the false positive rate.
//
// False positive calculation usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives
// --filter-start=<integer>
// --filter-steps=<integer>
// --filter-verbose
//
// --filter-start: The filter multiplier to begin with. This represents the
// number of bits per prefix of memory to use in the filter.
// The default value is identical to the current SafeBrowsing
// database value.
// --filter-steps: The number of iterations to run, with each iteration
// increasing the filter multiplier by 1. The default value
// is 1.
// --filter-verbose: Used to print out the hit / miss results per URL.
// --filter-csv: The URL file contains information about the number of
// unique views (the popularity) of each URL. See the format
// description below.
//
//
// Hash compute time usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.HashTime
// --filter-num-checks=<integer>
//
// --filter-num-checks: The number of hash look ups to perform on the bloom
// filter. The default is 10 million.
//
// Data files:
// chrome/test/data/safe_browsing/filter/database
// chrome/test/data/safe_browsing/filter/urls
//
// database: A normal SafeBrowsing database.
// urls: A text file containing a list of URLs, one per line. If the option
// --filter-csv is specified, the format of each line in the file is
// <url>,<weight> where weight is an integer indicating the number of
// unique views for the URL.
#include <fstream>
#include <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/scoped_ptr.h"
#include "base/sha2.h"
#include "base/string_util.h"
#include "base/time.h"
#include "chrome/browser/safe_browsing/bloom_filter.h"
#include "chrome/browser/safe_browsing/safe_browsing_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/sqlite_compiled_statement.h"
#include "chrome/common/sqlite_utils.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
namespace {
// Ensures the SafeBrowsing database is closed properly.
class ScopedPerfDatabase {
public:
explicit ScopedPerfDatabase(sqlite3* db) : db_(db) {}
~ScopedPerfDatabase() {
sqlite3_close(db_);
}
private:
sqlite3* db_;
DISALLOW_COPY_AND_ASSIGN(ScopedPerfDatabase);
};
// Command line flags.
const wchar_t kFilterVerbose[] = L"filter-verbose";
const wchar_t kFilterStart[] = L"filter-start";
const wchar_t kFilterSteps[] = L"filter-steps";
const wchar_t kFilterCsv[] = L"filter-csv";
const wchar_t kFilterNumChecks[] = L"filter-num-checks";
// Number of hash checks to make during performance testing.
static const int kNumHashChecks = 10000000;
// Returns the path to the data used in this test, relative to the top of the
// source directory.
FilePath GetFullDataPath() {
FilePath full_path;
CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path));
full_path = full_path.Append(FILE_PATH_LITERAL("safe_browsing"));
full_path = full_path.Append(FILE_PATH_LITERAL("filter"));
CHECK(file_util::PathExists(full_path));
return full_path;
}
// Constructs a bloom filter of the appropriate size from the provided prefixes.
void BuildBloomFilter(int size_multiplier,
const std::vector<SBPrefix>& prefixes,
BloomFilter** bloom_filter) {
// Create a BloomFilter with the specified size.
const int key_count = std::max(static_cast<int>(prefixes.size()),
BloomFilter::kBloomFilterMinSize);
const int filter_size = key_count * size_multiplier;
*bloom_filter = new BloomFilter(filter_size);
// Add the prefixes to it.
for (size_t i = 0; i < prefixes.size(); ++i)
(*bloom_filter)->Insert(prefixes[i]);
std::cout << "Bloom filter with prefixes: " << prefixes.size()
<< ", multiplier: " << size_multiplier
<< ", size (bytes): " << (*bloom_filter)->size()
<< std::endl;
}
// Reads the set of add prefixes contained in a SafeBrowsing database into a
// sorted array suitable for fast searching. This takes significantly less time
// to look up a given prefix than performing SQL queries.
bool ReadDatabase(const FilePath& path, std::vector<SBPrefix>* prefixes) {
FilePath database_file = path.Append(FILE_PATH_LITERAL("database"));
sqlite3* db = NULL;
if (sqlite_utils::OpenSqliteDb(database_file, &db) != SQLITE_OK) {
sqlite3_close(db);
return false;
}
ScopedPerfDatabase database(db);
scoped_ptr<SqliteStatementCache> sql_cache(new SqliteStatementCache(db));
// Get the number of items in the add_prefix table.
std::string sql = "SELECT COUNT(*) FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(count_statement, *sql_cache, sql.c_str());
if (!count_statement.is_valid())
return false;
if (count_statement->step() != SQLITE_ROW)
return false;
const int count = count_statement->column_int(0);
// Load them into a prefix vector and sort
prefixes->reserve(count);
sql = "SELECT prefix FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(prefix_statement, *sql_cache, sql.c_str());
if (!prefix_statement.is_valid())
return false;
while (prefix_statement->step() == SQLITE_ROW)
prefixes->push_back(prefix_statement->column_int(0));
DCHECK(static_cast<int>(prefixes->size()) == count);
sort(prefixes->begin(), prefixes->end());
return true;
}
// Generates all legal SafeBrowsing prefixes for the specified URL, and returns
// the set of Prefixes that exist in the bloom filter. The function returns the
// number of host + path combinations checked.
int GeneratePrefixHits(const std::string url,
BloomFilter* bloom_filter,
std::vector<SBPrefix>* prefixes) {
GURL url_check(url);
std::vector<std::string> hosts;
if (url_check.HostIsIPAddress()) {
hosts.push_back(url_check.host());
} else {
safe_browsing_util::GenerateHostsToCheck(url_check, &hosts);
}
std::vector<std::string> paths;
safe_browsing_util::GeneratePathsToCheck(url_check, &paths);
for (size_t i = 0; i < hosts.size(); ++i) {
for (size_t j = 0; j < paths.size(); ++j) {
SBPrefix prefix;
base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix));
if (bloom_filter->Exists(prefix))
prefixes->push_back(prefix);
}
}
return hosts.size() * paths.size();
}
// Binary search of sorted prefixes.
bool IsPrefixInDatabase(SBPrefix prefix,
const std::vector<SBPrefix>& prefixes) {
if (prefixes.empty())
return false;
int low = 0;
int high = prefixes.size() - 1;
while (low <= high) {
int mid = ((unsigned int)low + (unsigned int)high) >> 1;
SBPrefix prefix_mid = prefixes[mid];
if (prefix_mid == prefix)
return true;
if (prefix_mid < prefix)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
// Construct a bloom filter with the given prefixes and multiplier, and test the
// false positive rate (misses) against a URL list.
void CalculateBloomFilterFalsePositives(
int size_multiplier,
const FilePath& data_dir,
const std::vector<SBPrefix>& prefix_list) {
BloomFilter* bloom_filter = NULL;
BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter);
scoped_refptr<BloomFilter> scoped_filter(bloom_filter);
// Read in data file line at a time.
FilePath url_file = data_dir.Append(FILE_PATH_LITERAL("urls"));
std::ifstream url_stream(WideToASCII(url_file.ToWStringHack()).c_str());
// Keep track of stats
int hits = 0;
int misses = 0;
int weighted_hits = 0;
int weighted_misses = 0;
int url_count = 0;
int prefix_count = 0;
// Print out volumes of data (per URL hit and miss information).
bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose);
bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv);
std::string url;
while (std::getline(url_stream, url)) {
++url_count;
// Handle a format that contains URLs weighted by unique views.
int weight = 1;
if (use_weights) {
std::string::size_type pos = url.find_last_of(",");
if (pos != std::string::npos) {
weight = StringToInt(std::string(url, pos + 1));
url = url.substr(0, pos);
}
}
// See if the URL is in the bloom filter.
std::vector<SBPrefix> prefixes;
prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes);
// See if the prefix is actually in the database (in-memory prefix list).
for (size_t i = 0; i < prefixes.size(); ++i) {
if (IsPrefixInDatabase(prefixes[i], prefix_list)) {
++hits;
weighted_hits += weight;
if (verbose) {
std::cout << "Hit for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
} else {
++misses;
weighted_misses += weight;
if (verbose) {
std::cout << "Miss for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
}
}
}
// Print out the results for this test.
std::cout << "URLs checked: " << url_count
<< ", prefix compares: " << prefix_count
<< ", hits: " << hits
<< ", misses: " << misses;
if (use_weights) {
std::cout << ", weighted hits: " << weighted_hits
<< ", weighted misses: " << weighted_misses;
}
std::cout << std::endl;
}
} // namespace
// This test can take several minutes to perform its calculations, so it should
// be disabled until you need to run it.
TEST(SafeBrowsingBloomFilter, FalsePositives) {
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
int start = BloomFilter::kBloomFilterSizeRatio;
if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterStart)) {
start = StringToInt(
CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterStart));
}
int steps = 1;
if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterSteps)) {
steps = StringToInt(
CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterSteps));
}
int stop = start + steps;
for (int multiplier = start; multiplier < stop; ++multiplier)
CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list);
}
// Computes the time required for performing a number of look ups in a bloom
// filter. This is useful for measuring the performance of new hash functions.
TEST(SafeBrowsingBloomFilter, HashTime) {
// Read the data from the database.
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
int num_checks = kNumHashChecks;
if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterNumChecks)) {
num_checks = StringToInt(
CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterNumChecks));
}
// Populate the bloom filter and measure the time.
BloomFilter* bloom_filter = NULL;
Time populate_before = Time::Now();
BuildBloomFilter(BloomFilter::kBloomFilterSizeRatio,
prefix_list, &bloom_filter);
TimeDelta populate = Time::Now() - populate_before;
// Check a large number of random prefixes against the filter.
int hits = 0;
Time check_before = Time::Now();
for (int i = 0; i < num_checks; ++i) {
uint32 prefix = static_cast<uint32>(base::RandUint64());
if (bloom_filter->Exists(prefix))
++hits;
}
TimeDelta check = Time::Now() - check_before;
int64 time_per_insert = populate.InMicroseconds() /
static_cast<int>(prefix_list.size());
int64 time_per_check = check.InMicroseconds() / num_checks;
std::cout << "Time results for checks: " << num_checks
<< ", prefixes: " << prefix_list.size()
<< ", populate time (ms): " << populate.InMilliseconds()
<< ", check time (ms): " << check.InMilliseconds()
<< ", hits: " << hits
<< ", per-populate (us): " << time_per_insert
<< ", per-check (us): " << time_per_check
<< std::endl;
}
<commit_msg>Fix the Windows build.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This test performs a series false positive checks using a list of URLs
// against a known set of SafeBrowsing data.
//
// It uses a normal SafeBrowsing database to create a bloom filter where it
// looks up all the URLs in the url file. A URL that has a prefix found in the
// bloom filter and found in the database is considered a hit: a valid lookup
// that will result in a gethash request. A URL that has a prefix found in the
// bloom filter but not in the database is a miss: a false positive lookup that
// will result in an unnecessary gethash request.
//
// By varying the size of the bloom filter and using a constant set of
// SafeBrowsing data, we can check a known set of URLs against the filter and
// determine the false positive rate.
//
// False positive calculation usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives
// --filter-start=<integer>
// --filter-steps=<integer>
// --filter-verbose
//
// --filter-start: The filter multiplier to begin with. This represents the
// number of bits per prefix of memory to use in the filter.
// The default value is identical to the current SafeBrowsing
// database value.
// --filter-steps: The number of iterations to run, with each iteration
// increasing the filter multiplier by 1. The default value
// is 1.
// --filter-verbose: Used to print out the hit / miss results per URL.
// --filter-csv: The URL file contains information about the number of
// unique views (the popularity) of each URL. See the format
// description below.
//
//
// Hash compute time usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.HashTime
// --filter-num-checks=<integer>
//
// --filter-num-checks: The number of hash look ups to perform on the bloom
// filter. The default is 10 million.
//
// Data files:
// chrome/test/data/safe_browsing/filter/database
// chrome/test/data/safe_browsing/filter/urls
//
// database: A normal SafeBrowsing database.
// urls: A text file containing a list of URLs, one per line. If the option
// --filter-csv is specified, the format of each line in the file is
// <url>,<weight> where weight is an integer indicating the number of
// unique views for the URL.
#include <fstream>
#include <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/scoped_ptr.h"
#include "base/sha2.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/time.h"
#include "chrome/browser/safe_browsing/bloom_filter.h"
#include "chrome/browser/safe_browsing/safe_browsing_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/sqlite_compiled_statement.h"
#include "chrome/common/sqlite_utils.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
namespace {
// Ensures the SafeBrowsing database is closed properly.
class ScopedPerfDatabase {
public:
explicit ScopedPerfDatabase(sqlite3* db) : db_(db) {}
~ScopedPerfDatabase() {
sqlite3_close(db_);
}
private:
sqlite3* db_;
DISALLOW_COPY_AND_ASSIGN(ScopedPerfDatabase);
};
// Command line flags.
const wchar_t kFilterVerbose[] = L"filter-verbose";
const wchar_t kFilterStart[] = L"filter-start";
const wchar_t kFilterSteps[] = L"filter-steps";
const wchar_t kFilterCsv[] = L"filter-csv";
const wchar_t kFilterNumChecks[] = L"filter-num-checks";
// Number of hash checks to make during performance testing.
static const int kNumHashChecks = 10000000;
// Returns the path to the data used in this test, relative to the top of the
// source directory.
FilePath GetFullDataPath() {
FilePath full_path;
CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path));
full_path = full_path.Append(FILE_PATH_LITERAL("safe_browsing"));
full_path = full_path.Append(FILE_PATH_LITERAL("filter"));
CHECK(file_util::PathExists(full_path));
return full_path;
}
// Constructs a bloom filter of the appropriate size from the provided prefixes.
void BuildBloomFilter(int size_multiplier,
const std::vector<SBPrefix>& prefixes,
BloomFilter** bloom_filter) {
// Create a BloomFilter with the specified size.
const int key_count = std::max(static_cast<int>(prefixes.size()),
BloomFilter::kBloomFilterMinSize);
const int filter_size = key_count * size_multiplier;
*bloom_filter = new BloomFilter(filter_size);
// Add the prefixes to it.
for (size_t i = 0; i < prefixes.size(); ++i)
(*bloom_filter)->Insert(prefixes[i]);
std::cout << "Bloom filter with prefixes: " << prefixes.size()
<< ", multiplier: " << size_multiplier
<< ", size (bytes): " << (*bloom_filter)->size()
<< std::endl;
}
// Reads the set of add prefixes contained in a SafeBrowsing database into a
// sorted array suitable for fast searching. This takes significantly less time
// to look up a given prefix than performing SQL queries.
bool ReadDatabase(const FilePath& path, std::vector<SBPrefix>* prefixes) {
FilePath database_file = path.Append(FILE_PATH_LITERAL("database"));
sqlite3* db = NULL;
if (sqlite_utils::OpenSqliteDb(database_file, &db) != SQLITE_OK) {
sqlite3_close(db);
return false;
}
ScopedPerfDatabase database(db);
scoped_ptr<SqliteStatementCache> sql_cache(new SqliteStatementCache(db));
// Get the number of items in the add_prefix table.
std::string sql = "SELECT COUNT(*) FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(count_statement, *sql_cache, sql.c_str());
if (!count_statement.is_valid())
return false;
if (count_statement->step() != SQLITE_ROW)
return false;
const int count = count_statement->column_int(0);
// Load them into a prefix vector and sort
prefixes->reserve(count);
sql = "SELECT prefix FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(prefix_statement, *sql_cache, sql.c_str());
if (!prefix_statement.is_valid())
return false;
while (prefix_statement->step() == SQLITE_ROW)
prefixes->push_back(prefix_statement->column_int(0));
DCHECK(static_cast<int>(prefixes->size()) == count);
sort(prefixes->begin(), prefixes->end());
return true;
}
// Generates all legal SafeBrowsing prefixes for the specified URL, and returns
// the set of Prefixes that exist in the bloom filter. The function returns the
// number of host + path combinations checked.
int GeneratePrefixHits(const std::string url,
BloomFilter* bloom_filter,
std::vector<SBPrefix>* prefixes) {
GURL url_check(url);
std::vector<std::string> hosts;
if (url_check.HostIsIPAddress()) {
hosts.push_back(url_check.host());
} else {
safe_browsing_util::GenerateHostsToCheck(url_check, &hosts);
}
std::vector<std::string> paths;
safe_browsing_util::GeneratePathsToCheck(url_check, &paths);
for (size_t i = 0; i < hosts.size(); ++i) {
for (size_t j = 0; j < paths.size(); ++j) {
SBPrefix prefix;
base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix));
if (bloom_filter->Exists(prefix))
prefixes->push_back(prefix);
}
}
return hosts.size() * paths.size();
}
// Binary search of sorted prefixes.
bool IsPrefixInDatabase(SBPrefix prefix,
const std::vector<SBPrefix>& prefixes) {
if (prefixes.empty())
return false;
int low = 0;
int high = prefixes.size() - 1;
while (low <= high) {
int mid = ((unsigned int)low + (unsigned int)high) >> 1;
SBPrefix prefix_mid = prefixes[mid];
if (prefix_mid == prefix)
return true;
if (prefix_mid < prefix)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
// Construct a bloom filter with the given prefixes and multiplier, and test the
// false positive rate (misses) against a URL list.
void CalculateBloomFilterFalsePositives(
int size_multiplier,
const FilePath& data_dir,
const std::vector<SBPrefix>& prefix_list) {
BloomFilter* bloom_filter = NULL;
BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter);
scoped_refptr<BloomFilter> scoped_filter(bloom_filter);
// Read in data file line at a time.
FilePath url_file = data_dir.Append(FILE_PATH_LITERAL("urls"));
std::ifstream url_stream(WideToASCII(url_file.ToWStringHack()).c_str());
// Keep track of stats
int hits = 0;
int misses = 0;
int weighted_hits = 0;
int weighted_misses = 0;
int url_count = 0;
int prefix_count = 0;
// Print out volumes of data (per URL hit and miss information).
bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose);
bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv);
std::string url;
while (std::getline(url_stream, url)) {
++url_count;
// Handle a format that contains URLs weighted by unique views.
int weight = 1;
if (use_weights) {
std::string::size_type pos = url.find_last_of(",");
if (pos != std::string::npos) {
base::StringToInt(std::string(url, pos + 1), &weight);
url = url.substr(0, pos);
}
}
// See if the URL is in the bloom filter.
std::vector<SBPrefix> prefixes;
prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes);
// See if the prefix is actually in the database (in-memory prefix list).
for (size_t i = 0; i < prefixes.size(); ++i) {
if (IsPrefixInDatabase(prefixes[i], prefix_list)) {
++hits;
weighted_hits += weight;
if (verbose) {
std::cout << "Hit for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
} else {
++misses;
weighted_misses += weight;
if (verbose) {
std::cout << "Miss for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
}
}
}
// Print out the results for this test.
std::cout << "URLs checked: " << url_count
<< ", prefix compares: " << prefix_count
<< ", hits: " << hits
<< ", misses: " << misses;
if (use_weights) {
std::cout << ", weighted hits: " << weighted_hits
<< ", weighted misses: " << weighted_misses;
}
std::cout << std::endl;
}
} // namespace
// This test can take several minutes to perform its calculations, so it should
// be disabled until you need to run it.
TEST(SafeBrowsingBloomFilter, FalsePositives) {
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
int start = BloomFilter::kBloomFilterSizeRatio;
if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterStart)) {
base::StringToInt(
CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterStart),
&start);
}
int steps = 1;
if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterSteps)) {
base::StringToInt(
CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterSteps),
&steps);
}
int stop = start + steps;
for (int multiplier = start; multiplier < stop; ++multiplier)
CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list);
}
// Computes the time required for performing a number of look ups in a bloom
// filter. This is useful for measuring the performance of new hash functions.
TEST(SafeBrowsingBloomFilter, HashTime) {
// Read the data from the database.
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
int num_checks = kNumHashChecks;
if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterNumChecks)) {
base::StringToInt(
CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterNumChecks),
&num_checks);
}
// Populate the bloom filter and measure the time.
BloomFilter* bloom_filter = NULL;
Time populate_before = Time::Now();
BuildBloomFilter(BloomFilter::kBloomFilterSizeRatio,
prefix_list, &bloom_filter);
TimeDelta populate = Time::Now() - populate_before;
// Check a large number of random prefixes against the filter.
int hits = 0;
Time check_before = Time::Now();
for (int i = 0; i < num_checks; ++i) {
uint32 prefix = static_cast<uint32>(base::RandUint64());
if (bloom_filter->Exists(prefix))
++hits;
}
TimeDelta check = Time::Now() - check_before;
int64 time_per_insert = populate.InMicroseconds() /
static_cast<int>(prefix_list.size());
int64 time_per_check = check.InMicroseconds() / num_checks;
std::cout << "Time results for checks: " << num_checks
<< ", prefixes: " << prefix_list.size()
<< ", populate time (ms): " << populate.InMilliseconds()
<< ", check time (ms): " << check.InMilliseconds()
<< ", hits: " << hits
<< ", per-populate (us): " << time_per_insert
<< ", per-check (us): " << time_per_check
<< std::endl;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MNSMozabProxy.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:28:06 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_MAB_MOZABHELPER_HXX_
#include "MNSMozabProxy.hxx"
#endif
#ifndef _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_
#include "MDatabaseMetaDataHelper.hxx"
#endif
#ifndef _CONNECTIVITY_MAB_QUERY_HXX_
#include "MQuery.hxx"
#endif
#include <nsIProxyObjectManager.h>
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif
// More Mozilla includes for LDAP Connection Test
#include "prprf.h"
#include "nsILDAPURL.h"
#include "nsILDAPMessage.h"
#include "nsILDAPMessageListener.h"
#include "nsILDAPErrors.h"
#include "nsILDAPConnection.h"
#include "nsILDAPOperation.h"
#ifndef _CONNECTIVITY_MAB_QUERY_HXX_
#include "MQuery.hxx"
#endif
#ifndef _CONNECTIVITY_MAB_QUERYHELPER_HXX_
#include <MQueryHelper.hxx>
#endif
#include <com/sun/star/uno/Reference.hxx>
#include <unotools/processfactory.hxx>
#ifndef _COM_SUN_STAR_MOZILLA_XPROXYRUNNER_HPP_
#include "com/sun/star/mozilla/XProxyRunner.hpp"
#endif
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::mozilla;
#define TYPEASSERT(value,type) if (value != type) return !NS_OK;
using namespace connectivity::mozab;
/* Implementation file */
static ::osl::Mutex m_aThreadMutex;
extern nsresult NewAddressBook(const ::rtl::OUString * aName);
MNSMozabProxy::MNSMozabProxy()
{
m_Args = NULL;
#if OSL_DEBUG_LEVEL > 0
m_oThreadID = osl_getThreadIdentifier(NULL);
#endif
acquire();
}
MNSMozabProxy::~MNSMozabProxy()
{
}
sal_Int32 MNSMozabProxy::StartProxy(RunArgs * args,::com::sun::star::mozilla::MozillaProductType aProduct,const ::rtl::OUString &aProfile)
{
OSL_TRACE( "IN : MNSMozabProxy::StartProxy() \n" );
::osl::MutexGuard aGuard(m_aThreadMutex);
m_Product = aProduct;
m_Profile = aProfile;
m_Args = args;
if (!xRunner.is())
{
Reference<XMultiServiceFactory> xFactory = ::comphelper::getProcessServiceFactory();
OSL_ENSURE( xFactory.is(), "can't get service factory" );
::com::sun::star::uno::Reference<XInterface> xInstance = xFactory->createInstance(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")) );
OSL_ENSURE( xInstance.is(), "failed to create instance" );
xRunner = ::com::sun::star::uno::Reference< ::com::sun::star::mozilla::XProxyRunner >(xInstance,UNO_QUERY);
}
const ::com::sun::star::uno::Reference< ::com::sun::star::mozilla::XCodeProxy > aCode(this);
return xRunner->Run(aCode);
}
extern nsresult getTableStringsProxied(const sal_Char* sAbURI, sal_Int32 *nDirectoryType,MNameMapper *nmap,
::std::vector< ::rtl::OUString >* _rStrings,
::std::vector< ::rtl::OUString >* _rTypes,
rtl::OUString * sError);
::com::sun::star::mozilla::MozillaProductType SAL_CALL MNSMozabProxy::getProductType( ) throw (::com::sun::star::uno::RuntimeException)
{
return m_Product;
}
::rtl::OUString SAL_CALL MNSMozabProxy::getProfileName( ) throw (::com::sun::star::uno::RuntimeException)
{
return m_Profile;
}
sal_Int32 SAL_CALL MNSMozabProxy::run( ) throw (::com::sun::star::uno::RuntimeException)
{
#if OSL_DEBUG_LEVEL > 0
OSL_TRACE( "IN : MNSMozabProxy::Run() Caller thread :%4d \n" , m_oThreadID );
#else
OSL_TRACE( "IN : MNSMozabProxy::Run() \n" );
#endif
nsresult rv = NS_ERROR_INVALID_ARG;
if (m_Args == NULL)
return NS_ERROR_INVALID_ARG;
switch(m_Args->funcIndex)
{
case ProxiedFunc::FUNC_TESTLDAP_INIT_LDAP:
case ProxiedFunc::FUNC_TESTLDAP_IS_LDAP_CONNECTED:
case ProxiedFunc::FUNC_TESTLDAP_RELEASE_RESOURCE:
rv = testLDAPConnection();
break;
case ProxiedFunc::FUNC_GET_TABLE_STRINGS:
rv = getTableStringsProxied((const sal_Char*)m_Args->arg1,
(sal_Int32 *)m_Args->arg2,
(MNameMapper *)m_Args->arg3,
(::std::vector< ::rtl::OUString >*)m_Args->arg4,
(::std::vector< ::rtl::OUString >*)m_Args->arg5,
(rtl::OUString *)m_Args->arg6);
break;
case ProxiedFunc::FUNC_EXECUTE_QUERY:
if (m_Args->arg1 && m_Args->arg2)
{
rv = ((MQuery*)m_Args->arg1)->executeQueryProxied((OConnection*)m_Args->arg2);
}
break;
case ProxiedFunc::FUNC_QUERYHELPER_CREATE_NEW_CARD:
case ProxiedFunc::FUNC_QUERYHELPER_DELETE_CARD:
case ProxiedFunc::FUNC_QUERYHELPER_COMMIT_CARD:
case ProxiedFunc::FUNC_QUERYHELPER_RESYNC_CARD:
if (m_Args->arg1)
{
rv = QueryHelperStub();
}
break;
case ProxiedFunc::FUNC_NEW_ADDRESS_BOOK:
if (m_Args->arg1)
{
rv = NewAddressBook((const ::rtl::OUString*)m_Args->arg1 );
}
break;
default:
return NS_ERROR_INVALID_ARG;
}
return rv;
}
nsresult MNSMozabProxy::QueryHelperStub()
{
nsresult rv = NS_ERROR_INVALID_ARG;
MQueryHelper * mHelper=(MQueryHelper*) m_Args->arg1;
switch(m_Args->funcIndex)
{
case ProxiedFunc::FUNC_QUERYHELPER_CREATE_NEW_CARD:
if (m_Args->arg2 ) //m_Args->arg2 used to return cord number
{
*((sal_Int32*)m_Args->arg2) = mHelper->createNewCard();
rv = NS_OK;
}
break;
case ProxiedFunc::FUNC_QUERYHELPER_DELETE_CARD:
if (m_Args->arg2 && m_Args->arg3 ) //m_Args->arg2 used to get the cord number
{
rv = mHelper->deleteCard(*((sal_Int32*)m_Args->arg2),(nsIAbDirectory*)m_Args->arg3);
}
break;
case ProxiedFunc::FUNC_QUERYHELPER_COMMIT_CARD:
if (m_Args->arg2 && m_Args->arg3 ) //m_Args->arg2 used to get the cord number
{
rv = mHelper->commitCard(*((sal_Int32*)m_Args->arg2),(nsIAbDirectory*)m_Args->arg3);
}
break;
case ProxiedFunc::FUNC_QUERYHELPER_RESYNC_CARD:
if (m_Args->arg2) //m_Args->arg2 used to get the cord number
{
rv = mHelper->resyncRow(*((sal_Int32*)m_Args->arg2));
}
break;
default:
break;
}
return rv;
}
//-------------------------------------------------------------------
#define NS_LDAPCONNECTION_CONTRACTID "@mozilla.org/network/ldap-connection;1"
#define NS_LDAPOPERATION_CONTRACTID "@mozilla.org/network/ldap-operation;1"
#define NS_LDAPMESSAGE_CONTRACTID "@mozilla.org/network/ldap-message;1"
#define NS_LDAPURL_CONTRACTID "@mozilla.org/network/ldap-url;1"
namespace connectivity {
namespace mozab {
class MLDAPMessageListener : public nsILDAPMessageListener {
NS_DECL_ISUPPORTS
NS_DECL_NSILDAPMESSAGELISTENER
MLDAPMessageListener();
~MLDAPMessageListener();
sal_Bool connected();
protected:
::osl::Mutex m_aMutex;
::osl::Condition m_aCondition;
sal_Bool m_IsComplete;
sal_Bool m_GoodConnection;
void setConnectionStatus( sal_Bool _good );
};
}
}
NS_IMPL_THREADSAFE_ISUPPORTS1(MLDAPMessageListener, nsILDAPMessageListener)
MLDAPMessageListener::MLDAPMessageListener()
: mRefCnt( 0 )
, m_IsComplete( sal_False )
, m_GoodConnection( sal_False )
{
m_aCondition.reset();
}
MLDAPMessageListener::~MLDAPMessageListener()
{
}
sal_Bool MLDAPMessageListener::connected()
{
return m_aCondition.check();
}
void MLDAPMessageListener::setConnectionStatus( sal_Bool _good )
{
::osl::MutexGuard aGuard( m_aMutex );
m_IsComplete = sal_True;
m_GoodConnection = _good;
m_aCondition.set();
}
NS_IMETHODIMP MLDAPMessageListener::OnLDAPInit(nsILDAPConnection *aConn, nsresult aStatus )
{
// Make sure that the Init() worked properly
if ( NS_FAILED(aStatus ) ) {
setConnectionStatus( sal_False );
}
return aStatus;
}
NS_IMETHODIMP MLDAPMessageListener::OnLDAPMessage( nsILDAPMessage* aMessage )
{
nsresult rv;
PRInt32 messageType;
rv = aMessage->GetType(&messageType);
NS_ENSURE_SUCCESS(rv, rv);
PRInt32 errCode;
switch (messageType)
{
case nsILDAPMessage::RES_BIND:
rv = aMessage->GetErrorCode(&errCode);
// if the login failed
if (errCode != nsILDAPErrors::SUCCESS) {
setConnectionStatus( sal_False );
}
else
setConnectionStatus( sal_True );
break;
case nsILDAPMessage::RES_SEARCH_RESULT:
setConnectionStatus( sal_True );
break;
default:
break;
}
return NS_OK;
}
//-------------------------------------------------------------------
nsresult
MNSMozabProxy::testLDAPConnection( )
{
nsresult rv=NS_ERROR_INVALID_ARG;
switch(m_Args->funcIndex)
{
case ProxiedFunc::FUNC_TESTLDAP_INIT_LDAP:
if (m_Args->arg1 && m_Args->arg4 )
{
rv = InitLDAP((sal_Char*)m_Args->arg1,(sal_Unicode*)m_Args->arg2,(sal_Unicode*)m_Args->arg3,(sal_Bool*)m_Args->arg4);
}
break;
case ProxiedFunc::FUNC_TESTLDAP_IS_LDAP_CONNECTED:
if (m_Args->arg5)
{
if ( ((MLDAPMessageListener*)m_Args->arg5)->connected())
{
rv = 0;
}
}
break;
case ProxiedFunc::FUNC_TESTLDAP_RELEASE_RESOURCE:
if (m_Args->arg5)
{
((MLDAPMessageListener*)m_Args->arg5)->Release();
delete (MLDAPMessageListener*)m_Args->arg5;
m_Args->arg5 = NULL;
rv = 0;
}
break;
default:
return NS_ERROR_INVALID_ARG;
}
return rv;
}
nsresult
MNSMozabProxy::InitLDAP(sal_Char* sUri, sal_Unicode* sBindDN, sal_Unicode* sPasswd,sal_Bool * nUseSSL)
{
sal_Bool useSSL = *nUseSSL;
nsresult rv;
nsCOMPtr<nsILDAPURL> url;
url = do_CreateInstance(NS_LDAPURL_CONTRACTID, &rv);
if ( NS_FAILED(rv) )
return NS_ERROR_INVALID_ARG;
rv = url->SetSpec( nsDependentCString(sUri) );
NS_ENSURE_SUCCESS(rv, rv);
nsCAutoString host;
rv = url->GetAsciiHost(host);
NS_ENSURE_SUCCESS(rv, rv);
PRInt32 port;
rv = url->GetPort(&port);
NS_ENSURE_SUCCESS(rv, rv);
nsCString dn;
rv = url->GetDn(dn);
NS_ENSURE_SUCCESS(rv, rv);
// Get the ldap connection
nsCOMPtr<nsILDAPConnection> ldapConnection;
ldapConnection = do_CreateInstance(NS_LDAPCONNECTION_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
MLDAPMessageListener* messageListener =
new MLDAPMessageListener ( );
if (messageListener == NULL)
return NS_ERROR_INVALID_ARG;
messageListener->AddRef();
nsCAutoString nsBind;
nsBind.AssignWithConversion(sBindDN);
// Now lets initialize the LDAP connection properly.
rv = ldapConnection->Init(host.get(), port, useSSL, nsBind,
messageListener,NULL,nsILDAPConnection::VERSION3);
// Initiate the LDAP operation
nsCOMPtr<nsILDAPOperation> ldapOperation =
do_CreateInstance(NS_LDAPOPERATION_CONTRACTID, &rv);
rv = ldapOperation->Init(ldapConnection, messageListener, nsnull);
if (NS_FAILED(rv))
return NS_ERROR_UNEXPECTED; // this should never happen
nsCAutoString nsPassword;
nsPassword.AssignWithConversion(sPasswd);
rv = ldapOperation->SimpleBind(nsPassword);
if (NS_SUCCEEDED(rv))
m_Args->arg5 = messageListener;
return rv;
}
<commit_msg>INTEGRATION: CWS dba202a (1.4.36); FILE MERGED 2005/11/23 15:41:00 fs 1.4.36.1: #i52789#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MNSMozabProxy.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2005-12-21 13:18:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_MAB_MOZABHELPER_HXX_
#include "MNSMozabProxy.hxx"
#endif
#ifndef _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_
#include "MDatabaseMetaDataHelper.hxx"
#endif
#ifndef _CONNECTIVITY_MAB_QUERY_HXX_
#include "MQuery.hxx"
#endif
#include <nsIProxyObjectManager.h>
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif
// More Mozilla includes for LDAP Connection Test
#include "prprf.h"
#include "nsILDAPURL.h"
#include "nsILDAPMessage.h"
#include "nsILDAPMessageListener.h"
#include "nsILDAPErrors.h"
#include "nsILDAPConnection.h"
#include "nsILDAPOperation.h"
#ifndef _CONNECTIVITY_MAB_QUERY_HXX_
#include "MQuery.hxx"
#endif
#ifndef _CONNECTIVITY_MAB_QUERYHELPER_HXX_
#include <MQueryHelper.hxx>
#endif
#include <com/sun/star/uno/Reference.hxx>
#include <unotools/processfactory.hxx>
#ifndef _COM_SUN_STAR_MOZILLA_XPROXYRUNNER_HPP_
#include "com/sun/star/mozilla/XProxyRunner.hpp"
#endif
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::mozilla;
#define TYPEASSERT(value,type) if (value != type) return !NS_OK;
using namespace connectivity::mozab;
/* Implementation file */
static ::osl::Mutex m_aThreadMutex;
extern nsresult NewAddressBook(const ::rtl::OUString * aName);
MNSMozabProxy::MNSMozabProxy()
{
m_Args = NULL;
#if OSL_DEBUG_LEVEL > 0
m_oThreadID = osl_getThreadIdentifier(NULL);
#endif
acquire();
}
MNSMozabProxy::~MNSMozabProxy()
{
}
sal_Int32 MNSMozabProxy::StartProxy(RunArgs * args,::com::sun::star::mozilla::MozillaProductType aProduct,const ::rtl::OUString &aProfile)
{
OSL_TRACE( "IN : MNSMozabProxy::StartProxy() \n" );
::osl::MutexGuard aGuard(m_aThreadMutex);
m_Product = aProduct;
m_Profile = aProfile;
m_Args = args;
if (!xRunner.is())
{
Reference<XMultiServiceFactory> xFactory = ::comphelper::getProcessServiceFactory();
OSL_ENSURE( xFactory.is(), "can't get service factory" );
::com::sun::star::uno::Reference<XInterface> xInstance = xFactory->createInstance(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")) );
OSL_ENSURE( xInstance.is(), "failed to create instance" );
xRunner = ::com::sun::star::uno::Reference< ::com::sun::star::mozilla::XProxyRunner >(xInstance,UNO_QUERY);
}
const ::com::sun::star::uno::Reference< ::com::sun::star::mozilla::XCodeProxy > aCode(this);
return xRunner->Run(aCode);
}
extern nsresult getTableStringsProxied(const sal_Char* sAbURI, sal_Int32 *nDirectoryType,MNameMapper *nmap,
::std::vector< ::rtl::OUString >* _rStrings,
::std::vector< ::rtl::OUString >* _rTypes,
rtl::OUString * sError);
::com::sun::star::mozilla::MozillaProductType SAL_CALL MNSMozabProxy::getProductType( ) throw (::com::sun::star::uno::RuntimeException)
{
return m_Product;
}
::rtl::OUString SAL_CALL MNSMozabProxy::getProfileName( ) throw (::com::sun::star::uno::RuntimeException)
{
return m_Profile;
}
sal_Int32 SAL_CALL MNSMozabProxy::run( ) throw (::com::sun::star::uno::RuntimeException)
{
#if OSL_DEBUG_LEVEL > 0
OSL_TRACE( "IN : MNSMozabProxy::Run() Caller thread :%4d \n" , m_oThreadID );
#else
OSL_TRACE( "IN : MNSMozabProxy::Run() \n" );
#endif
nsresult rv = NS_ERROR_INVALID_ARG;
if (m_Args == NULL)
return NS_ERROR_INVALID_ARG;
switch(m_Args->funcIndex)
{
case ProxiedFunc::FUNC_TESTLDAP_INIT_LDAP:
case ProxiedFunc::FUNC_TESTLDAP_IS_LDAP_CONNECTED:
case ProxiedFunc::FUNC_TESTLDAP_RELEASE_RESOURCE:
rv = testLDAPConnection();
break;
case ProxiedFunc::FUNC_GET_TABLE_STRINGS:
rv = getTableStringsProxied((const sal_Char*)m_Args->arg1,
(sal_Int32 *)m_Args->arg2,
(MNameMapper *)m_Args->arg3,
(::std::vector< ::rtl::OUString >*)m_Args->arg4,
(::std::vector< ::rtl::OUString >*)m_Args->arg5,
(rtl::OUString *)m_Args->arg6);
break;
case ProxiedFunc::FUNC_EXECUTE_QUERY:
if (m_Args->arg1 && m_Args->arg2)
{
rv = ((MQuery*)m_Args->arg1)->executeQueryProxied((OConnection*)m_Args->arg2);
}
break;
case ProxiedFunc::FUNC_QUERYHELPER_CREATE_NEW_CARD:
case ProxiedFunc::FUNC_QUERYHELPER_DELETE_CARD:
case ProxiedFunc::FUNC_QUERYHELPER_COMMIT_CARD:
case ProxiedFunc::FUNC_QUERYHELPER_RESYNC_CARD:
if (m_Args->arg1)
{
rv = QueryHelperStub();
}
break;
case ProxiedFunc::FUNC_NEW_ADDRESS_BOOK:
if (m_Args->arg1)
{
rv = NewAddressBook((const ::rtl::OUString*)m_Args->arg1 );
}
break;
default:
return NS_ERROR_INVALID_ARG;
}
return rv;
}
nsresult MNSMozabProxy::QueryHelperStub()
{
nsresult rv = NS_ERROR_INVALID_ARG;
MQueryHelper * mHelper=(MQueryHelper*) m_Args->arg1;
switch(m_Args->funcIndex)
{
case ProxiedFunc::FUNC_QUERYHELPER_CREATE_NEW_CARD:
if (m_Args->arg2 ) //m_Args->arg2 used to return cord number
{
*((sal_Int32*)m_Args->arg2) = mHelper->createNewCard();
rv = NS_OK;
}
break;
case ProxiedFunc::FUNC_QUERYHELPER_DELETE_CARD:
if (m_Args->arg2 && m_Args->arg3 ) //m_Args->arg2 used to get the cord number
{
rv = mHelper->deleteCard(*((sal_Int32*)m_Args->arg2),(nsIAbDirectory*)m_Args->arg3);
}
break;
case ProxiedFunc::FUNC_QUERYHELPER_COMMIT_CARD:
if (m_Args->arg2 && m_Args->arg3 ) //m_Args->arg2 used to get the cord number
{
rv = mHelper->commitCard(*((sal_Int32*)m_Args->arg2),(nsIAbDirectory*)m_Args->arg3);
}
break;
case ProxiedFunc::FUNC_QUERYHELPER_RESYNC_CARD:
if (m_Args->arg2) //m_Args->arg2 used to get the cord number
{
rv = mHelper->resyncRow(*((sal_Int32*)m_Args->arg2));
}
break;
default:
break;
}
return rv;
}
//-------------------------------------------------------------------
#define NS_LDAPCONNECTION_CONTRACTID "@mozilla.org/network/ldap-connection;1"
#define NS_LDAPOPERATION_CONTRACTID "@mozilla.org/network/ldap-operation;1"
#define NS_LDAPMESSAGE_CONTRACTID "@mozilla.org/network/ldap-message;1"
#define NS_LDAPURL_CONTRACTID "@mozilla.org/network/ldap-url;1"
namespace connectivity {
namespace mozab {
class MLDAPMessageListener : public nsILDAPMessageListener {
NS_DECL_ISUPPORTS
NS_DECL_NSILDAPMESSAGELISTENER
MLDAPMessageListener();
~MLDAPMessageListener();
sal_Bool connected();
protected:
::osl::Mutex m_aMutex;
::osl::Condition m_aCondition;
sal_Bool m_IsComplete;
sal_Bool m_GoodConnection;
void setConnectionStatus( sal_Bool _good );
};
}
}
NS_IMPL_THREADSAFE_ISUPPORTS1(MLDAPMessageListener, nsILDAPMessageListener)
MLDAPMessageListener::MLDAPMessageListener()
: mRefCnt( 0 )
, m_IsComplete( sal_False )
, m_GoodConnection( sal_False )
{
m_aCondition.reset();
}
MLDAPMessageListener::~MLDAPMessageListener()
{
}
sal_Bool MLDAPMessageListener::connected()
{
return m_aCondition.check();
}
void MLDAPMessageListener::setConnectionStatus( sal_Bool _good )
{
::osl::MutexGuard aGuard( m_aMutex );
m_IsComplete = sal_True;
m_GoodConnection = _good;
m_aCondition.set();
}
NS_IMETHODIMP MLDAPMessageListener::OnLDAPInit(nsILDAPConnection *aConn, nsresult aStatus )
{
// Make sure that the Init() worked properly
if ( NS_FAILED(aStatus ) ) {
setConnectionStatus( sal_False );
}
return aStatus;
}
NS_IMETHODIMP MLDAPMessageListener::OnLDAPMessage( nsILDAPMessage* aMessage )
{
nsresult rv;
PRInt32 messageType;
rv = aMessage->GetType(&messageType);
NS_ENSURE_SUCCESS(rv, rv);
PRInt32 errCode;
switch (messageType)
{
case nsILDAPMessage::RES_BIND:
rv = aMessage->GetErrorCode(&errCode);
// if the login failed
if (errCode != (PRInt32)nsILDAPErrors::SUCCESS) {
setConnectionStatus( sal_False );
}
else
setConnectionStatus( sal_True );
break;
case nsILDAPMessage::RES_SEARCH_RESULT:
setConnectionStatus( sal_True );
break;
default:
break;
}
return NS_OK;
}
//-------------------------------------------------------------------
nsresult
MNSMozabProxy::testLDAPConnection( )
{
nsresult rv=NS_ERROR_INVALID_ARG;
switch(m_Args->funcIndex)
{
case ProxiedFunc::FUNC_TESTLDAP_INIT_LDAP:
if (m_Args->arg1 && m_Args->arg4 )
{
rv = InitLDAP((sal_Char*)m_Args->arg1,(sal_Unicode*)m_Args->arg2,(sal_Unicode*)m_Args->arg3,(sal_Bool*)m_Args->arg4);
}
break;
case ProxiedFunc::FUNC_TESTLDAP_IS_LDAP_CONNECTED:
if (m_Args->arg5)
{
if ( ((MLDAPMessageListener*)m_Args->arg5)->connected())
{
rv = 0;
}
}
break;
case ProxiedFunc::FUNC_TESTLDAP_RELEASE_RESOURCE:
if (m_Args->arg5)
{
((MLDAPMessageListener*)m_Args->arg5)->Release();
delete (MLDAPMessageListener*)m_Args->arg5;
m_Args->arg5 = NULL;
rv = 0;
}
break;
default:
return NS_ERROR_INVALID_ARG;
}
return rv;
}
nsresult
MNSMozabProxy::InitLDAP(sal_Char* sUri, sal_Unicode* sBindDN, sal_Unicode* sPasswd,sal_Bool * nUseSSL)
{
sal_Bool useSSL = *nUseSSL;
nsresult rv;
nsCOMPtr<nsILDAPURL> url;
url = do_CreateInstance(NS_LDAPURL_CONTRACTID, &rv);
if ( NS_FAILED(rv) )
return NS_ERROR_INVALID_ARG;
rv = url->SetSpec( nsDependentCString(sUri) );
NS_ENSURE_SUCCESS(rv, rv);
nsCAutoString host;
rv = url->GetAsciiHost(host);
NS_ENSURE_SUCCESS(rv, rv);
PRInt32 port;
rv = url->GetPort(&port);
NS_ENSURE_SUCCESS(rv, rv);
nsCString dn;
rv = url->GetDn(dn);
NS_ENSURE_SUCCESS(rv, rv);
// Get the ldap connection
nsCOMPtr<nsILDAPConnection> ldapConnection;
ldapConnection = do_CreateInstance(NS_LDAPCONNECTION_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
MLDAPMessageListener* messageListener =
new MLDAPMessageListener ( );
if (messageListener == NULL)
return NS_ERROR_INVALID_ARG;
messageListener->AddRef();
nsCAutoString nsBind;
nsBind.AssignWithConversion(sBindDN);
// Now lets initialize the LDAP connection properly.
rv = ldapConnection->Init(host.get(), port, useSSL, nsBind,
messageListener,NULL,nsILDAPConnection::VERSION3);
// Initiate the LDAP operation
nsCOMPtr<nsILDAPOperation> ldapOperation =
do_CreateInstance(NS_LDAPOPERATION_CONTRACTID, &rv);
rv = ldapOperation->Init(ldapConnection, messageListener, nsnull);
if (NS_FAILED(rv))
return NS_ERROR_UNEXPECTED; // this should never happen
nsCAutoString nsPassword;
nsPassword.AssignWithConversion(sPasswd);
rv = ldapOperation->SimpleBind(nsPassword);
if (NS_SUCCEEDED(rv))
m_Args->arg5 = messageListener;
return rv;
}
<|endoftext|> |
<commit_before>#include "gui/navigation/qrnavigationtabpage.h"
#include <QtCore/qdebug.h>
#include <QtCore/qsortfilterproxymodel.h>
#include <QtGui/qstandarditemmodel.h>
#include <QtWidgets/qboxlayout.h>
#include <QtWidgets/qpushbutton.h>
#include "db/qrtblnavigation.h"
#include "gui/navigation/qrnavigationmodel.h"
#include "gui/navigation/qrnavigationtabpageview.h"
NS_CHAOS_BASE_BEGIN
class QrNavigationTabPagePrivate{
QR_DECLARE_PUBLIC(QrNavigationTabPage)
public:
QrNavigationTabPagePrivate(QrNavigationTabPage *q) :q_ptr(q) {}
public:
void loadUI();
void clearModel();
void initModel(QString parentKey,
QStandardItem *rootItem,
QrNavigationDbData *data);
void connectConfigs();
public:
QrNavigationTabView *view = nullptr;
QStandardItemModel *data = nullptr;
QrNavigationFilterProxyModel *dataProxy = nullptr;
QMap<QStandardItem*, QPushButton*> dataItemMapBtn; // store to call button click event when view click event happen
QMap<QPushButton*, QString> buttonMapKey; // store to remove pushbutton of button container when reinit
};
void QrNavigationTabPagePrivate::loadUI()
{
Q_Q(QrNavigationTabPage);
view = new QrNavigationTabView(q);
data = new QStandardItemModel(view);
dataProxy = new QrNavigationFilterProxyModel(view);
dataProxy->setSourceModel(data);
dataProxy->setFilterKeyColumn(0);
dataProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
view->setModel(dataProxy);
view->setFocusPolicy(Qt::NoFocus);
view->setEditTriggers(QAbstractItemView::NoEditTriggers);
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
QVBoxLayout* mainLayout = new QVBoxLayout();
mainLayout->setContentsMargins(0,0,0,0);
mainLayout->setSpacing(0);
mainLayout->addWidget(view);
q->setLayout(mainLayout);
}
void QrNavigationTabPagePrivate::clearModel()
{
this->data->clear();
Q_Q(QrNavigationTabPage);
Q_FOREACH(QPushButton* pushbtn, dataItemMapBtn) {
emit q->removeButton(this->buttonMapKey[pushbtn], pushbtn);
delete pushbtn;
pushbtn = nullptr;
}
this->dataItemMapBtn.clear();
}
void QrNavigationTabPagePrivate::initModel(QString parentKey,
QStandardItem *rootItem,
QrNavigationDbData *dbData)
{
Q_Q(QrNavigationTabPage);
Q_FOREACH(QrNavigationDbData* data, dbData->children) {
QStandardItem *item = new QStandardItem(data->display);
if (! data->children.empty()) {
initModel(parentKey.isEmpty() ? data->key
: parentKey+"."+data->key,
item,
data);
} else { // leaf node
auto itemPath = parentKey + "." + data->key;
auto itemButton = new QPushButton(itemPath);
buttonMapKey[itemButton] = itemPath;
dataItemMapBtn[item] = itemButton;
emit q->addButton(itemPath, itemButton);
}
rootItem->appendRow(item);
}
}
void QrNavigationTabPagePrivate::connectConfigs()
{
QObject::connect(this->view, &QrNavigationTabView::clicked, [this](const QModelIndex &index){
if (! index.isValid()) {
return;
}
auto item = this->data->itemFromIndex(index);
if (! this->dataItemMapBtn.contains(item)) {
return ;
}
dataItemMapBtn[item]->click();
qDebug() << "click " << this->buttonMapKey[dataItemMapBtn[item]];
});
}
NS_CHAOS_BASE_END
USING_NS_CHAOS_BASE;
QrNavigationTabPage::QrNavigationTabPage(QWidget* parent)
:QWidget(parent), d_ptr(new QrNavigationTabPagePrivate(this))
{
d_ptr->loadUI();
}
void QrNavigationTabPage::expandAll()
{
Q_D(QrNavigationTabPage);
d->view->expandAll();
}
void QrNavigationTabPage::initModelByDbData(QrNavigationDbData *dbData)
{
Q_D(QrNavigationTabPage);
d->clearModel();
d->initModel("", d->data->invisibleRootItem(), dbData);
d->connectConfigs();
}
QrNavigationFilterProxyModel *QrNavigationTabPage::modelProxy()
{
Q_D(QrNavigationTabPage);
return d->dataProxy;
}
<commit_msg>no response when click on navigation<commit_after>#include "gui/navigation/qrnavigationtabpage.h"
#include <QtCore/qdebug.h>
#include <QtCore/qsortfilterproxymodel.h>
#include <QtGui/qstandarditemmodel.h>
#include <QtWidgets/qboxlayout.h>
#include <QtWidgets/qpushbutton.h>
#include "db/qrtblnavigation.h"
#include "gui/navigation/qrnavigationmodel.h"
#include "gui/navigation/qrnavigationtabpageview.h"
NS_CHAOS_BASE_BEGIN
class QrNavigationTabPagePrivate{
QR_DECLARE_PUBLIC(QrNavigationTabPage)
public:
QrNavigationTabPagePrivate(QrNavigationTabPage *q) :q_ptr(q) {}
public:
void loadUI();
void clearModel();
void initModel(QString parentKey,
QStandardItem *rootItem,
QrNavigationDbData *data);
void connectConfigs();
public:
QrNavigationTabView *view = nullptr;
QStandardItemModel *data = nullptr;
QrNavigationFilterProxyModel *dataProxy = nullptr;
QMap<QStandardItem*, QPushButton*> dataItemMapBtn; // store to call button click event when view click event happen
QMap<QPushButton*, QString> buttonMapKey; // store to remove pushbutton of button container when reinit
};
void QrNavigationTabPagePrivate::loadUI()
{
Q_Q(QrNavigationTabPage);
view = new QrNavigationTabView(q);
data = new QStandardItemModel(view);
dataProxy = new QrNavigationFilterProxyModel(view);
dataProxy->setSourceModel(data);
dataProxy->setFilterKeyColumn(0);
dataProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
view->setModel(dataProxy);
view->setFocusPolicy(Qt::NoFocus);
view->setEditTriggers(QAbstractItemView::NoEditTriggers);
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
QVBoxLayout* mainLayout = new QVBoxLayout();
mainLayout->setContentsMargins(0,0,0,0);
mainLayout->setSpacing(0);
mainLayout->addWidget(view);
q->setLayout(mainLayout);
}
void QrNavigationTabPagePrivate::clearModel()
{
this->data->clear();
Q_Q(QrNavigationTabPage);
Q_FOREACH(QPushButton* pushbtn, dataItemMapBtn) {
emit q->removeButton(this->buttonMapKey[pushbtn], pushbtn);
delete pushbtn;
pushbtn = nullptr;
}
this->dataItemMapBtn.clear();
}
void QrNavigationTabPagePrivate::initModel(QString parentKey,
QStandardItem *rootItem,
QrNavigationDbData *dbData)
{
Q_Q(QrNavigationTabPage);
Q_FOREACH(QrNavigationDbData* data, dbData->children) {
QStandardItem *item = new QStandardItem(data->display);
if (! data->children.empty()) {
initModel(parentKey.isEmpty() ? data->key
: parentKey+"."+data->key,
item,
data);
} else { // leaf node
auto itemPath = parentKey + "." + data->key;
auto itemButton = new QPushButton(itemPath);
buttonMapKey[itemButton] = itemPath;
dataItemMapBtn[item] = itemButton;
emit q->addButton(itemPath, itemButton);
}
rootItem->appendRow(item);
}
}
void QrNavigationTabPagePrivate::connectConfigs()
{
QObject::connect(this->view, &QrNavigationTabView::clicked, [this](const QModelIndex &index){
if (! index.isValid()) {
return;
}
auto item = this->data->itemFromIndex(this->dataProxy->mapToSource(index));
if (! this->dataItemMapBtn.contains(item)) {
return ;
}
dataItemMapBtn[item]->click();
qDebug() << "click " << this->buttonMapKey[dataItemMapBtn[item]];
});
}
NS_CHAOS_BASE_END
USING_NS_CHAOS_BASE;
QrNavigationTabPage::QrNavigationTabPage(QWidget* parent)
:QWidget(parent), d_ptr(new QrNavigationTabPagePrivate(this))
{
d_ptr->loadUI();
}
void QrNavigationTabPage::expandAll()
{
Q_D(QrNavigationTabPage);
d->view->expandAll();
}
void QrNavigationTabPage::initModelByDbData(QrNavigationDbData *dbData)
{
Q_D(QrNavigationTabPage);
d->clearModel();
d->initModel("", d->data->invisibleRootItem(), dbData);
d->connectConfigs();
}
QrNavigationFilterProxyModel *QrNavigationTabPage::modelProxy()
{
Q_D(QrNavigationTabPage);
return d->dataProxy;
}
<|endoftext|> |
<commit_before>//
// Reactor.cpp
// ofxLibwebsockets
//
// Created by Brett Renfer on 4/12/12.
// Copyright (c) 2012 Robotconscience. All rights reserved.
//
#include "ofxLibwebsockets/Reactor.h"
namespace ofxLibwebsockets {
//--------------------------------------------------------------
Reactor::Reactor()
: context(NULL), waitMillis(50){
reactors.push_back(this);
bParseJSON = true;
largeMessage = "";
largeBinaryMessage.clear();
largeBinarySize = 0;
bReceivingLargeMessage = false;
closeAndFree = false;
}
//--------------------------------------------------------------
Reactor::~Reactor(){
exit();
}
//--------------------------------------------------------------
void Reactor::registerProtocol(const std::string& name, Protocol& protocol){
protocol.idx = protocols.size();
protocol.rx_buffer_size = OFX_LWS_MAX_BUFFER;
protocol.reactor = this;
protocols.push_back(make_pair(name, &protocol));
}
//--------------------------------------------------------------
Protocol* const Reactor::protocol(const unsigned int idx){
return (idx < protocols.size())? protocols[idx].second : NULL;
}
//--------------------------------------------------------------
void Reactor::close(Connection* const conn){
if (conn != NULL && conn->ws != NULL){
// In the current git for the library, libwebsocket_close_and_free_session() has been removed from the public api.
//Instead, if you return -1 from the user callback, the library will understand it should call libwebsocket_close_and_free_session() for you.
//Calling libwebsocket_close_and_free_session() from outside the callback made trouble, because it frees the struct libwebsocket while the library may still hold pointers.
//libwebsocket_close_and_free_session(context, conn->ws, LWS_CLOSE_STATUS_NORMAL);
closeAndFree = true;
}
}
//--------------------------------------------------------------
void Reactor::exit(){
if (context != NULL)
{
waitForThread(true);
// on windows the app does crash if the context is destroyed
// while the thread or the library still might hold pointers
// better to live with non deleted memory, or?
//libwebsocket_context_destroy(context);
context = NULL;
}
}
//--------------------------------------------------------------
struct libwebsocket_context * Reactor::getContext(){
return context;
}
//--------------------------------------------------------------
vector<Connection *> Reactor::getConnections(){
return connections;
}
//--------------------------------------------------------------
Connection * Reactor::getConnection( int index ){
if ( index < connections.size() ){
return connections[ index ];
}
return NULL;
}
//--------------------------------------------------------------
unsigned int
Reactor::_allow(struct libwebsocket *ws, Protocol* const protocol, const long fd){
std::string client_ip(128, 0);
std::string client_name(128, 0);
libwebsockets_get_peer_addresses(context, ws, (int)fd,
&client_name[0], client_name.size(),
&client_ip[0], client_ip.size());
return protocol->_allowClient(client_name, client_ip);
}
//--------------------------------------------------------------
unsigned int Reactor::_notify(Connection* conn,
enum libwebsocket_callback_reasons const reason,
const char* const _message,
const unsigned int len){
if (conn == NULL || conn->protocol == NULL){
if (conn == NULL){
ofLog(OF_LOG_WARNING, "[ofxLibwebsockets] connection is null ");
} else {
ofLog(OF_LOG_WARNING, "[ofxLibwebsockets] protocol is null");
}
return 1;
}
if (closeAndFree){
closeAndFree = false;
return -1;
}
std::string message;
Event args(*conn, message);
switch (reason) {
// connection was not successful
case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
ofLogError()<<"[ofxLibwebsockets] Connection error";
//TODO: add error event!
for (int i=0; i<connections.size(); i++){
if ( connections[i] == conn ){
connections.erase( connections.begin() + i );
break;
}
}
ofNotifyEvent(conn->protocol->oncloseEvent, args);
break;
case LWS_CALLBACK_ESTABLISHED:
case LWS_CALLBACK_CLIENT_ESTABLISHED:
connections.push_back( conn );
ofNotifyEvent(conn->protocol->onopenEvent, args);
break;
case LWS_CALLBACK_CLOSED:
// erase connection from vector
for (int i=0; i<connections.size(); i++){
if ( connections[i] == conn ){
connections.erase( connections.begin() + i );
break;
}
}
ofNotifyEvent(conn->protocol->oncloseEvent, args);
break;
case LWS_CALLBACK_SERVER_WRITEABLE:
case LWS_CALLBACK_CLIENT_WRITEABLE:
// idle is good! means you can write again
ofNotifyEvent(conn->protocol->onidleEvent, args);
break;
case LWS_CALLBACK_RECEIVE:
case LWS_CALLBACK_CLIENT_RECEIVE:
case LWS_CALLBACK_CLIENT_RECEIVE_PONG:
{
bool bFinishedReceiving = false;
// decide if this is part of a larger message or not
size_t bytesLeft = libwebsockets_remaining_packet_payload( conn->ws );
if ( !bReceivingLargeMessage && (bytesLeft > 0 || !libwebsocket_is_final_fragment( conn->ws )) ){
bReceivingLargeMessage = true;
}
// text or binary?
int isBinary = lws_frame_is_binary(conn->ws);
if (isBinary == 1 ){
// set binary flag on event
args.isBinary = true;
if ( bReceivingLargeMessage){
// need to allocate data...
if ( largeBinarySize == 0 ){
largeBinaryMessage.set( _message, len );
largeBinarySize = len;
} else {
largeBinarySize += len;
largeBinaryMessage.append(_message, len);
}
if ( bytesLeft == 0 && libwebsocket_is_final_fragment( conn->ws )){
// copy into event
args.data.set(largeBinaryMessage.getBinaryBuffer(), largeBinaryMessage.size());
bFinishedReceiving = true;
bReceivingLargeMessage = false;
largeBinaryMessage.clear();
largeBinarySize = 0;
}
} else {
}
} else {
if (_message != NULL && len > 0){
args.message = std::string(_message, len);
}
if ( bReceivingLargeMessage){
largeMessage += args.message;
if ( bytesLeft == 0 && libwebsocket_is_final_fragment( conn->ws )){
args.message = largeMessage;
bFinishedReceiving = true;
bReceivingLargeMessage = false;
largeMessage = "";
}
}
if (_message != NULL && len > 0 && (!bReceivingLargeMessage || bFinishedReceiving) ){
args.json = Json::Value( Json::nullValue );
bool parsingSuccessful = ( bParseJSON ? reader.parse( args.message, args.json ) : false);
if ( !parsingSuccessful ){
// report to the user the failure and their locations in the document.
ofLog( OF_LOG_VERBOSE, "[ofxLibwebsockets] Failed to parse JSON\n"+ reader.getFormatedErrorMessages() );
args.json = Json::Value( Json::nullValue );
}
}
}
// only notify if we have a complete message
if (!bReceivingLargeMessage || bFinishedReceiving){
ofNotifyEvent(conn->protocol->onmessageEvent, args);
}
}
break;
default:
ofLogVerbose() << "[ofxLibwebsockets] received unknown event "<< reason <<endl;
break;
}
return 0;
}
//--------------------------------------------------------------
unsigned int Reactor::_http(struct libwebsocket *ws,
const char* const _url){
std::string url(_url);
if (url == "/")
url = "/index.html";
// why does this need to be done?
std::string ext = url.substr(url.find_last_of(".")+1);
// watch out for query strings!
size_t find = url.find("?");
if ( find!=string::npos ){
url = url.substr(0,url.find("?"));
}
std::string file = document_root+url;
std::string mimetype = "text/html";
if (ext == "ico")
mimetype = "image/x-icon";
if (ext == "manifest")
mimetype = "text/cache-manifest";
if (ext == "swf")
mimetype = "application/x-shockwave-flash";
if (ext == "js")
mimetype = "application/javascript";
if (ext == "css")
mimetype = "text/css";
if (libwebsockets_serve_http_file(context, ws, file.c_str(), mimetype.c_str()) < 0){
ofLog( OF_LOG_WARNING, "[ofxLibwebsockets] Failed to send HTTP file "+ file + " for "+ url);
}
return 0;
}
}
<commit_msg>Bug fix for tiny binary messages<commit_after>//
// Reactor.cpp
// ofxLibwebsockets
//
// Created by Brett Renfer on 4/12/12.
// Copyright (c) 2012 Robotconscience. All rights reserved.
//
#include "ofxLibwebsockets/Reactor.h"
namespace ofxLibwebsockets {
//--------------------------------------------------------------
Reactor::Reactor()
: context(NULL), waitMillis(50){
reactors.push_back(this);
bParseJSON = true;
largeMessage = "";
largeBinaryMessage.clear();
largeBinarySize = 0;
bReceivingLargeMessage = false;
closeAndFree = false;
}
//--------------------------------------------------------------
Reactor::~Reactor(){
exit();
}
//--------------------------------------------------------------
void Reactor::registerProtocol(const std::string& name, Protocol& protocol){
protocol.idx = protocols.size();
protocol.rx_buffer_size = OFX_LWS_MAX_BUFFER;
protocol.reactor = this;
protocols.push_back(make_pair(name, &protocol));
}
//--------------------------------------------------------------
Protocol* const Reactor::protocol(const unsigned int idx){
return (idx < protocols.size())? protocols[idx].second : NULL;
}
//--------------------------------------------------------------
void Reactor::close(Connection* const conn){
if (conn != NULL && conn->ws != NULL){
// In the current git for the library, libwebsocket_close_and_free_session() has been removed from the public api.
//Instead, if you return -1 from the user callback, the library will understand it should call libwebsocket_close_and_free_session() for you.
//Calling libwebsocket_close_and_free_session() from outside the callback made trouble, because it frees the struct libwebsocket while the library may still hold pointers.
//libwebsocket_close_and_free_session(context, conn->ws, LWS_CLOSE_STATUS_NORMAL);
closeAndFree = true;
}
}
//--------------------------------------------------------------
void Reactor::exit(){
if (context != NULL)
{
waitForThread(true);
// on windows the app does crash if the context is destroyed
// while the thread or the library still might hold pointers
// better to live with non deleted memory, or?
//libwebsocket_context_destroy(context);
context = NULL;
}
}
//--------------------------------------------------------------
struct libwebsocket_context * Reactor::getContext(){
return context;
}
//--------------------------------------------------------------
vector<Connection *> Reactor::getConnections(){
return connections;
}
//--------------------------------------------------------------
Connection * Reactor::getConnection( int index ){
if ( index < connections.size() ){
return connections[ index ];
}
return NULL;
}
//--------------------------------------------------------------
unsigned int
Reactor::_allow(struct libwebsocket *ws, Protocol* const protocol, const long fd){
std::string client_ip(128, 0);
std::string client_name(128, 0);
libwebsockets_get_peer_addresses(context, ws, (int)fd,
&client_name[0], client_name.size(),
&client_ip[0], client_ip.size());
return protocol->_allowClient(client_name, client_ip);
}
//--------------------------------------------------------------
unsigned int Reactor::_notify(Connection* conn,
enum libwebsocket_callback_reasons const reason,
const char* const _message,
const unsigned int len){
if (conn == NULL || conn->protocol == NULL){
if (conn == NULL){
ofLog(OF_LOG_WARNING, "[ofxLibwebsockets] connection is null ");
} else {
ofLog(OF_LOG_WARNING, "[ofxLibwebsockets] protocol is null");
}
return 1;
}
if (closeAndFree){
closeAndFree = false;
return -1;
}
std::string message;
Event args(*conn, message);
switch (reason) {
// connection was not successful
case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
ofLogError()<<"[ofxLibwebsockets] Connection error";
//TODO: add error event!
for (int i=0; i<connections.size(); i++){
if ( connections[i] == conn ){
connections.erase( connections.begin() + i );
break;
}
}
ofNotifyEvent(conn->protocol->oncloseEvent, args);
break;
case LWS_CALLBACK_ESTABLISHED:
case LWS_CALLBACK_CLIENT_ESTABLISHED:
connections.push_back( conn );
ofNotifyEvent(conn->protocol->onopenEvent, args);
break;
case LWS_CALLBACK_CLOSED:
// erase connection from vector
for (int i=0; i<connections.size(); i++){
if ( connections[i] == conn ){
connections.erase( connections.begin() + i );
break;
}
}
ofNotifyEvent(conn->protocol->oncloseEvent, args);
break;
case LWS_CALLBACK_SERVER_WRITEABLE:
case LWS_CALLBACK_CLIENT_WRITEABLE:
// idle is good! means you can write again
ofNotifyEvent(conn->protocol->onidleEvent, args);
break;
case LWS_CALLBACK_RECEIVE:
case LWS_CALLBACK_CLIENT_RECEIVE:
case LWS_CALLBACK_CLIENT_RECEIVE_PONG:
{
bool bFinishedReceiving = false;
// decide if this is part of a larger message or not
size_t bytesLeft = libwebsockets_remaining_packet_payload( conn->ws );
if ( !bReceivingLargeMessage && (bytesLeft > 0 || !libwebsocket_is_final_fragment( conn->ws )) ){
bReceivingLargeMessage = true;
}
// text or binary?
int isBinary = lws_frame_is_binary(conn->ws);
if (isBinary == 1 ){
// set binary flag on event
args.isBinary = true;
if ( bReceivingLargeMessage){
cout << "Getting large message "<<endl;
// need to allocate data...
if ( largeBinarySize == 0 ){
largeBinaryMessage.set( _message, len );
largeBinarySize = len;
} else {
largeBinarySize += len;
largeBinaryMessage.append(_message, len);
}
if ( bytesLeft == 0 && libwebsocket_is_final_fragment( conn->ws )){
cout << "Last fragment "<<endl;
// copy into event
args.data.set(largeBinaryMessage.getBinaryBuffer(), largeBinaryMessage.size());
bFinishedReceiving = true;
bReceivingLargeMessage = false;
largeBinaryMessage.clear();
largeBinarySize = 0;
}
} else {
args.data.set(_message, len);
bFinishedReceiving = true;
bReceivingLargeMessage = false;
largeBinaryMessage.clear();
largeBinarySize = 0;
}
} else {
if (_message != NULL && len > 0){
args.message = std::string(_message, len);
}
if ( bReceivingLargeMessage){
largeMessage += args.message;
if ( bytesLeft == 0 && libwebsocket_is_final_fragment( conn->ws )){
args.message = largeMessage;
bFinishedReceiving = true;
bReceivingLargeMessage = false;
largeMessage = "";
}
}
if (_message != NULL && len > 0 && (!bReceivingLargeMessage || bFinishedReceiving) ){
args.json = Json::Value( Json::nullValue );
bool parsingSuccessful = ( bParseJSON ? reader.parse( args.message, args.json ) : false);
if ( !parsingSuccessful ){
// report to the user the failure and their locations in the document.
ofLog( OF_LOG_VERBOSE, "[ofxLibwebsockets] Failed to parse JSON\n"+ reader.getFormatedErrorMessages() );
args.json = Json::Value( Json::nullValue );
}
}
}
// only notify if we have a complete message
if (!bReceivingLargeMessage || bFinishedReceiving){
ofNotifyEvent(conn->protocol->onmessageEvent, args);
}
}
break;
default:
ofLogVerbose() << "[ofxLibwebsockets] received unknown event "<< reason <<endl;
break;
}
return 0;
}
//--------------------------------------------------------------
unsigned int Reactor::_http(struct libwebsocket *ws,
const char* const _url){
std::string url(_url);
if (url == "/")
url = "/index.html";
// why does this need to be done?
std::string ext = url.substr(url.find_last_of(".")+1);
// watch out for query strings!
size_t find = url.find("?");
if ( find!=string::npos ){
url = url.substr(0,url.find("?"));
}
std::string file = document_root+url;
std::string mimetype = "text/html";
if (ext == "ico")
mimetype = "image/x-icon";
if (ext == "manifest")
mimetype = "text/cache-manifest";
if (ext == "swf")
mimetype = "application/x-shockwave-flash";
if (ext == "js")
mimetype = "application/javascript";
if (ext == "css")
mimetype = "text/css";
if (libwebsockets_serve_http_file(context, ws, file.c_str(), mimetype.c_str()) < 0){
ofLog( OF_LOG_WARNING, "[ofxLibwebsockets] Failed to send HTTP file "+ file + " for "+ url);
}
return 0;
}
}
<|endoftext|> |
<commit_before>#include "ros/ros.h"
#include "vrep_common/VrepInfo.h"
#include "rosgraph_msgs/Clock.h"
#include <string>
const int SIM_STARTED = 1;
ros::Publisher clock_publisher;
ros::Subscriber vrep_clock_subscriber;
float sim_time = -1;
void updateClock(const vrep_common::VrepInfo::ConstPtr & new_time) {
if (SIM_STARTED == new_time->simulatorState.data) {
sim_time = new_time->simulationTime.data;
rosgraph_msgs::Clock c;
c.clock.sec = static_cast<uint32_t>(sim_time);
c.clock.nsec = static_cast<uint32_t>((sim_time - c.clock.sec) * 1000000000);
clock_publisher.publish(c);
}
}
int main(int argc, char **argv) {
ros::init(argc, argv, "vrepClockServer");
ros::NodeHandle nh;
vrep_clock_subscriber = nh.subscribe("/vrep/info", 1, updateClock);
clock_publisher = nh.advertise<rosgraph_msgs::Clock>("/clock", 1);
ros::spin();
}
<commit_msg>vrep clock server: everything was wrong<commit_after>#include "ros/ros.h"
#include "vrep_common/VrepInfo.h"
#include "rosgraph_msgs/Clock.h"
#include <string>
constexpr unsigned int SIM_STARTED_MASK = 1;
ros::Publisher clock_publisher;
ros::Subscriber vrep_clock_subscriber;
float sim_time = -1;
void updateClock(const vrep_common::VrepInfo::ConstPtr& new_time) {
/*
simulatorState.data is bitwise encoded state
bit0 set: simulation not stopped
bit1 set: simulation paused
bit2 set: real-time switch on
bit3-bit5: the edit mode type (0=no edit mode, 1=triangle, 2=vertex, 3=edge, 4=path, 5=UI)
*/
if (!(new_time->simulatorState.data & SIM_STARTED_MASK)) {
return;
}
sim_time = new_time->simulationTime.data;
rosgraph_msgs::Clock c;
/* convert float time to sec a nano sec */
c.clock.sec = static_cast<uint32_t>(sim_time);
c.clock.nsec = static_cast<uint32_t>((sim_time - c.clock.sec) * 1000000000);
clock_publisher.publish(c);
}
int main(int argc, char **argv) {
ros::init(argc, argv, "vrepClockServer");
ros::NodeHandle nh;
vrep_clock_subscriber = nh.subscribe("/vrep/info", 1, updateClock);
clock_publisher = nh.advertise<rosgraph_msgs::Clock>("/clock", 1);
ros::spin();
}
<|endoftext|> |
<commit_before>#include "ofUtils.h"
#include "ofImage.h"
#if defined(TARGET_OF_IPHONE) || defined(TARGET_OSX ) || defined(TARGET_LINUX)
#include "sys/time.h"
#endif
#ifdef TARGET_WIN32
#include <mmsystem.h>
#ifdef _MSC_VER
#include <direct.h>
#endif
#endif
static bool enableDataPath = true;
static unsigned long startTime = ofGetSystemTime(); // better at the first frame ?? (currently, there is some delay from static init, to running.
//--------------------------------------
int ofGetElapsedTimeMillis(){
return (int)(ofGetSystemTime() - startTime);
}
//--------------------------------------
float ofGetElapsedTimef(){
return ((float) ((int)(ofGetSystemTime() - startTime)) / 1000.0f);
}
//--------------------------------------
void ofResetElapsedTimeCounter(){
startTime = ofGetSystemTime();
}
//=======================================
// this is from freeglut, and used internally:
/* Platform-dependent time in milliseconds, as an unsigned 32-bit integer.
* This value wraps every 49.7 days, but integer overflows cancel
* when subtracting an initial start time, unless the total time exceeds
* 32-bit, where the GLUT API return value is also overflowed.
*/
unsigned long ofGetSystemTime( ) {
#ifndef TARGET_WIN32
struct timeval now;
gettimeofday( &now, NULL );
return now.tv_usec/1000 + now.tv_sec*1000;
#else
#if defined(_WIN32_WCE)
return GetTickCount();
#else
return timeGetTime();
#endif
#endif
}
//--------------------------------------------------
int ofGetSeconds(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
return local.tm_sec;
}
//--------------------------------------------------
int ofGetMinutes(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
return local.tm_min;
}
//--------------------------------------------------
int ofGetHours(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
return local.tm_hour;
}
//--------------------------------------------------
int ofGetYear(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
int year = local.tm_year + 1900;
return year;
}
//--------------------------------------------------
int ofGetMonth(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
int month = local.tm_mon + 1;
return month;
}
//--------------------------------------------------
int ofGetDay(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
return local.tm_mday;
}
//--------------------------------------------------
int ofGetWeekday(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
return local.tm_wday;
}
//--------------------------------------------------
void ofEnableDataPath(){
enableDataPath = true;
}
//--------------------------------------------------
void ofDisableDataPath(){
enableDataPath = false;
}
//use ofSetDataPathRoot() to override this
#if defined TARGET_OSX
static string dataPathRoot = "../../../data/";
#else
static string dataPathRoot = "data/";
#endif
//--------------------------------------------------
void ofSetDataPathRoot(string newRoot){
dataPathRoot = newRoot;
}
//--------------------------------------------------
string ofToDataPath(string path, bool makeAbsolute){
if( enableDataPath ){
//check if absolute path has been passed or if data path has already been applied
//do we want to check for C: D: etc ?? like substr(1, 2) == ':' ??
if( path.substr(0,1) != "/" && path.substr(1,1) != ":" && path.substr(0,dataPathRoot.length()) != dataPathRoot){
path = dataPathRoot+path;
}
if(makeAbsolute && path.substr(0,1) != "/"){
#ifndef TARGET_OF_IPHONE
#ifndef _MSC_VER
char currDir[1024];
path = "/"+path;
path = getcwd(currDir, 1024)+path;
#else
char currDir[1024];
path = "\\"+path;
path = _getcwd(currDir, 1024)+path;
std::replace( path.begin(), path.end(), '/', '\\' ); // fix any unixy paths...
#endif
#else
//do we need iphone specific code here?
#endif
}
}
return path;
}
//--------------------------------------------------
string ofToString(double value, int precision){
stringstream sstr;
sstr << fixed << setprecision(precision) << value;
return sstr.str();
}
//--------------------------------------------------
string ofToString(int value){
stringstream sstr;
sstr << value;
return sstr.str();
}
//--------------------------------------------------
int ofToInt(const string& intString) {
int x;
sscanf(intString.c_str(), "%d", &x);
return x;
}
float ofToFloat(const string& floatString) {
float x;
sscanf(floatString.c_str(), "%f", &x);
return x;
}
//--------------------------------------------------
vector<string> ofSplitString(const string& str, const string& delimiter = " "){
vector<string> elements;
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiter, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiter, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
elements.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiter, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiter, lastPos);
}
return elements;
}
//--------------------------------------------------
void ofLaunchBrowser(string url){
// http://support.microsoft.com/kb/224816
//make sure it is a properly formatted url
if(url.substr(0,7) != "http://"){
ofLog(OF_LOG_WARNING, "ofLaunchBrowser: url must begin http://");
return;
}
//----------------------------
#ifdef TARGET_WIN32
//----------------------------
#if (_MSC_VER)
// microsoft visual studio yaks about strings, wide chars, unicode, etc
ShellExecuteA(NULL, "open", url.c_str(),
NULL, NULL, SW_SHOWNORMAL);
#else
ShellExecute(NULL, "open", url.c_str(),
NULL, NULL, SW_SHOWNORMAL);
#endif
//----------------------------
#endif
//----------------------------
//--------------------------------------
#ifdef TARGET_OSX
//--------------------------------------
// ok gotta be a better way then this,
// this is what I found...
string commandStr = "open "+url;
system(commandStr.c_str());
//----------------------------
#endif
//----------------------------
//--------------------------------------
#ifdef TARGET_LINUX
//--------------------------------------
string commandStr = "xdg-open "+url;
int ret = system(commandStr.c_str());
if(ret!=0) ofLog(OF_LOG_ERROR,"ofLaunchBrowser: couldn't open browser");
//----------------------------
#endif
//----------------------------
}
//--------------------------------------------------
string ofGetVersionInfo(){
string version;
stringstream sstr;
sstr << "of version: " << OF_VERSION << endl;
return sstr.str();
}
//---- new to 006
//from the forums http://www.openframeworks.cc/forum/viewtopic.php?t=1413
//--------------------------------------------------
void ofSaveScreen(string filename) {
ofImage screen;
screen.allocate(ofGetWidth(), ofGetHeight(), OF_IMAGE_COLOR);
screen.grabScreen(0, 0, ofGetWidth(), ofGetHeight());
screen.saveImage(filename);
}
//--------------------------------------------------
int saveImageCounter = 0;
void ofSaveFrame(){
string fileName = ofToString(saveImageCounter) + ".png";
ofSaveScreen(fileName);
saveImageCounter++;
}
//levels are currently:
// see ofConstants.h
// OF_LOG_NOTICE
// OF_LOG_WARNING
// OF_LOG_ERROR
// OF_LOG_FATAL_ERROR
int currentLogLevel = OF_DEFAULT_LOG_LEVEL;
//--------------------------------------------------
void ofSetLogLevel(int logLevel){
currentLogLevel = logLevel;
}
//--------------------------------------------------
void ofLog(int logLevel, string message){
if(logLevel >= currentLogLevel){
if(logLevel == OF_LOG_VERBOSE){
printf("OF_VERBOSE: ");
}
else if(logLevel == OF_LOG_NOTICE){
printf("OF_NOTICE: ");
}
else if(logLevel == OF_LOG_WARNING){
printf("OF_WARNING: ");
}
else if(logLevel == OF_LOG_ERROR){
printf("OF_ERROR: ");
}
else if(logLevel == OF_LOG_FATAL_ERROR){
printf("OF_FATAL_ERROR: ");
}
printf("%s\n",message.c_str());
}
}
//--------------------------------------------------
void ofLog(int logLevel, const char* format, ...){
//thanks stefan!
//http://www.ozzu.com/cpp-tutorials/tutorial-writing-custom-printf-wrapper-function-t89166.html
if(logLevel >= currentLogLevel){
va_list args;
va_start( args, format );
if(logLevel == OF_LOG_VERBOSE){
printf("OF_VERBOSE: ");
}
else if(logLevel == OF_LOG_NOTICE){
printf("OF_NOTICE: ");
}
else if(logLevel == OF_LOG_WARNING){
printf("OF_WARNING: ");
}
else if(logLevel == OF_LOG_ERROR){
printf("OF_ERROR: ");
}
else if(logLevel == OF_LOG_FATAL_ERROR){
printf("OF_FATAL_ERROR: ");
}
vprintf( format, args );
printf("\n");
va_end( args );
}
}
//for setting console color
//doesn't work in the xcode console - do we need this?
//works fine on the terminal though - not much use
//--------------------------------------------------
void ofSetConsoleColor(int color){
#ifdef TARGET_WIN32
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
#else
printf("\033[%im", color);
#endif
}
//--------------------------------------------------
void ofRestoreConsoleColor(){
#ifdef TARGET_WIN32
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), OF_CONSOLE_COLOR_RESTORE);
#else
printf("\033[%im", OF_CONSOLE_COLOR_RESTORE);
#endif
}
<commit_msg>utils/ofUtils.cpp: fix for ofToDataPath with empty path. Closes #110<commit_after>#include "ofUtils.h"
#include "ofImage.h"
#if defined(TARGET_OF_IPHONE) || defined(TARGET_OSX ) || defined(TARGET_LINUX)
#include "sys/time.h"
#endif
#ifdef TARGET_WIN32
#include <mmsystem.h>
#ifdef _MSC_VER
#include <direct.h>
#endif
#endif
static bool enableDataPath = true;
static unsigned long startTime = ofGetSystemTime(); // better at the first frame ?? (currently, there is some delay from static init, to running.
//--------------------------------------
int ofGetElapsedTimeMillis(){
return (int)(ofGetSystemTime() - startTime);
}
//--------------------------------------
float ofGetElapsedTimef(){
return ((float) ((int)(ofGetSystemTime() - startTime)) / 1000.0f);
}
//--------------------------------------
void ofResetElapsedTimeCounter(){
startTime = ofGetSystemTime();
}
//=======================================
// this is from freeglut, and used internally:
/* Platform-dependent time in milliseconds, as an unsigned 32-bit integer.
* This value wraps every 49.7 days, but integer overflows cancel
* when subtracting an initial start time, unless the total time exceeds
* 32-bit, where the GLUT API return value is also overflowed.
*/
unsigned long ofGetSystemTime( ) {
#ifndef TARGET_WIN32
struct timeval now;
gettimeofday( &now, NULL );
return now.tv_usec/1000 + now.tv_sec*1000;
#else
#if defined(_WIN32_WCE)
return GetTickCount();
#else
return timeGetTime();
#endif
#endif
}
//--------------------------------------------------
int ofGetSeconds(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
return local.tm_sec;
}
//--------------------------------------------------
int ofGetMinutes(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
return local.tm_min;
}
//--------------------------------------------------
int ofGetHours(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
return local.tm_hour;
}
//--------------------------------------------------
int ofGetYear(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
int year = local.tm_year + 1900;
return year;
}
//--------------------------------------------------
int ofGetMonth(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
int month = local.tm_mon + 1;
return month;
}
//--------------------------------------------------
int ofGetDay(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
return local.tm_mday;
}
//--------------------------------------------------
int ofGetWeekday(){
time_t curr;
tm local;
time(&curr);
local =*(localtime(&curr));
return local.tm_wday;
}
//--------------------------------------------------
void ofEnableDataPath(){
enableDataPath = true;
}
//--------------------------------------------------
void ofDisableDataPath(){
enableDataPath = false;
}
//use ofSetDataPathRoot() to override this
#if defined TARGET_OSX
static string dataPathRoot = "../../../data/";
#else
static string dataPathRoot = "data/";
#endif
//--------------------------------------------------
void ofSetDataPathRoot(string newRoot){
dataPathRoot = newRoot;
}
//--------------------------------------------------
string ofToDataPath(string path, bool makeAbsolute){
if( enableDataPath ){
//check if absolute path has been passed or if data path has already been applied
//do we want to check for C: D: etc ?? like substr(1, 2) == ':' ??
if( path.length()==0 || (path.substr(0,1) != "/" && path.substr(1,1) != ":" && path.substr(0,dataPathRoot.length()) != dataPathRoot)){
path = dataPathRoot+path;
}
if(makeAbsolute && (path.length()==0 || path.substr(0,1) != "/")){
#ifndef TARGET_OF_IPHONE
#ifndef _MSC_VER
char currDir[1024];
path = "/"+path;
path = getcwd(currDir, 1024)+path;
#else
char currDir[1024];
path = "\\"+path;
path = _getcwd(currDir, 1024)+path;
std::replace( path.begin(), path.end(), '/', '\\' ); // fix any unixy paths...
#endif
#else
//do we need iphone specific code here?
#endif
}
}
return path;
}
//--------------------------------------------------
string ofToString(double value, int precision){
stringstream sstr;
sstr << fixed << setprecision(precision) << value;
return sstr.str();
}
//--------------------------------------------------
string ofToString(int value){
stringstream sstr;
sstr << value;
return sstr.str();
}
//--------------------------------------------------
int ofToInt(const string& intString) {
int x;
sscanf(intString.c_str(), "%d", &x);
return x;
}
float ofToFloat(const string& floatString) {
float x;
sscanf(floatString.c_str(), "%f", &x);
return x;
}
//--------------------------------------------------
vector<string> ofSplitString(const string& str, const string& delimiter = " "){
vector<string> elements;
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiter, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiter, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
elements.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiter, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiter, lastPos);
}
return elements;
}
//--------------------------------------------------
void ofLaunchBrowser(string url){
// http://support.microsoft.com/kb/224816
//make sure it is a properly formatted url
if(url.substr(0,7) != "http://"){
ofLog(OF_LOG_WARNING, "ofLaunchBrowser: url must begin http://");
return;
}
//----------------------------
#ifdef TARGET_WIN32
//----------------------------
#if (_MSC_VER)
// microsoft visual studio yaks about strings, wide chars, unicode, etc
ShellExecuteA(NULL, "open", url.c_str(),
NULL, NULL, SW_SHOWNORMAL);
#else
ShellExecute(NULL, "open", url.c_str(),
NULL, NULL, SW_SHOWNORMAL);
#endif
//----------------------------
#endif
//----------------------------
//--------------------------------------
#ifdef TARGET_OSX
//--------------------------------------
// ok gotta be a better way then this,
// this is what I found...
string commandStr = "open "+url;
system(commandStr.c_str());
//----------------------------
#endif
//----------------------------
//--------------------------------------
#ifdef TARGET_LINUX
//--------------------------------------
string commandStr = "xdg-open "+url;
int ret = system(commandStr.c_str());
if(ret!=0) ofLog(OF_LOG_ERROR,"ofLaunchBrowser: couldn't open browser");
//----------------------------
#endif
//----------------------------
}
//--------------------------------------------------
string ofGetVersionInfo(){
string version;
stringstream sstr;
sstr << "of version: " << OF_VERSION << endl;
return sstr.str();
}
//---- new to 006
//from the forums http://www.openframeworks.cc/forum/viewtopic.php?t=1413
//--------------------------------------------------
void ofSaveScreen(string filename) {
ofImage screen;
screen.allocate(ofGetWidth(), ofGetHeight(), OF_IMAGE_COLOR);
screen.grabScreen(0, 0, ofGetWidth(), ofGetHeight());
screen.saveImage(filename);
}
//--------------------------------------------------
int saveImageCounter = 0;
void ofSaveFrame(){
string fileName = ofToString(saveImageCounter) + ".png";
ofSaveScreen(fileName);
saveImageCounter++;
}
//levels are currently:
// see ofConstants.h
// OF_LOG_NOTICE
// OF_LOG_WARNING
// OF_LOG_ERROR
// OF_LOG_FATAL_ERROR
int currentLogLevel = OF_DEFAULT_LOG_LEVEL;
//--------------------------------------------------
void ofSetLogLevel(int logLevel){
currentLogLevel = logLevel;
}
//--------------------------------------------------
void ofLog(int logLevel, string message){
if(logLevel >= currentLogLevel){
if(logLevel == OF_LOG_VERBOSE){
printf("OF_VERBOSE: ");
}
else if(logLevel == OF_LOG_NOTICE){
printf("OF_NOTICE: ");
}
else if(logLevel == OF_LOG_WARNING){
printf("OF_WARNING: ");
}
else if(logLevel == OF_LOG_ERROR){
printf("OF_ERROR: ");
}
else if(logLevel == OF_LOG_FATAL_ERROR){
printf("OF_FATAL_ERROR: ");
}
printf("%s\n",message.c_str());
}
}
//--------------------------------------------------
void ofLog(int logLevel, const char* format, ...){
//thanks stefan!
//http://www.ozzu.com/cpp-tutorials/tutorial-writing-custom-printf-wrapper-function-t89166.html
if(logLevel >= currentLogLevel){
va_list args;
va_start( args, format );
if(logLevel == OF_LOG_VERBOSE){
printf("OF_VERBOSE: ");
}
else if(logLevel == OF_LOG_NOTICE){
printf("OF_NOTICE: ");
}
else if(logLevel == OF_LOG_WARNING){
printf("OF_WARNING: ");
}
else if(logLevel == OF_LOG_ERROR){
printf("OF_ERROR: ");
}
else if(logLevel == OF_LOG_FATAL_ERROR){
printf("OF_FATAL_ERROR: ");
}
vprintf( format, args );
printf("\n");
va_end( args );
}
}
//for setting console color
//doesn't work in the xcode console - do we need this?
//works fine on the terminal though - not much use
//--------------------------------------------------
void ofSetConsoleColor(int color){
#ifdef TARGET_WIN32
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
#else
printf("\033[%im", color);
#endif
}
//--------------------------------------------------
void ofRestoreConsoleColor(){
#ifdef TARGET_WIN32
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), OF_CONSOLE_COLOR_RESTORE);
#else
printf("\033[%im", OF_CONSOLE_COLOR_RESTORE);
#endif
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "debuggertoolchaincombobox.h"
#include "debuggerprofileinformation.h"
#include <projectexplorer/profileinformation.h>
#include <projectexplorer/profilemanager.h>
#include <projectexplorer/abi.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
#include <QDir>
#include <QPair>
#include <QtEvents>
typedef QPair<ProjectExplorer::Abi, QString> AbiDebuggerCommandPair;
Q_DECLARE_METATYPE(AbiDebuggerCommandPair)
namespace Debugger {
namespace Internal {
DebuggerToolChainComboBox::DebuggerToolChainComboBox(QWidget *parent) :
QComboBox(parent)
{
}
void DebuggerToolChainComboBox::init(bool hostAbiOnly)
{
const ProjectExplorer::Abi hostAbi = ProjectExplorer::Abi::hostAbi();
foreach (const ProjectExplorer::Profile *st,
ProjectExplorer::ProfileManager::instance()->profiles()) {
if (!st->isValid())
continue;
ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainProfileInformation::toolChain(st);
if (!tc)
continue;
const ProjectExplorer::Abi abi = tc->targetAbi();
if (hostAbiOnly && hostAbi.os() != abi.os())
continue;
const QString debuggerCommand = DebuggerProfileInformation::debuggerCommand(st).toString();
if (debuggerCommand.isEmpty())
continue;
const AbiDebuggerCommandPair data(abi, debuggerCommand);
const QString completeBase = QFileInfo(debuggerCommand).completeBaseName();
const QString name = tr("%1 (%2)").arg(st->displayName(), completeBase);
addItem(name, qVariantFromValue(data));
}
setEnabled(count() > 1);
}
void DebuggerToolChainComboBox::setAbi(const ProjectExplorer::Abi &abi)
{
QTC_ASSERT(abi.isValid(), return);
const int c = count();
for (int i = 0; i < c; i++) {
if (abiAt(i) == abi) {
setCurrentIndex(i);
break;
}
}
}
ProjectExplorer::Abi DebuggerToolChainComboBox::abi() const
{
return abiAt(currentIndex());
}
QString DebuggerToolChainComboBox::debuggerCommand() const
{
return debuggerCommandAt(currentIndex());
}
QString DebuggerToolChainComboBox::debuggerCommandAt(int index) const
{
if (index >= 0 && index < count()) {
const AbiDebuggerCommandPair abiCommandPair = qvariant_cast<AbiDebuggerCommandPair>(itemData(index));
return abiCommandPair.second;
}
return QString();
}
ProjectExplorer::Abi DebuggerToolChainComboBox::abiAt(int index) const
{
if (index >= 0 && index < count()) {
const AbiDebuggerCommandPair abiCommandPair = qvariant_cast<AbiDebuggerCommandPair>(itemData(index));
return abiCommandPair.first;
}
return ProjectExplorer::Abi();
}
static inline QString abiToolTip(const AbiDebuggerCommandPair &abiCommandPair)
{
QString debugger = QDir::toNativeSeparators(abiCommandPair.second);
debugger.replace(QString(QLatin1Char(' ')), QLatin1String(" "));
return DebuggerToolChainComboBox::tr(
"<html><head/><body><table><tr><td>ABI:</td><td><i>%1</i></td></tr>"
"<tr><td>Debugger:</td><td>%2</td></tr>").
arg(abiCommandPair.first.toString(),
QDir::toNativeSeparators(debugger));
}
bool DebuggerToolChainComboBox::event(QEvent *event)
{
if (event->type() == QEvent::ToolTip) {
const int index = currentIndex();
if (index >= 0) {
const AbiDebuggerCommandPair abiCommandPair = qvariant_cast<AbiDebuggerCommandPair>(itemData(index));
setToolTip(abiToolTip(abiCommandPair));
} else {
setToolTip(QString());
}
}
return QComboBox::event(event);
}
} // namespace Debugger
} // namespace Internal
<commit_msg>debugger: reduce line noise<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "debuggertoolchaincombobox.h"
#include "debuggerprofileinformation.h"
#include <projectexplorer/profileinformation.h>
#include <projectexplorer/profilemanager.h>
#include <projectexplorer/abi.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
#include <QDir>
#include <QPair>
#include <QtEvents>
using namespace ProjectExplorer;
typedef QPair<Abi, QString> AbiDebuggerCommandPair;
Q_DECLARE_METATYPE(AbiDebuggerCommandPair)
namespace Debugger {
namespace Internal {
DebuggerToolChainComboBox::DebuggerToolChainComboBox(QWidget *parent) :
QComboBox(parent)
{
}
void DebuggerToolChainComboBox::init(bool hostAbiOnly)
{
const Abi hostAbi = Abi::hostAbi();
foreach (const Profile *st, ProfileManager::instance()->profiles()) {
if (!st->isValid())
continue;
ToolChain *tc = ToolChainProfileInformation::toolChain(st);
if (!tc)
continue;
const Abi abi = tc->targetAbi();
if (hostAbiOnly && hostAbi.os() != abi.os())
continue;
const QString debuggerCommand = DebuggerProfileInformation::debuggerCommand(st).toString();
if (debuggerCommand.isEmpty())
continue;
const AbiDebuggerCommandPair data(abi, debuggerCommand);
const QString completeBase = QFileInfo(debuggerCommand).completeBaseName();
const QString name = tr("%1 (%2)").arg(st->displayName(), completeBase);
addItem(name, qVariantFromValue(data));
}
setEnabled(count() > 1);
}
void DebuggerToolChainComboBox::setAbi(const Abi &abi)
{
QTC_ASSERT(abi.isValid(), return);
const int c = count();
for (int i = 0; i < c; i++) {
if (abiAt(i) == abi) {
setCurrentIndex(i);
break;
}
}
}
Abi DebuggerToolChainComboBox::abi() const
{
return abiAt(currentIndex());
}
QString DebuggerToolChainComboBox::debuggerCommand() const
{
return debuggerCommandAt(currentIndex());
}
QString DebuggerToolChainComboBox::debuggerCommandAt(int index) const
{
if (index >= 0 && index < count()) {
const AbiDebuggerCommandPair abiCommandPair = qvariant_cast<AbiDebuggerCommandPair>(itemData(index));
return abiCommandPair.second;
}
return QString();
}
Abi DebuggerToolChainComboBox::abiAt(int index) const
{
if (index >= 0 && index < count()) {
const AbiDebuggerCommandPair abiCommandPair = qvariant_cast<AbiDebuggerCommandPair>(itemData(index));
return abiCommandPair.first;
}
return Abi();
}
static inline QString abiToolTip(const AbiDebuggerCommandPair &abiCommandPair)
{
QString debugger = QDir::toNativeSeparators(abiCommandPair.second);
debugger.replace(QString(QLatin1Char(' ')), QLatin1String(" "));
return DebuggerToolChainComboBox::tr(
"<html><head/><body><table><tr><td>ABI:</td><td><i>%1</i></td></tr>"
"<tr><td>Debugger:</td><td>%2</td></tr>").
arg(abiCommandPair.first.toString(),
QDir::toNativeSeparators(debugger));
}
bool DebuggerToolChainComboBox::event(QEvent *event)
{
if (event->type() == QEvent::ToolTip) {
const int index = currentIndex();
if (index >= 0) {
const AbiDebuggerCommandPair abiCommandPair = qvariant_cast<AbiDebuggerCommandPair>(itemData(index));
setToolTip(abiToolTip(abiCommandPair));
} else {
setToolTip(QString());
}
}
return QComboBox::event(event);
}
} // namespace Debugger
} // namespace Internal
<|endoftext|> |
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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 manager
//==============================================================================
#include "cliutils.h"
#include "filemanager.h"
//==============================================================================
#include <QApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QIODevice>
#include <QTemporaryFile>
#include <QTextStream>
#include <QTimer>
//==============================================================================
namespace OpenCOR {
namespace Core {
//==============================================================================
FileManager::FileManager() :
mCanCheckFiles(true),
mFiles(QMap<QString, File *>()),
mFilesReadable(QMap<QString, bool>()),
mFilesWritable(QMap<QString, bool>())
{
// Create our timer
mTimer = new QTimer(this);
// A connection to handle the timing out of our timer
connect(mTimer, SIGNAL(timeout()),
this, SLOT(checkFiles()));
}
//==============================================================================
FileManager::~FileManager()
{
// Delete some internal objects
delete mTimer;
// Remove all the managed files
foreach (File *file, mFiles)
delete file;
}
//==============================================================================
FileManager * FileManager::instance()
{
// Return the 'global' instance of our file manager class
static FileManager instance;
return static_cast<FileManager *>(Core::globalInstance("OpenCOR::Core::FileManager::instance()",
&instance));
}
//==============================================================================
FileManager::Status FileManager::manage(const QString &pFileName,
const File::Type &pType,
const QString &pUrl)
{
// Manage the given file, should it not be already managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
if (QFile::exists(nativeFileName)) {
if (isManaged(nativeFileName)) {
// The file is already managed, so...
return AlreadyManaged;
} else {
// The file isn't already managed, so add it to our list of managed
// files and let people know about it being now managed
mFiles.insert(nativeFileName, new File(nativeFileName, pType, pUrl));
if (!mTimer->isActive())
mTimer->start(1000);
emit fileManaged(nativeFileName);
return Added;
}
} else {
// The file doesn't exist, so...
return DoesNotExist;
}
}
//==============================================================================
FileManager::Status FileManager::unmanage(const QString &pFileName)
{
// Unmanage the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file) {
// The file is managed, so we can remove it
mFiles.remove(nativeFileName);;
delete file;
if (mFiles.isEmpty())
mTimer->stop();
emit fileUnmanaged(nativeFileName);
return Removed;
} else {
// The file isn't managed, so...
return NotManaged;
}
}
//==============================================================================
File * FileManager::isManaged(const QString &pFileName) const
{
// Return whether the given file is managed
return mFiles.value(nativeCanonicalFileName(pFileName), 0);
}
//==============================================================================
bool FileManager::canCheckFiles() const
{
// Return whether we can check files
return mCanCheckFiles;
}
//==============================================================================
void FileManager::setCanCheckFiles(const bool &pCanCheckFiles)
{
// Set whether we can check files
mCanCheckFiles = pCanCheckFiles;
}
//==============================================================================
QString FileManager::sha1(const QString &pFileName) const
{
// Return the SHA-1 value of the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file)
return file->sha1();
else
return QString();
}
//==============================================================================
void FileManager::reset(const QString &pFileName)
{
// Reset the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file)
file->reset();
}
//==============================================================================
int FileManager::newIndex(const QString &pFileName) const
{
// Return the given file's new index, if it is being managed
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->newIndex();
else
return 0;
}
//==============================================================================
QString FileManager::url(const QString &pFileName) const
{
// Return the given file's URL, if it is being managed
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->url();
else
return QString();
}
//==============================================================================
bool FileManager::isDifferent(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is different from
// its corresponding physical version
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isDifferent();
else
return false;
}
//==============================================================================
bool FileManager::isDifferent(const QString &pFileName,
const QString &pFileContents) const
{
// Return whether the given file, if it is being managed, has the same
// contents has the given one
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isDifferent(pFileContents);
else
return false;
}
//==============================================================================
bool FileManager::isNew(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is new
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isNew();
else
return false;
}
//==============================================================================
bool FileManager::isRemote(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is a remote one
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isRemote();
else
return false;
}
//==============================================================================
bool FileManager::isModified(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, has been modified
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isModified();
else
return false;
}
//==============================================================================
bool FileManager::isNewOrModified(const QString &pFileName) const
{
// Return whether the given file is new or modified
return isNew(pFileName) || isModified(pFileName);
}
//==============================================================================
void FileManager::makeNew(const QString &pFileName)
{
// Make the given file new, should it be managed
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file) {
QString newFileName;
if (newFile(QString(), newFileName))
file->makeNew(newFileName);
}
}
//==============================================================================
void FileManager::setModified(const QString &pFileName, const bool &pModified)
{
// Set the modified state of the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file && file->setModified(pModified))
emit fileModified(nativeFileName);
}
//==============================================================================
void FileManager::setConsiderModified(const QString &pFileName,
const bool &pConsiderModified)
{
// Set the consider modified state of the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file && file->setConsiderModified(pConsiderModified))
emit fileModified(nativeFileName);
}
//==============================================================================
bool FileManager::isReadable(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is readable
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isReadable();
else
return false;
}
//==============================================================================
bool FileManager::isWritable(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is writable
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isWritable();
else
return false;
}
//==============================================================================
bool FileManager::isReadableAndWritable(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is readable and
// writable
return isReadable(pFileName) && isWritable(pFileName);
}
//==============================================================================
bool FileManager::isLocked(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is locked
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isLocked();
else
return false;
}
//==============================================================================
FileManager::Status FileManager::setLocked(const QString &pFileName,
const bool &pLocked)
{
// Set the locked status of the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file) {
File::Status status = file->setLocked(pLocked);
if (status == File::LockedSet)
emit filePermissionsChanged(nativeFileName);
if (status == File::LockedNotNeeded)
return LockedNotNeeded;
else if (status == File::LockedSet)
return LockedSet;
else
return LockedNotSet;
} else {
return NotManaged;
}
}
//==============================================================================
void FileManager::reload(const QString &pFileName)
{
// Make sure that the given file is managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file) {
// The file is managed, so reset its settings and let people know that
// it should be reloaded
file->reset();
emit fileReloaded(nativeFileName);
}
}
//==============================================================================
bool FileManager::newFile(const QString &pContents, QString &pFileName)
{
// Create a new file
QTemporaryFile file(QDir::tempPath()+QDir::separator()+"XXXXXX.tmp");
if (file.open()) {
file.setAutoRemove(false);
// Note: by default, a temporary file is to autoremove itself, but we
// clearly don't want that here...
QTextStream fileOut(&file);
fileOut << pContents;
file.close();
pFileName = file.fileName();
return true;
} else {
pFileName = QString();
return false;
}
}
//==============================================================================
FileManager::Status FileManager::create(const QString &pUrl,
const QString &pContents)
{
// Create a new file
QString createdFileName;
if (newFile(pContents, createdFileName)) {
// Let people know that we have created a file
emit fileCreated(createdFileName, pUrl);
return Created;
} else {
return NotCreated;
}
}
//==============================================================================
FileManager::Status FileManager::rename(const QString &pOldFileName,
const QString &pNewFileName)
{
// Make sure that the given 'old' file is managed
QString oldNativeFileName = nativeCanonicalFileName(pOldFileName);
File *file = isManaged(oldNativeFileName);
if (file) {
// The 'old' file is managed, so rename it and let people know about it
QString newNativeFileName = nativeCanonicalFileName(pNewFileName);
if (file->setFileName(newNativeFileName)) {
mFiles.insert(newNativeFileName, mFiles.value(oldNativeFileName));
mFiles.remove(oldNativeFileName);;
emit fileRenamed(oldNativeFileName, newNativeFileName);
return Renamed;
} else {
return RenamingNotNeeded;
}
} else {
return NotManaged;
}
}
//==============================================================================
FileManager::Status FileManager::duplicate(const QString &pFileName)
{
// Make sure that the given file is managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file) {
// The file is managed, so retrieve its contents
QString fileContents;
if (Core::readTextFromFile(pFileName, fileContents)) {
// Now, we can create a new file, which contents will be that of our
// given file
QString duplicatedFileName;
if (newFile(fileContents, duplicatedFileName)) {
// Let people know that we have duplicated a file
emit fileDuplicated(duplicatedFileName);
return Duplicated;
} else {
return NotDuplicated;
}
} else {
return NotDuplicated;
}
} else {
return NotManaged;
}
}
//==============================================================================
int FileManager::count() const
{
// Return the number of files currently being managed
return mFiles.count();
}
//==============================================================================
void FileManager::checkFiles()
{
// We only want to check our files if we can check files and if there is no
// currently active dialog box
if (!mCanCheckFiles || QApplication::activeModalWidget())
return;
// Check our various files, as well as their locked status, but only if they
// are not being ignored
foreach (File *file, mFiles) {
QString fileName = file->fileName();
switch (file->check()) {
case File::Changed:
// The file has changed, so let people know about it
emit fileChanged(fileName);
break;
case File::Deleted:
// The file has been deleted, so let people know about it
emit fileDeleted(fileName);
break;
default:
// The file has neither changed nor been deleted, so check whether
// its permissions have changed
bool fileReadable = isReadable(fileName);
bool fileWritable = isWritable(fileName);
if ( (fileReadable != mFilesReadable.value(fileName, false))
|| (fileWritable != mFilesWritable.value(fileName, false))
|| !( mFilesReadable.contains(fileName)
&& mFilesWritable.contains(fileName))) {
emit filePermissionsChanged(fileName);
mFilesReadable.insert(fileName, fileReadable);
mFilesWritable.insert(fileName, fileWritable);
}
}
}
}
//==============================================================================
} // namespace Core
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Fixed the issue that prevented the CellML Tools plugin from exporting a remote CellML 1.1 file to a given file (closes #422).<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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 manager
//==============================================================================
#include "cliutils.h"
#include "filemanager.h"
//==============================================================================
#include <QApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QIODevice>
#include <QTemporaryFile>
#include <QTextStream>
#include <QTimer>
//==============================================================================
namespace OpenCOR {
namespace Core {
//==============================================================================
FileManager::FileManager() :
mCanCheckFiles(true),
mFiles(QMap<QString, File *>()),
mFilesReadable(QMap<QString, bool>()),
mFilesWritable(QMap<QString, bool>())
{
// Create our timer
mTimer = new QTimer(this);
// A connection to handle the timing out of our timer
connect(mTimer, SIGNAL(timeout()),
this, SLOT(checkFiles()));
}
//==============================================================================
FileManager::~FileManager()
{
// Delete some internal objects
delete mTimer;
// Remove all the managed files
foreach (File *file, mFiles)
delete file;
}
//==============================================================================
FileManager * FileManager::instance()
{
// Return the 'global' instance of our file manager class
static FileManager instance;
return static_cast<FileManager *>(Core::globalInstance("OpenCOR::Core::FileManager::instance()",
&instance));
}
//==============================================================================
FileManager::Status FileManager::manage(const QString &pFileName,
const File::Type &pType,
const QString &pUrl)
{
// Manage the given file, should it not be already managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
if (QFile::exists(nativeFileName)) {
if (isManaged(nativeFileName)) {
// The file is already managed, so...
return AlreadyManaged;
} else {
// The file isn't already managed, so add it to our list of managed
// files and let people know about it being now managed
mFiles.insert(nativeFileName, new File(nativeFileName, pType, pUrl));
if (!mTimer->isActive())
mTimer->start(1000);
emit fileManaged(nativeFileName);
return Added;
}
} else {
// The file doesn't exist, so...
return DoesNotExist;
}
}
//==============================================================================
FileManager::Status FileManager::unmanage(const QString &pFileName)
{
// Unmanage the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file) {
// The file is managed, so we can remove it
mFiles.remove(nativeFileName);;
delete file;
if (mFiles.isEmpty())
mTimer->stop();
emit fileUnmanaged(nativeFileName);
return Removed;
} else {
// The file isn't managed, so...
return NotManaged;
}
}
//==============================================================================
File * FileManager::isManaged(const QString &pFileName) const
{
// Return whether the given file is managed
return mFiles.value(nativeCanonicalFileName(pFileName), 0);
}
//==============================================================================
bool FileManager::canCheckFiles() const
{
// Return whether we can check files
return mCanCheckFiles;
}
//==============================================================================
void FileManager::setCanCheckFiles(const bool &pCanCheckFiles)
{
// Set whether we can check files
mCanCheckFiles = pCanCheckFiles;
}
//==============================================================================
QString FileManager::sha1(const QString &pFileName) const
{
// Return the SHA-1 value of the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file)
return file->sha1();
else
return QString();
}
//==============================================================================
void FileManager::reset(const QString &pFileName)
{
// Reset the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file)
file->reset();
}
//==============================================================================
int FileManager::newIndex(const QString &pFileName) const
{
// Return the given file's new index, if it is being managed
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->newIndex();
else
return 0;
}
//==============================================================================
QString FileManager::url(const QString &pFileName) const
{
// Return the given file's URL, if it is being managed
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->url();
else
return QString();
}
//==============================================================================
bool FileManager::isDifferent(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is different from
// its corresponding physical version
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isDifferent();
else
return false;
}
//==============================================================================
bool FileManager::isDifferent(const QString &pFileName,
const QString &pFileContents) const
{
// Return whether the given file, if it is being managed, has the same
// contents has the given one
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isDifferent(pFileContents);
else
return false;
}
//==============================================================================
bool FileManager::isNew(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is new
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isNew();
else
return false;
}
//==============================================================================
bool FileManager::isRemote(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is a remote one
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isRemote();
else
return false;
}
//==============================================================================
bool FileManager::isModified(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, has been modified
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isModified();
else
return false;
}
//==============================================================================
bool FileManager::isNewOrModified(const QString &pFileName) const
{
// Return whether the given file is new or modified
return isNew(pFileName) || isModified(pFileName);
}
//==============================================================================
void FileManager::makeNew(const QString &pFileName)
{
// Make the given file new, should it be managed
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file) {
QString newFileName;
if (newFile(QString(), newFileName))
file->makeNew(newFileName);
}
}
//==============================================================================
void FileManager::setModified(const QString &pFileName, const bool &pModified)
{
// Set the modified state of the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file && file->setModified(pModified))
emit fileModified(nativeFileName);
}
//==============================================================================
void FileManager::setConsiderModified(const QString &pFileName,
const bool &pConsiderModified)
{
// Set the consider modified state of the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file && file->setConsiderModified(pConsiderModified))
emit fileModified(nativeFileName);
}
//==============================================================================
bool FileManager::isReadable(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is readable
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isReadable();
else
return false;
}
//==============================================================================
bool FileManager::isWritable(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is writable
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isWritable();
else
return false;
}
//==============================================================================
bool FileManager::isReadableAndWritable(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is readable and
// writable
return isReadable(pFileName) && isWritable(pFileName);
}
//==============================================================================
bool FileManager::isLocked(const QString &pFileName) const
{
// Return whether the given file, if it is being managed, is locked
File *file = isManaged(nativeCanonicalFileName(pFileName));
if (file)
return file->isLocked();
else
return false;
}
//==============================================================================
FileManager::Status FileManager::setLocked(const QString &pFileName,
const bool &pLocked)
{
// Set the locked status of the given file, should it be managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file) {
File::Status status = file->setLocked(pLocked);
if (status == File::LockedSet)
emit filePermissionsChanged(nativeFileName);
if (status == File::LockedNotNeeded)
return LockedNotNeeded;
else if (status == File::LockedSet)
return LockedSet;
else
return LockedNotSet;
} else {
return NotManaged;
}
}
//==============================================================================
void FileManager::reload(const QString &pFileName)
{
// Make sure that the given file is managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file) {
// The file is managed, so reset its settings and let people know that
// it should be reloaded
file->reset();
emit fileReloaded(nativeFileName);
}
}
//==============================================================================
bool FileManager::newFile(const QString &pContents, QString &pFileName)
{
// Create a new file
QTemporaryFile file(QDir::tempPath()+QDir::separator()+"XXXXXX.tmp");
if (file.open()) {
file.setAutoRemove(false);
// Note: by default, a temporary file is to autoremove itself, but we
// clearly don't want that here...
QTextStream fileOut(&file);
fileOut << pContents;
file.close();
pFileName = file.fileName();
return true;
} else {
pFileName = QString();
return false;
}
}
//==============================================================================
FileManager::Status FileManager::create(const QString &pUrl,
const QString &pContents)
{
// Create a new file
QString createdFileName;
if (newFile(pContents, createdFileName)) {
// Let people know that we have created a file
emit fileCreated(createdFileName, pUrl);
return Created;
} else {
return NotCreated;
}
}
//==============================================================================
FileManager::Status FileManager::rename(const QString &pOldFileName,
const QString &pNewFileName)
{
// Make sure that the given 'old' file is managed
QString oldNativeFileName = nativeCanonicalFileName(pOldFileName);
File *file = isManaged(oldNativeFileName);
if (file) {
// The 'old' file is managed, so rename it and let people know about it
QString newNativeFileName = nativeCanonicalFileName(pNewFileName);
if (file->setFileName(newNativeFileName)) {
mFiles.insert(newNativeFileName, mFiles.value(oldNativeFileName));
mFiles.remove(oldNativeFileName);;
emit fileRenamed(oldNativeFileName, newNativeFileName);
return Renamed;
} else {
return RenamingNotNeeded;
}
} else {
return NotManaged;
}
}
//==============================================================================
FileManager::Status FileManager::duplicate(const QString &pFileName)
{
// Make sure that the given file is managed
QString nativeFileName = nativeCanonicalFileName(pFileName);
File *file = isManaged(nativeFileName);
if (file) {
// The file is managed, so retrieve its contents
QString fileContents;
if (Core::readTextFromFile(pFileName, fileContents)) {
// Now, we can create a new file, which contents will be that of our
// given file
QString duplicatedFileName;
if (newFile(fileContents, duplicatedFileName)) {
// Let people know that we have duplicated a file
emit fileDuplicated(duplicatedFileName);
return Duplicated;
} else {
return NotDuplicated;
}
} else {
return NotDuplicated;
}
} else {
return NotManaged;
}
}
//==============================================================================
int FileManager::count() const
{
// Return the number of files currently being managed
return mFiles.count();
}
//==============================================================================
void FileManager::checkFiles()
{
// We only want to check our files if we can check files and if there is no
// currently active dialog box (which requires at least one top level
// widget)
if ( !mCanCheckFiles
|| !QApplication::topLevelWidgets().count()
|| QApplication::activePopupWidget())
return;
// Check our various files, as well as their locked status, but only if they
// are not being ignored
foreach (File *file, mFiles) {
QString fileName = file->fileName();
switch (file->check()) {
case File::Changed:
// The file has changed, so let people know about it
emit fileChanged(fileName);
break;
case File::Deleted:
// The file has been deleted, so let people know about it
emit fileDeleted(fileName);
break;
default:
// The file has neither changed nor been deleted, so check whether
// its permissions have changed
bool fileReadable = isReadable(fileName);
bool fileWritable = isWritable(fileName);
if ( (fileReadable != mFilesReadable.value(fileName, false))
|| (fileWritable != mFilesWritable.value(fileName, false))
|| !( mFilesReadable.contains(fileName)
&& mFilesWritable.contains(fileName))) {
emit filePermissionsChanged(fileName);
mFilesReadable.insert(fileName, fileReadable);
mFilesWritable.insert(fileName, fileWritable);
}
}
}
}
//==============================================================================
} // namespace Core
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2013 Mohammed Nafees <[email protected]>
//
#include "NavigationButton.h"
#include <QtGui/QPainter>
#include <QtGui/QMouseEvent>
namespace Marble
{
NavigationButton::NavigationButton( QWidget *parent )
: QAbstractButton( parent ),
m_iconMode( QIcon::Normal )
{
// nothing to do
}
void NavigationButton::mousePressEvent ( QMouseEvent *mouseEvent )
{
if ( isEnabled() ) {
if ( mouseEvent->button() == Qt::LeftButton ) {
m_iconMode = QIcon::Selected;
}
}
emit repaintNeeded();
}
void NavigationButton::mouseReleaseEvent ( QMouseEvent * )
{
if ( isEnabled() ) {
m_iconMode = QIcon::Normal;
emit clicked();
}
emit repaintNeeded();
}
void NavigationButton::enterEvent(QEvent *)
{
if ( isEnabled() ) {
m_iconMode = QIcon::Active;
}
emit repaintNeeded();
}
void NavigationButton::leaveEvent( QEvent * )
{
if ( isEnabled() ) {
m_iconMode = QIcon::Normal;
}
emit repaintNeeded();
}
void NavigationButton::changeEvent( QEvent *e )
{
if ( e->type() == QEvent::EnabledChange ) {
m_iconMode = isEnabled() ? QIcon::Normal : QIcon::Disabled;
}
emit repaintNeeded();
}
void NavigationButton::paintEvent( QPaintEvent * )
{
QPainter painter( this );
painter.drawPixmap( 0, 0, icon().pixmap( iconSize(), m_iconMode ) );
}
}
#include "NavigationButton.moc"
<commit_msg>Hover effect on mouse release.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2013 Mohammed Nafees <[email protected]>
//
#include "NavigationButton.h"
#include <QtGui/QPainter>
#include <QtGui/QMouseEvent>
namespace Marble
{
NavigationButton::NavigationButton( QWidget *parent )
: QAbstractButton( parent ),
m_iconMode( QIcon::Normal )
{
// nothing to do
}
void NavigationButton::mousePressEvent ( QMouseEvent *mouseEvent )
{
if ( isEnabled() ) {
if ( mouseEvent->button() == Qt::LeftButton ) {
m_iconMode = QIcon::Selected;
}
}
emit repaintNeeded();
}
void NavigationButton::mouseReleaseEvent ( QMouseEvent * )
{
if ( isEnabled() ) {
m_iconMode = QIcon::Active;
emit clicked();
}
emit repaintNeeded();
}
void NavigationButton::enterEvent(QEvent *)
{
if ( isEnabled() ) {
m_iconMode = QIcon::Active;
}
emit repaintNeeded();
}
void NavigationButton::leaveEvent( QEvent * )
{
if ( isEnabled() ) {
m_iconMode = QIcon::Normal;
}
emit repaintNeeded();
}
void NavigationButton::changeEvent( QEvent *e )
{
if ( e->type() == QEvent::EnabledChange ) {
m_iconMode = isEnabled() ? QIcon::Normal : QIcon::Disabled;
}
emit repaintNeeded();
}
void NavigationButton::paintEvent( QPaintEvent * )
{
QPainter painter( this );
painter.drawPixmap( 0, 0, icon().pixmap( iconSize(), m_iconMode ) );
}
}
#include "NavigationButton.moc"
<|endoftext|> |
<commit_before>#ifndef SCENE_BUILDINGS_FACADES_LOWPOLYWALLBUILDER_HPP_DEFINED
#define SCENE_BUILDINGS_FACADES_LOWPOLYWALLBUILDER_HPP_DEFINED
#include "GeoCoordinate.hpp"
#include "meshing/MeshTypes.hpp"
#include "mapcss/ColorGradient.hpp"
namespace utymap { namespace scene {
// Responsible for building facade wall in low poly quality.
class LowPolyWallBuilder
{
protected:
// Represents point in 3d where y points up.
struct Point3d
{
double x, y, z;
Point3d(double x, double y, double z) : x(x), y(y), z(z) {}
};
public:
LowPolyWallBuilder(const utymap::meshing::Mesh& mesh,
const utymap::mapcss::ColorGradient& gradient)
: mesh_(mesh), gradient_(gradient), height_(12), minHeight_(0)
{
}
// Sets height of wall.
inline LowPolyWallBuilder& setHeight(double height) { height_ = height; return *this; }
// Sets height above ground level.
inline LowPolyWallBuilder& setMinHeight(double minHeight) { minHeight_ = minHeight; return *this; }
void build(const utymap::GeoCoordinate& start, const utymap::GeoCoordinate& end)
{
addPlane(start, end);
}
private:
void addPlane(const utymap::GeoCoordinate& p1, const utymap::GeoCoordinate& p2)
{
double top = minHeight_ + height_;
int color = 0, index = mesh_.triangles.size();
// first triangle
addVertex(p1, minHeight_, index++, color);
addVertex(p2, minHeight_, index++, color);
addVertex(p2, top, index++, color);
// second triangle
addVertex(p2, minHeight_, index++, color);
addVertex(p2, top, index++, color);
addVertex(p1, top, index, color);
}
inline void addVertex(const utymap::GeoCoordinate& coordinate, double height, int triIndex, int color)
{
mesh_.vertices.push_back(coordinate.longitude);
mesh_.vertices.push_back(coordinate.latitude);
mesh_.vertices.push_back(height);
mesh_.triangles.push_back(triIndex);
mesh_.colors.push_back(color);
}
const utymap::meshing::Mesh& mesh_;
const utymap::mapcss::ColorGradient& gradient_;
double height_, minHeight_;
};
}}
#endif // SCENE_BUILDINGS_FACADES_LOWPOLYWALLBUILDER_HPP_DEFINED
<commit_msg>refactoring: remove dead code<commit_after>#ifndef SCENE_BUILDINGS_FACADES_LOWPOLYWALLBUILDER_HPP_DEFINED
#define SCENE_BUILDINGS_FACADES_LOWPOLYWALLBUILDER_HPP_DEFINED
#include "GeoCoordinate.hpp"
#include "meshing/MeshTypes.hpp"
#include "mapcss/ColorGradient.hpp"
namespace utymap { namespace scene {
// Responsible for building facade wall in low poly quality.
class LowPolyWallBuilder
{
public:
LowPolyWallBuilder(const utymap::meshing::Mesh& mesh,
const utymap::mapcss::ColorGradient& gradient)
: mesh_(mesh), gradient_(gradient), height_(12), minHeight_(0)
{
}
// Sets height of wall.
inline LowPolyWallBuilder& setHeight(double height) { height_ = height; return *this; }
// Sets height above ground level.
inline LowPolyWallBuilder& setMinHeight(double minHeight) { minHeight_ = minHeight; return *this; }
void build(const utymap::GeoCoordinate& start, const utymap::GeoCoordinate& end)
{
addPlane(start, end);
}
private:
void addPlane(const utymap::GeoCoordinate& p1, const utymap::GeoCoordinate& p2)
{
double top = minHeight_ + height_;
int color = 0, index = mesh_.triangles.size();
// first triangle
addVertex(p1, minHeight_, index++, color);
addVertex(p2, minHeight_, index++, color);
addVertex(p2, top, index++, color);
// second triangle
addVertex(p2, minHeight_, index++, color);
addVertex(p2, top, index++, color);
addVertex(p1, top, index, color);
}
inline void addVertex(const utymap::GeoCoordinate& coordinate, double height, int triIndex, int color)
{
mesh_.vertices.push_back(coordinate.longitude);
mesh_.vertices.push_back(coordinate.latitude);
mesh_.vertices.push_back(height);
mesh_.triangles.push_back(triIndex);
mesh_.colors.push_back(color);
}
const utymap::meshing::Mesh& mesh_;
const utymap::mapcss::ColorGradient& gradient_;
double height_, minHeight_;
};
}}
#endif // SCENE_BUILDINGS_FACADES_LOWPOLYWALLBUILDER_HPP_DEFINED
<|endoftext|> |
<commit_before>/*
* Moon++ Scripts for Ascent MMORPG Server
* Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Setup.h"
class CassaCrimsonwing_Gossip : public Arcemu::Gossip::Script
{
public:
void OnHello(Object* pObject, Player* plr)
{
GossipMenu* Menu;
objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 11224, plr);
Arcemu::Gossip::Menu menu(pObject->GetGUID(), 11224);
if(plr->GetQuestLogForEntry(11142) != NULL)
menu.AddItem(Arcemu::Gossip::ICON_CHAT, "Lady Jaina told me to speak to you about using a gryphon to survey Alcaz Island.", 1);
menu.Send(plr);
}
void OnSelectOption(Object* pObject, Player* plr, uint32 Id, const char* Code)
{
plr->GetQuestLogForEntry(11142)->SendQuestComplete();
plr->TaxiStart(sTaxiMgr.GetTaxiPath(724), 1147, 0); // Gryph
}
void Destroy() { delete this; }
};
class CaptainGarranVimes_Gossip : public Arcemu::Gossip::Script
{
public:
void OnHello(Object* pObject, Player* plr)
{
Arcemu::Gossip::Menu::SendQuickMenu(pObject->GetGUID(), 1793, plr, 1, Arcemu::Gossip::ICON_CHAT, "What have you heard of the Shady Rest Inn?");
}
void GossipSelectOption(Object* pObject, Player* plr, uint32 Id, uint32 IntId, const char* Code)
{
Arcemu::Gossip::Menu::SendSimpleMenu(pObject->GetGUID(), 1794, plr);
}
void Destroy() { delete this; }
};
void SetupTheramoreGossip(ScriptMgr* mgr)
{
mgr->register_creature_gossip(23704, new CassaCrimsonwing_Gossip); // Cassa Crimsonwing
mgr->register_creature_gossip(4944, new CaptainGarranVimes_Gossip); // Captain Garran Vimes
}
<commit_msg>Quests that require action with "Captain Garran Vimes" in Theramore do not work as the custom gossip handler does not return the quests for this NPC. Fixed.<commit_after>/*
* Moon++ Scripts for Ascent MMORPG Server
* Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Setup.h"
class CassaCrimsonwing_Gossip : public Arcemu::Gossip::Script
{
public:
void OnHello(Object* pObject, Player* plr)
{
GossipMenu* Menu;
objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 11224, plr);
Arcemu::Gossip::Menu menu(pObject->GetGUID(), 11224);
if(plr->GetQuestLogForEntry(11142) != NULL)
menu.AddItem(Arcemu::Gossip::ICON_CHAT, "Lady Jaina told me to speak to you about using a gryphon to survey Alcaz Island.", 1);
menu.Send(plr);
}
void OnSelectOption(Object* pObject, Player* plr, uint32 Id, const char* Code)
{
plr->GetQuestLogForEntry(11142)->SendQuestComplete();
plr->TaxiStart(sTaxiMgr.GetTaxiPath(724), 1147, 0); // Gryph
}
void Destroy() { delete this; }
};
class CaptainGarranVimes_Gossip : public Arcemu::Gossip::Script
{
public:
void OnHello(Object* pObject, Player* plr)
{
//Send quests and gossip menu.
uint32 Text = objmgr.GetGossipTextForNpc(pObject->GetEntry());
if(NpcTextStorage.LookupEntry(Text) == NULL)
Text = Arcemu::Gossip::DEFAULT_TXTINDEX;
Arcemu::Gossip::Menu menu(pObject->GetGUID(), Text, plr->GetSession()->language);
sQuestMgr.FillQuestMenu(TO_CREATURE(pObject), plr, menu);
if((plr->GetQuestLogForEntry(11123) != NULL) || (plr->GetQuestRewardStatus(11123) == 0))
menu.AddItem(Arcemu::Gossip::ICON_CHAT, "What have you heard of the Shady Rest Inn?", 1794);
menu.Send(plr);
}
void OnSelectOption(Object* pObject, Player* plr, uint32 Id, const char* Code)
{
Arcemu::Gossip::Menu::SendSimpleMenu(pObject->GetGUID(), 1794, plr);
}
void Destroy() { delete this; }
};
void SetupTheramoreGossip(ScriptMgr* mgr)
{
mgr->register_creature_gossip(23704, new CassaCrimsonwing_Gossip); // Cassa Crimsonwing
mgr->register_creature_gossip(4944, new CaptainGarranVimes_Gossip); // Captain Garran Vimes
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Heiko Strathmann
*/
#include <shogun/base/init.h>
#include <shogun/statistics/LinearTimeMMD.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/mathematics/Statistics.h>
using namespace shogun;
void create_mean_data(SGMatrix<float64_t> target, float64_t difference)
{
/* create data matrix for P and Q. P is a standard normal, Q is the same but
* has a mean difference in one dimension */
for (index_t i=0; i<target.num_rows; ++i)
{
for (index_t j=0; j<target.num_cols/2; ++j)
target(i,j)=CMath::randn_double();
/* add mean difference in first dimension of second half of data */
for (index_t j=target.num_cols/2; j<target.num_cols; ++j)
target(i,j)=CMath::randn_double() + (i==0 ? difference : 0);
}
}
/** tests the linear mmd statistic for a single data case and ensures
* equality with matlab implementation */
void test_linear_mmd_fixed()
{
index_t m=2;
index_t d=3;
float64_t sigma=2;
float64_t sq_sigma_twice=sigma*sigma*2;
SGMatrix<float64_t> data(d,2*m);
for (index_t i=0; i<2*d*m; ++i)
data.matrix[i]=i;
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
/* shoguns kernel width is different */
CGaussianKernel* kernel=new CGaussianKernel(10, sq_sigma_twice);
kernel->init(features, features);
CLinearTimeMMD* mmd=new CLinearTimeMMD(kernel, features, m);
/* assert matlab result */
float64_t difference=mmd->compute_statistic()-0.034218118311602;
ASSERT(CMath::abs(difference)<10E-16);
SG_UNREF(mmd);
}
/** tests the linear mmd statistic for a random data case (fixed distribution
* and ensures equality with matlab implementation */
void test_linear_mmd_random()
{
index_t dimension=3;
index_t m=10000;
float64_t difference=0.5;
float64_t sigma=2;
index_t num_runs=100;
SGVector<float64_t> mmds(num_runs);
SGMatrix<float64_t> data(dimension, 2*m);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
/* shoguns kernel width is different */
CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
CLinearTimeMMD* mmd=new CLinearTimeMMD(kernel, features, m);
for (index_t i=0; i<num_runs; ++i)
{
create_mean_data(data, difference);
mmds[i]=mmd->compute_statistic();
}
float64_t mean=CStatistics::mean(mmds);
float64_t var=CStatistics::variance(mmds);
/* MATLAB 100-run 3 sigma interval for mean is
* [ 0.006291248839741, 0.039143028479036] */
ASSERT(mean>0.006291248839741);
ASSERT(mean<0.039143028479036);
/* MATLAB 100-run variance is 2.997887292969012e-05 quite stable */
ASSERT(CMath::abs(var-2.997887292969012e-05)<10E-5);
SG_UNREF(mmd);
}
void test_linear_mmd_variance_estimate()
{
index_t dimension=3;
index_t m=10000;
float64_t difference=0.5;
float64_t sigma=2;
index_t num_runs=100;
SGVector<float64_t> vars(num_runs);
SGMatrix<float64_t> data(dimension, 2*m);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
/* shoguns kernel width is different */
CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
CLinearTimeMMD* mmd=new CLinearTimeMMD(kernel, features, m);
for (index_t i=0; i<num_runs; ++i)
{
create_mean_data(data, difference);
vars[i]=mmd->compute_variance_estimate();
}
float64_t mean=CStatistics::mean(vars);
float64_t var=CStatistics::variance(vars);
/* MATLAB 100-run 3 sigma interval for mean is
* [2.487949168976897e-05, 2.816652377191562e-05] */
ASSERT(mean>2.487949168976897e-05);
ASSERT(mean<2.816652377191562e-05);
/* MATLAB 100-run variance is 8.321246145460274e-06 quite stable */
ASSERT(CMath::abs(var- 8.321246145460274e-06)<10E-6);
SG_UNREF(mmd);
}
void test_linear_mmd_variance_estimate_vs_bootstrap()
{
index_t dimension=3;
index_t m=50000;
float64_t difference=0.5;
float64_t sigma=2;
SGMatrix<float64_t> data(dimension, 2*m);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
create_mean_data(data, difference);
/* shoguns kernel width is different */
CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
CLinearTimeMMD* mmd=new CLinearTimeMMD(kernel, features, m);
SGVector<float64_t> null_samples=mmd->bootstrap_null();
float64_t bootstrap_variance=CStatistics::variance(null_samples);
float64_t estimated_variance=mmd->compute_variance_estimate();
float64_t statistic=mmd->compute_statistic();
float64_t variance_error=CMath::abs(bootstrap_variance-estimated_variance);
/* assert that variances error is less than 10E-5 of statistic */
SG_SPRINT("null distribution variance: %f\n", bootstrap_variance);
SG_SPRINT("estimated variance: %f\n", estimated_variance);
SG_SPRINT("linear mmd itself: %f\n", statistic);
SG_SPRINT("variance error: %f\n", variance_error);
SG_SPRINT("error/statistic: %f\n", variance_error/statistic);
ASSERT(variance_error/statistic<10E-5);
SG_UNREF(mmd);
}
void test_linear_mmd_type2_error()
{
index_t dimension=3;
index_t m=10000;
float64_t difference=0.4;
float64_t sigma=2;
index_t num_runs=500;
index_t num_errors=0;
SGMatrix<float64_t> data(dimension, 2*m);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
/* shoguns kernel width is different */
CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
CLinearTimeMMD* mmd=new CLinearTimeMMD(kernel, features, m);
mmd->set_null_approximation_method(MMD1_GAUSSIAN);
for (index_t i=0; i<num_runs; ++i)
{
create_mean_data(data, difference);
float64_t statistic=mmd->compute_statistic();
float64_t p_value_est=mmd->compute_p_value(statistic);
/* lets allow a 5% type 1 error */
num_errors+=p_value_est<0.05 ? 0 : 1;
}
float64_t type_2_error=(float64_t)num_errors/(float64_t)num_runs;
SG_SPRINT("type2 error est: %f\n", type_2_error);
/* for 100 MATLAB runs, 3*sigma error range lies in
* [0.024568646859226, 0.222231353140774] */
ASSERT(type_2_error>0.024568646859226);
ASSERT(type_2_error<0.222231353140774);
SG_UNREF(mmd);
}
int main(int argc, char** argv)
{
init_shogun_with_defaults();
test_linear_mmd_fixed();
test_linear_mmd_random();
test_linear_mmd_variance_estimate();
test_linear_mmd_variance_estimate_vs_bootstrap();
test_linear_mmd_type2_error();
exit_shogun();
return 0;
}
<commit_msg>added a little comment to avoid confusion<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Heiko Strathmann
*/
#include <shogun/base/init.h>
#include <shogun/statistics/LinearTimeMMD.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/mathematics/Statistics.h>
using namespace shogun;
void create_mean_data(SGMatrix<float64_t> target, float64_t difference)
{
/* create data matrix for P and Q. P is a standard normal, Q is the same but
* has a mean difference in one dimension */
for (index_t i=0; i<target.num_rows; ++i)
{
for (index_t j=0; j<target.num_cols/2; ++j)
target(i,j)=CMath::randn_double();
/* add mean difference in first dimension of second half of data */
for (index_t j=target.num_cols/2; j<target.num_cols; ++j)
target(i,j)=CMath::randn_double() + (i==0 ? difference : 0);
}
}
/** tests the linear mmd statistic for a single data case and ensures
* equality with matlab implementation */
void test_linear_mmd_fixed()
{
index_t m=2;
index_t d=3;
float64_t sigma=2;
float64_t sq_sigma_twice=sigma*sigma*2;
SGMatrix<float64_t> data(d,2*m);
for (index_t i=0; i<2*d*m; ++i)
data.matrix[i]=i;
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
/* shoguns kernel width is different */
CGaussianKernel* kernel=new CGaussianKernel(10, sq_sigma_twice);
kernel->init(features, features);
CLinearTimeMMD* mmd=new CLinearTimeMMD(kernel, features, m);
/* assert matlab result */
float64_t difference=mmd->compute_statistic()-0.034218118311602;
ASSERT(CMath::abs(difference)<10E-16);
SG_UNREF(mmd);
}
/** tests the linear mmd statistic for a random data case (fixed distribution
* and ensures equality with matlab implementation */
void test_linear_mmd_random()
{
index_t dimension=3;
index_t m=10000;
float64_t difference=0.5;
float64_t sigma=2;
index_t num_runs=100;
SGVector<float64_t> mmds(num_runs);
SGMatrix<float64_t> data(dimension, 2*m);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
/* shoguns kernel width is different */
CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
CLinearTimeMMD* mmd=new CLinearTimeMMD(kernel, features, m);
for (index_t i=0; i<num_runs; ++i)
{
create_mean_data(data, difference);
mmds[i]=mmd->compute_statistic();
}
float64_t mean=CStatistics::mean(mmds);
float64_t var=CStatistics::variance(mmds);
/* MATLAB 100-run 3 sigma interval for mean is
* [ 0.006291248839741, 0.039143028479036] */
ASSERT(mean>0.006291248839741);
ASSERT(mean<0.039143028479036);
/* MATLAB 100-run variance is 2.997887292969012e-05 quite stable */
ASSERT(CMath::abs(var-2.997887292969012e-05)<10E-5);
SG_UNREF(mmd);
}
void test_linear_mmd_variance_estimate()
{
index_t dimension=3;
index_t m=10000;
float64_t difference=0.5;
float64_t sigma=2;
index_t num_runs=100;
SGVector<float64_t> vars(num_runs);
SGMatrix<float64_t> data(dimension, 2*m);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
/* shoguns kernel width is different */
CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
CLinearTimeMMD* mmd=new CLinearTimeMMD(kernel, features, m);
for (index_t i=0; i<num_runs; ++i)
{
create_mean_data(data, difference);
vars[i]=mmd->compute_variance_estimate();
}
float64_t mean=CStatistics::mean(vars);
float64_t var=CStatistics::variance(vars);
/* MATLAB 100-run 3 sigma interval for mean is
* [2.487949168976897e-05, 2.816652377191562e-05] */
ASSERT(mean>2.487949168976897e-05);
ASSERT(mean<2.816652377191562e-05);
/* MATLAB 100-run variance is 8.321246145460274e-06 quite stable */
ASSERT(CMath::abs(var- 8.321246145460274e-06)<10E-6);
SG_UNREF(mmd);
}
void test_linear_mmd_variance_estimate_vs_bootstrap()
{
index_t dimension=3;
index_t m=50000;
float64_t difference=0.5;
float64_t sigma=2;
SGMatrix<float64_t> data(dimension, 2*m);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
create_mean_data(data, difference);
/* shoguns kernel width is different */
CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
CLinearTimeMMD* mmd=new CLinearTimeMMD(kernel, features, m);
SGVector<float64_t> null_samples=mmd->bootstrap_null();
float64_t bootstrap_variance=CStatistics::variance(null_samples);
float64_t estimated_variance=mmd->compute_variance_estimate();
float64_t statistic=mmd->compute_statistic();
float64_t variance_error=CMath::abs(bootstrap_variance-estimated_variance);
/* assert that variances error is less than 10E-5 of statistic */
SG_SPRINT("null distribution variance: %f\n", bootstrap_variance);
SG_SPRINT("estimated variance: %f\n", estimated_variance);
SG_SPRINT("linear mmd itself: %f\n", statistic);
SG_SPRINT("variance error: %f\n", variance_error);
SG_SPRINT("error/statistic: %f\n", variance_error/statistic);
ASSERT(variance_error/statistic<10E-5);
SG_UNREF(mmd);
}
void test_linear_mmd_type2_error()
{
index_t dimension=3;
index_t m=10000;
float64_t difference=0.4;
float64_t sigma=2;
index_t num_runs=500;
index_t num_errors=0;
SGMatrix<float64_t> data(dimension, 2*m);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
/* shoguns kernel width is different */
CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
CLinearTimeMMD* mmd=new CLinearTimeMMD(kernel, features, m);
mmd->set_null_approximation_method(MMD1_GAUSSIAN);
for (index_t i=0; i<num_runs; ++i)
{
create_mean_data(data, difference);
/* technically, this leads to a wrong result since training (statistic)
* and testing (p-value) have to happen on different data, but this
* is only to compare against MATLAB, where I did the same "mistake"
* See for example python_modular example how to do this correct */
float64_t statistic=mmd->compute_statistic();
float64_t p_value_est=mmd->compute_p_value(statistic);
/* lets allow a 5% type 1 error */
num_errors+=p_value_est<0.05 ? 0 : 1;
}
float64_t type_2_error=(float64_t)num_errors/(float64_t)num_runs;
SG_SPRINT("type2 error est: %f\n", type_2_error);
/* for 100 MATLAB runs, 3*sigma error range lies in
* [0.024568646859226, 0.222231353140774] */
ASSERT(type_2_error>0.024568646859226);
ASSERT(type_2_error<0.222231353140774);
SG_UNREF(mmd);
}
int main(int argc, char** argv)
{
init_shogun_with_defaults();
test_linear_mmd_fixed();
test_linear_mmd_random();
test_linear_mmd_variance_estimate();
test_linear_mmd_variance_estimate_vs_bootstrap();
test_linear_mmd_type2_error();
exit_shogun();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_CORE_NAIVE_PAIR_CALCULATION
#define MJOLNIR_CORE_NAIVE_PAIR_CALCULATION
#include "System.hpp"
namespace mjolnir
{
template<typename traitsT>
class NaivePairCalculation
{
public:
typedef traitsT traits_type;
typedef System<traits_type> system_type;
typedef typename traits_type::boundary_type boundary_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef std::vector<std::size_t> index_array;
typedef std::vector<index_array> partners_type;
struct information
{
information() : chain_idx(std::numeric_limits<std::size_t>::max()){}
std::size_t chain_idx;
index_array except_chains;
index_array except_indices;
};
typedef std::vector<information> particle_info_type;
public:
NaivePairCalculation(): dirty_(true){};
~NaivePairCalculation() = default;
NaivePairCalculation(NaivePairCalculation&&) = default;
NaivePairCalculation& operator=(NaivePairCalculation&&) = default;
bool valid() const noexcept override {return true;}
std::size_t& chain_index (std::size_t i);
index_array& except_indices(std::size_t i);
index_array& except_chains (std::size_t i);
void make (const system_type& sys);
void update(const system_type& sys) noexcept {return;}
void update(const system_type& sys, const real_type dt) noexcept {return;}
index_array const& partners(std::size_t i) const noexcept {return list_[i];}
private:
partners_type partners_;
particle_info_type informations_;
};
template<typename traitsT>
std::size_t& NaivePairCalculation<traitsT>::chain_index(std::size_t i)
{
if(this->informations_.size() <= i)
this->informations_.resize(i+1);
return this->informations_.at(i).chain_idx;
}
template<typename traitsT>
typename NaivePairCalculation<traitsT>::index_array&
NaivePairCalculation<traitsT>::except_indices(std::size_t i)
{
if(this->informations_.size() <= i)
this->informations_.resize(i+1);
return this->informations_.at(i).except_indices;
}
template<typename traitsT>
typename NaivePairCalculation<traitsT>::index_array&
NaivePairCalculation<traitsT>::except_chains(std::size_t i)
{
if(this->informations_.size() <= i)
this->informations_.resize(i+1);
return this->informations_.at(i).except_chains;
}
template<typename traitsT>
void NaivePairCalculation<traitsT>::make(const system_type& sys)
{
this->partners_.resize(sys.size());
for(auto& partner : this->partners) partner.clear();
if(informations_.size() < sys.size())
informations_.resize(sys.size());
for(std::size_t i=0, sz = sys.size()-1; i < sz; ++i)
{
const auto& info = informations_.at(i);
const auto index_begin = info.except_indices.cbegin();
const auto index_end = info.except_indices.cend();
const auto chain_begin = info.except_chains.cbegin();
const auto chain_end = info.except_chains.cend();
for(std::size_t j=i+1; j<sys.size(); ++j)
{
const std::size_t j_chain = informations_.at(j).chain_idx;
if(std::find(chain_begin, chain_end, j_chain) != chain_end) continue;
if(std::find(index_begin, index_end, j) != index_end) continue;
this->partners_.at(i).push_back(j);
}
}
return;
}
} // mjolnir
#endif /*MJOLNIR_CORE_NAIVE_PAIR_CALCULATION*/
<commit_msg>remove needless override<commit_after>#ifndef MJOLNIR_CORE_NAIVE_PAIR_CALCULATION
#define MJOLNIR_CORE_NAIVE_PAIR_CALCULATION
#include "System.hpp"
namespace mjolnir
{
template<typename traitsT>
class NaivePairCalculation
{
public:
typedef traitsT traits_type;
typedef System<traits_type> system_type;
typedef typename traits_type::boundary_type boundary_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef std::vector<std::size_t> index_array;
typedef std::vector<index_array> partners_type;
struct information
{
information() : chain_idx(std::numeric_limits<std::size_t>::max()){}
std::size_t chain_idx;
index_array except_chains;
index_array except_indices;
};
typedef std::vector<information> particle_info_type;
public:
NaivePairCalculation(): dirty_(true){};
~NaivePairCalculation() = default;
NaivePairCalculation(NaivePairCalculation&&) = default;
NaivePairCalculation& operator=(NaivePairCalculation&&) = default;
bool valid() const noexcept {return true;}
std::size_t& chain_index (std::size_t i);
index_array& except_indices(std::size_t i);
index_array& except_chains (std::size_t i);
void make (const system_type& sys);
void update(const system_type& sys) noexcept {return;}
void update(const system_type& sys, const real_type dt) noexcept {return;}
index_array const& partners(std::size_t i) const noexcept {return list_[i];}
private:
partners_type partners_;
particle_info_type informations_;
};
template<typename traitsT>
std::size_t& NaivePairCalculation<traitsT>::chain_index(std::size_t i)
{
if(this->informations_.size() <= i)
this->informations_.resize(i+1);
return this->informations_.at(i).chain_idx;
}
template<typename traitsT>
typename NaivePairCalculation<traitsT>::index_array&
NaivePairCalculation<traitsT>::except_indices(std::size_t i)
{
if(this->informations_.size() <= i)
this->informations_.resize(i+1);
return this->informations_.at(i).except_indices;
}
template<typename traitsT>
typename NaivePairCalculation<traitsT>::index_array&
NaivePairCalculation<traitsT>::except_chains(std::size_t i)
{
if(this->informations_.size() <= i)
this->informations_.resize(i+1);
return this->informations_.at(i).except_chains;
}
template<typename traitsT>
void NaivePairCalculation<traitsT>::make(const system_type& sys)
{
this->partners_.resize(sys.size());
for(auto& partner : this->partners) partner.clear();
if(informations_.size() < sys.size())
informations_.resize(sys.size());
for(std::size_t i=0, sz = sys.size()-1; i < sz; ++i)
{
const auto& info = informations_.at(i);
const auto index_begin = info.except_indices.cbegin();
const auto index_end = info.except_indices.cend();
const auto chain_begin = info.except_chains.cbegin();
const auto chain_end = info.except_chains.cend();
for(std::size_t j=i+1; j<sys.size(); ++j)
{
const std::size_t j_chain = informations_.at(j).chain_idx;
if(std::find(chain_begin, chain_end, j_chain) != chain_end) continue;
if(std::find(index_begin, index_end, j) != index_end) continue;
this->partners_.at(i).push_back(j);
}
}
return;
}
} // mjolnir
#endif /*MJOLNIR_CORE_NAIVE_PAIR_CALCULATION*/
<|endoftext|> |
<commit_before>// Copyright 2014 Toggl Desktop developers.
#include "./mainwindowcontroller.h"
#include "./ui_mainwindowcontroller.h"
#include <iostream> // NOLINT
#include <QAction> // NOLINT
#include <QCloseEvent> // NOLINT
#include <QtConcurrent/QtConcurrent> // NOLINT
#include <QDebug> // NOLINT
#include <QDesktopServices> // NOLINT
#include <QImageReader> // NOLINT
#include <QLabel> // NOLINT
#include <QMenu> // NOLINT
#include <QMessageBox> // NOLINT
#include <QSettings> // NOLINT
#include <QVBoxLayout> // NOLINT
#include <QStatusBar> // NOLINT
#include "./toggl.h"
#include "./errorviewcontroller.h"
#include "./loginwidget.h"
#include "./timeentrylistwidget.h"
#include "./timeentryeditorwidget.h"
MainWindowController::MainWindowController(
QWidget *parent,
QString logPathOverride,
QString dbPathOverride,
QString scriptPath)
: QMainWindow(parent),
ui(new Ui::MainWindowController),
togglApi(new TogglApi(0, logPathOverride, dbPathOverride)),
tracking(false),
loggedIn(false),
actionEmail(0),
actionNew(0),
actionContinue(0),
actionStop(0),
actionSync(0),
actionLogout(0),
actionClear_Cache(0),
actionSend_Feedback(0),
actionReports(0),
preferencesDialog(new PreferencesDialog(this)),
aboutDialog(new AboutDialog(this)),
feedbackDialog(new FeedbackDialog(this)),
idleNotificationDialog(new IdleNotificationDialog(this)),
trayIcon(0),
reminder(false),
script(scriptPath),
ui_started(false) {
TogglApi::instance->setEnvironment(APP_ENVIRONMENT);
ui->setupUi(this);
ui->menuBar->setVisible(true);
QVBoxLayout *verticalLayout = new QVBoxLayout();
verticalLayout->addWidget(new ErrorViewController());
verticalLayout->addWidget(new LoginWidget());
verticalLayout->addWidget(new TimeEntryListWidget());
verticalLayout->addWidget(new TimeEntryEditorWidget());
verticalLayout->setContentsMargins(0, 0, 0, 0);
verticalLayout->setSpacing(0);
centralWidget()->setLayout(verticalLayout);
readSettings();
connect(TogglApi::instance, SIGNAL(displayApp(bool)), // NOLINT
this, SLOT(displayApp(bool))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayStoppedTimerState()), // NOLINT
this, SLOT(displayStoppedTimerState())); // NOLINT
connect(TogglApi::instance, SIGNAL(displayRunningTimerState(TimeEntryView*)), // NOLINT
this, SLOT(displayRunningTimerState(TimeEntryView*))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayLogin(bool,uint64_t)), // NOLINT
this, SLOT(displayLogin(bool,uint64_t))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayReminder(QString,QString)), // NOLINT
this, SLOT(displayReminder(QString,QString))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayUpdate(QString)), // NOLINT
this, SLOT(displayUpdate(QString))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayOnlineState(int64_t)), // NOLINT
this, SLOT(displayOnlineState(int64_t))); // NOLINT
hasTrayIconCached = hasTrayIcon();
if (hasTrayIconCached) {
icon.addFile(QString::fromUtf8(":/icons/1024x1024/toggldesktop.png"));
iconDisabled.addFile(QString::fromUtf8(
":/icons/1024x1024/toggldesktop_gray.png"));
trayIcon = new QSystemTrayIcon(this);
}
connectMenuActions();
enableMenuActions();
if (hasTrayIconCached) {
// icon is set in enableMenuActions based on if tracking is in progress
trayIcon->show();
} else {
setWindowIcon(icon);
}
}
MainWindowController::~MainWindowController() {
delete togglApi;
togglApi = 0;
delete ui;
}
void MainWindowController::displayOnlineState(
int64_t state) {
switch (state) {
case 0: // online
statusBar()->clearMessage();
break;
case 1: // no network
statusBar()->showMessage("Status: Offline, no network");
break;
case 2: // backend down
statusBar()->showMessage("Status: Offline, Toggl not responding");
break;
default:
qDebug() << "Unknown online state " << state;
break;
}
}
void MainWindowController::displayReminder(
const QString title,
const QString informative_text) {
if (reminder) {
return;
}
reminder = true;
QMessageBox(
QMessageBox::Information,
title,
informative_text,
QMessageBox::Ok).exec();
reminder = false;
}
void MainWindowController::displayLogin(
const bool open,
const uint64_t user_id) {
loggedIn = !open && user_id;
enableMenuActions();
}
void MainWindowController::displayRunningTimerState(
TimeEntryView *te) {
tracking = true;
enableMenuActions();
}
void MainWindowController::displayStoppedTimerState() {
tracking = false;
enableMenuActions();
}
void MainWindowController::enableMenuActions() {
actionNew->setEnabled(loggedIn);
actionContinue->setEnabled(loggedIn && !tracking);
actionStop->setEnabled(loggedIn && tracking);
actionSync->setEnabled(loggedIn);
actionLogout->setEnabled(loggedIn);
actionClear_Cache->setEnabled(loggedIn);
actionSend_Feedback->setEnabled(loggedIn);
actionReports->setEnabled(loggedIn);
actionEmail->setText(TogglApi::instance->userEmail());
if (hasTrayIconCached) {
if (tracking) {
trayIcon->setIcon(icon);
setWindowIcon(icon);
} else {
trayIcon->setIcon(iconDisabled);
setWindowIcon(iconDisabled);
}
}
}
void MainWindowController::connectMenuActions() {
foreach(QMenu *menu, ui->menuBar->findChildren<QMenu *>()) {
if (trayIcon) {
trayIcon->setContextMenu(menu);
}
foreach(QAction *action, menu->actions()) {
connectMenuAction(action);
}
}
}
void MainWindowController::connectMenuAction(
QAction *action) {
if ("actionEmail" == action->objectName()) {
actionEmail = action;
} else if ("actionNew" == action->objectName()) {
actionNew = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionNew()));
} else if ("actionContinue" == action->objectName()) {
actionContinue = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionContinue()));
} else if ("actionStop" == action->objectName()) {
actionStop = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionStop()));
} else if ("actionSync" == action->objectName()) {
actionSync = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionSync()));
} else if ("actionLogout" == action->objectName()) {
actionLogout = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionLogout()));
} else if ("actionClear_Cache" == action->objectName()) {
actionClear_Cache = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionClear_Cache()));
} else if ("actionSend_Feedback" == action->objectName()) {
actionSend_Feedback = action;
connect(action, SIGNAL(triggered()),
this, SLOT(onActionSend_Feedback()));
} else if ("actionReports" == action->objectName()) {
actionReports = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionReports()));
} else if ("actionShow" == action->objectName()) {
connect(action, SIGNAL(triggered()), this, SLOT(onActionShow()));
} else if ("actionPreferences" == action->objectName()) {
connect(action, SIGNAL(triggered()), this, SLOT(onActionPreferences()));
} else if ("actionAbout" == action->objectName()) {
connect(action, SIGNAL(triggered()), this, SLOT(onActionAbout()));
} else if ("actionQuit" == action->objectName()) {
connect(action, SIGNAL(triggered()), this, SLOT(onActionQuit()));
} else if ("actionHelp" == action->objectName()) {
connect(action, SIGNAL(triggered()), this, SLOT(onActionHelp()));
}
}
void MainWindowController::onActionNew() {
TogglApi::instance->start("", "", 0, 0);
}
void MainWindowController::onActionContinue() {
TogglApi::instance->continueLatestTimeEntry();
}
void MainWindowController::onActionStop() {
TogglApi::instance->stop();
}
void MainWindowController::onActionShow() {
displayApp(true);
}
void MainWindowController::onActionSync() {
TogglApi::instance->sync();
}
void MainWindowController::onActionReports() {
TogglApi::instance->openInBrowser();
}
void MainWindowController::onActionPreferences() {
TogglApi::instance->editPreferences();
}
void MainWindowController::onActionAbout() {
aboutDialog->show();
}
void MainWindowController::onActionSend_Feedback() {
feedbackDialog->show();
}
void MainWindowController::onActionLogout() {
TogglApi::instance->logout();
}
void MainWindowController::onActionQuit() {
quitApp();
}
void MainWindowController::quitApp() {
TogglApi::instance->shutdown = true;
qApp->exit(0);
}
void MainWindowController::onActionClear_Cache() {
if (QMessageBox::Ok == QMessageBox(
QMessageBox::Question,
"Clear Cache?",
"Clearing cache will delete any unsaved time entries and log you out.",
QMessageBox::Ok|QMessageBox::Cancel).exec()) {
TogglApi::instance->clearCache();
}
}
void MainWindowController::onActionHelp() {
TogglApi::instance->getSupport();
}
void MainWindowController::displayApp(const bool open) {
if (open) {
show();
raise();
}
}
void MainWindowController::readSettings() {
QSettings settings("Toggl", "TogglDesktop");
restoreGeometry(settings.value("geometry").toByteArray());
restoreState(settings.value("windowState").toByteArray());
}
void MainWindowController::writeSettings() {
QSettings settings("Toggl", "TogglDesktop");
settings.setValue("geometry", saveGeometry());
settings.setValue("windowState", saveState());
}
void MainWindowController::closeEvent(QCloseEvent *event) {
QMessageBox::StandardButton dialog;
dialog = QMessageBox::question(this,
"Toggl Desktop",
"Really quit the app?",
QMessageBox::Ok | QMessageBox::Cancel);
if (QMessageBox::Ok == dialog) {
writeSettings();
close();
} else {
event->ignore();
return;
}
QMainWindow::closeEvent(event);
}
bool MainWindowController::hasTrayIcon() const {
QString currentDesktop = QProcessEnvironment::systemEnvironment().value(
"XDG_CURRENT_DESKTOP", "");
return "Unity" != currentDesktop;
}
void MainWindowController::showEvent(QShowEvent *event) {
QMainWindow::showEvent(event);
// Avoid 'user already logged in' error from double UI start
if (ui_started) {
return;
}
ui_started = true;
if (!TogglApi::instance->startEvents()) {
QMessageBox(
QMessageBox::Warning,
"Error",
"The application could not start. Please inspect the log file.",
QMessageBox::Ok|QMessageBox::Cancel).exec();
return;
}
if (script.isEmpty()) {
qDebug() << "no script to run";
return;
}
qDebug() << "will run script: " << script;
QtConcurrent::run(this, &MainWindowController::runScript);
}
void MainWindowController::displayUpdate(const QString url) {
if (aboutDialog->isVisible()
|| url.isEmpty()) {
return;
}
if (QMessageBox::Yes == QMessageBox(
QMessageBox::Question,
"Download new version?",
"A new version of Toggl Desktop is available. Continue with download?",
QMessageBox::No|QMessageBox::Yes).exec()) {
QDesktopServices::openUrl(QUrl(url));
quitApp();
}
}
void MainWindowController::runScript() {
if (TogglApi::instance->runScriptFile(script)) {
quitApp();
}
}
<commit_msg>Raise window on duplicate app run (linux)<commit_after>// Copyright 2014 Toggl Desktop developers.
#include "./mainwindowcontroller.h"
#include "./ui_mainwindowcontroller.h"
#include <iostream> // NOLINT
#include <QAction> // NOLINT
#include <QCloseEvent> // NOLINT
#include <QtConcurrent/QtConcurrent> // NOLINT
#include <QDebug> // NOLINT
#include <QDesktopServices> // NOLINT
#include <QImageReader> // NOLINT
#include <QLabel> // NOLINT
#include <QMenu> // NOLINT
#include <QMessageBox> // NOLINT
#include <QSettings> // NOLINT
#include <QVBoxLayout> // NOLINT
#include <QStatusBar> // NOLINT
#include "./toggl.h"
#include "./errorviewcontroller.h"
#include "./loginwidget.h"
#include "./timeentrylistwidget.h"
#include "./timeentryeditorwidget.h"
MainWindowController::MainWindowController(
QWidget *parent,
QString logPathOverride,
QString dbPathOverride,
QString scriptPath)
: QMainWindow(parent),
ui(new Ui::MainWindowController),
togglApi(new TogglApi(0, logPathOverride, dbPathOverride)),
tracking(false),
loggedIn(false),
actionEmail(0),
actionNew(0),
actionContinue(0),
actionStop(0),
actionSync(0),
actionLogout(0),
actionClear_Cache(0),
actionSend_Feedback(0),
actionReports(0),
preferencesDialog(new PreferencesDialog(this)),
aboutDialog(new AboutDialog(this)),
feedbackDialog(new FeedbackDialog(this)),
idleNotificationDialog(new IdleNotificationDialog(this)),
trayIcon(0),
reminder(false),
script(scriptPath),
ui_started(false) {
TogglApi::instance->setEnvironment(APP_ENVIRONMENT);
ui->setupUi(this);
ui->menuBar->setVisible(true);
QVBoxLayout *verticalLayout = new QVBoxLayout();
verticalLayout->addWidget(new ErrorViewController());
verticalLayout->addWidget(new LoginWidget());
verticalLayout->addWidget(new TimeEntryListWidget());
verticalLayout->addWidget(new TimeEntryEditorWidget());
verticalLayout->setContentsMargins(0, 0, 0, 0);
verticalLayout->setSpacing(0);
centralWidget()->setLayout(verticalLayout);
readSettings();
connect(QApplication::instance(), SIGNAL(showUp()),
this, SLOT(raise()));
connect(TogglApi::instance, SIGNAL(displayApp(bool)), // NOLINT
this, SLOT(displayApp(bool))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayStoppedTimerState()), // NOLINT
this, SLOT(displayStoppedTimerState())); // NOLINT
connect(TogglApi::instance, SIGNAL(displayRunningTimerState(TimeEntryView*)), // NOLINT
this, SLOT(displayRunningTimerState(TimeEntryView*))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayLogin(bool,uint64_t)), // NOLINT
this, SLOT(displayLogin(bool,uint64_t))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayReminder(QString,QString)), // NOLINT
this, SLOT(displayReminder(QString,QString))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayUpdate(QString)), // NOLINT
this, SLOT(displayUpdate(QString))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayOnlineState(int64_t)), // NOLINT
this, SLOT(displayOnlineState(int64_t))); // NOLINT
hasTrayIconCached = hasTrayIcon();
if (hasTrayIconCached) {
icon.addFile(QString::fromUtf8(":/icons/1024x1024/toggldesktop.png"));
iconDisabled.addFile(QString::fromUtf8(
":/icons/1024x1024/toggldesktop_gray.png"));
trayIcon = new QSystemTrayIcon(this);
}
connectMenuActions();
enableMenuActions();
if (hasTrayIconCached) {
// icon is set in enableMenuActions based on if tracking is in progress
trayIcon->show();
} else {
setWindowIcon(icon);
}
}
MainWindowController::~MainWindowController() {
delete togglApi;
togglApi = 0;
delete ui;
}
void MainWindowController::displayOnlineState(
int64_t state) {
switch (state) {
case 0: // online
statusBar()->clearMessage();
break;
case 1: // no network
statusBar()->showMessage("Status: Offline, no network");
break;
case 2: // backend down
statusBar()->showMessage("Status: Offline, Toggl not responding");
break;
default:
qDebug() << "Unknown online state " << state;
break;
}
}
void MainWindowController::displayReminder(
const QString title,
const QString informative_text) {
if (reminder) {
return;
}
reminder = true;
QMessageBox(
QMessageBox::Information,
title,
informative_text,
QMessageBox::Ok).exec();
reminder = false;
}
void MainWindowController::displayLogin(
const bool open,
const uint64_t user_id) {
loggedIn = !open && user_id;
enableMenuActions();
}
void MainWindowController::displayRunningTimerState(
TimeEntryView *te) {
tracking = true;
enableMenuActions();
}
void MainWindowController::displayStoppedTimerState() {
tracking = false;
enableMenuActions();
}
void MainWindowController::enableMenuActions() {
actionNew->setEnabled(loggedIn);
actionContinue->setEnabled(loggedIn && !tracking);
actionStop->setEnabled(loggedIn && tracking);
actionSync->setEnabled(loggedIn);
actionLogout->setEnabled(loggedIn);
actionClear_Cache->setEnabled(loggedIn);
actionSend_Feedback->setEnabled(loggedIn);
actionReports->setEnabled(loggedIn);
actionEmail->setText(TogglApi::instance->userEmail());
if (hasTrayIconCached) {
if (tracking) {
trayIcon->setIcon(icon);
setWindowIcon(icon);
} else {
trayIcon->setIcon(iconDisabled);
setWindowIcon(iconDisabled);
}
}
}
void MainWindowController::connectMenuActions() {
foreach(QMenu *menu, ui->menuBar->findChildren<QMenu *>()) {
if (trayIcon) {
trayIcon->setContextMenu(menu);
}
foreach(QAction *action, menu->actions()) {
connectMenuAction(action);
}
}
}
void MainWindowController::connectMenuAction(
QAction *action) {
if ("actionEmail" == action->objectName()) {
actionEmail = action;
} else if ("actionNew" == action->objectName()) {
actionNew = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionNew()));
} else if ("actionContinue" == action->objectName()) {
actionContinue = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionContinue()));
} else if ("actionStop" == action->objectName()) {
actionStop = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionStop()));
} else if ("actionSync" == action->objectName()) {
actionSync = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionSync()));
} else if ("actionLogout" == action->objectName()) {
actionLogout = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionLogout()));
} else if ("actionClear_Cache" == action->objectName()) {
actionClear_Cache = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionClear_Cache()));
} else if ("actionSend_Feedback" == action->objectName()) {
actionSend_Feedback = action;
connect(action, SIGNAL(triggered()),
this, SLOT(onActionSend_Feedback()));
} else if ("actionReports" == action->objectName()) {
actionReports = action;
connect(action, SIGNAL(triggered()), this, SLOT(onActionReports()));
} else if ("actionShow" == action->objectName()) {
connect(action, SIGNAL(triggered()), this, SLOT(onActionShow()));
} else if ("actionPreferences" == action->objectName()) {
connect(action, SIGNAL(triggered()), this, SLOT(onActionPreferences()));
} else if ("actionAbout" == action->objectName()) {
connect(action, SIGNAL(triggered()), this, SLOT(onActionAbout()));
} else if ("actionQuit" == action->objectName()) {
connect(action, SIGNAL(triggered()), this, SLOT(onActionQuit()));
} else if ("actionHelp" == action->objectName()) {
connect(action, SIGNAL(triggered()), this, SLOT(onActionHelp()));
}
}
void MainWindowController::onActionNew() {
TogglApi::instance->start("", "", 0, 0);
}
void MainWindowController::onActionContinue() {
TogglApi::instance->continueLatestTimeEntry();
}
void MainWindowController::onActionStop() {
TogglApi::instance->stop();
}
void MainWindowController::onActionShow() {
displayApp(true);
}
void MainWindowController::onActionSync() {
TogglApi::instance->sync();
}
void MainWindowController::onActionReports() {
TogglApi::instance->openInBrowser();
}
void MainWindowController::onActionPreferences() {
TogglApi::instance->editPreferences();
}
void MainWindowController::onActionAbout() {
aboutDialog->show();
}
void MainWindowController::onActionSend_Feedback() {
feedbackDialog->show();
}
void MainWindowController::onActionLogout() {
TogglApi::instance->logout();
}
void MainWindowController::onActionQuit() {
quitApp();
}
void MainWindowController::quitApp() {
TogglApi::instance->shutdown = true;
qApp->exit(0);
}
void MainWindowController::onActionClear_Cache() {
if (QMessageBox::Ok == QMessageBox(
QMessageBox::Question,
"Clear Cache?",
"Clearing cache will delete any unsaved time entries and log you out.",
QMessageBox::Ok|QMessageBox::Cancel).exec()) {
TogglApi::instance->clearCache();
}
}
void MainWindowController::onActionHelp() {
TogglApi::instance->getSupport();
}
void MainWindowController::displayApp(const bool open) {
if (open) {
show();
raise();
}
}
void MainWindowController::readSettings() {
QSettings settings("Toggl", "TogglDesktop");
restoreGeometry(settings.value("geometry").toByteArray());
restoreState(settings.value("windowState").toByteArray());
}
void MainWindowController::writeSettings() {
QSettings settings("Toggl", "TogglDesktop");
settings.setValue("geometry", saveGeometry());
settings.setValue("windowState", saveState());
}
void MainWindowController::closeEvent(QCloseEvent *event) {
QMessageBox::StandardButton dialog;
dialog = QMessageBox::question(this,
"Toggl Desktop",
"Really quit the app?",
QMessageBox::Ok | QMessageBox::Cancel);
if (QMessageBox::Ok == dialog) {
writeSettings();
close();
} else {
event->ignore();
return;
}
QMainWindow::closeEvent(event);
}
bool MainWindowController::hasTrayIcon() const {
QString currentDesktop = QProcessEnvironment::systemEnvironment().value(
"XDG_CURRENT_DESKTOP", "");
return "Unity" != currentDesktop;
}
void MainWindowController::showEvent(QShowEvent *event) {
QMainWindow::showEvent(event);
// Avoid 'user already logged in' error from double UI start
if (ui_started) {
return;
}
ui_started = true;
if (!TogglApi::instance->startEvents()) {
QMessageBox(
QMessageBox::Warning,
"Error",
"The application could not start. Please inspect the log file.",
QMessageBox::Ok|QMessageBox::Cancel).exec();
return;
}
if (script.isEmpty()) {
qDebug() << "no script to run";
return;
}
qDebug() << "will run script: " << script;
QtConcurrent::run(this, &MainWindowController::runScript);
}
void MainWindowController::displayUpdate(const QString url) {
if (aboutDialog->isVisible()
|| url.isEmpty()) {
return;
}
if (QMessageBox::Yes == QMessageBox(
QMessageBox::Question,
"Download new version?",
"A new version of Toggl Desktop is available. Continue with download?",
QMessageBox::No|QMessageBox::Yes).exec()) {
QDesktopServices::openUrl(QUrl(url));
quitApp();
}
}
void MainWindowController::runScript() {
if (TogglApi::instance->runScriptFile(script)) {
quitApp();
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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 "XSLTProcessorEnvSupportDefault.hpp"
#include <algorithm>
#include <xercesc/sax/EntityResolver.hpp>
#include <xercesc/util/XMLURL.hpp>
#include <xalanc/Include/STLHelper.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/URISupport.hpp>
#include <xalanc/XPath/ElementPrefixResolverProxy.hpp>
#include <xalanc/XPath/XPathExecutionContext.hpp>
#include <xalanc/XMLSupport/XMLParserLiaison.hpp>
#include "KeyTable.hpp"
#include "StylesheetRoot.hpp"
#include "XSLTProcessor.hpp"
#include "XSLTInputSource.hpp"
XALAN_CPP_NAMESPACE_BEGIN
XSLTProcessorEnvSupportDefault::XSLTProcessorEnvSupportDefault(
MemoryManagerType& theManager,
XSLTProcessor* theProcessor) :
XSLTProcessorEnvSupport(),
m_defaultSupport(theManager),
m_processor(theProcessor)
{
}
XSLTProcessorEnvSupportDefault::~XSLTProcessorEnvSupportDefault()
{
reset();
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
XPathEnvSupportDefault::installExternalFunctionGlobal(theNamespace, functionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
XPathEnvSupportDefault::uninstallExternalFunctionGlobal(theNamespace, functionName);
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
m_defaultSupport.installExternalFunctionLocal(theNamespace, functionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
m_defaultSupport.uninstallExternalFunctionLocal(theNamespace, functionName);
}
void
XSLTProcessorEnvSupportDefault::reset()
{
m_defaultSupport.reset();
}
XalanDocument*
XSLTProcessorEnvSupportDefault::parseXML(
MemoryManagerType& theManager,
const XalanDOMString& urlString,
const XalanDOMString& base)
{
if (m_processor == 0)
{
return m_defaultSupport.parseXML(theManager, urlString, base);
}
else
{
typedef URISupport::URLAutoPtrType URLAutoPtrType;
// $$$ ToDo: we should re-work this code to only use
// XMLRUL when necessary.
const URLAutoPtrType xslURL =
URISupport::getURLFromString(urlString, base, theManager);
const XalanDOMString urlText(xslURL->getURLText(), theManager);
// First see if it's already been parsed...
XalanDocument* theDocument =
getSourceDocument(urlText);
if (theDocument == 0)
{
XMLParserLiaison& parserLiaison =
m_processor->getXMLParserLiaison();
EntityResolverType* const theResolver =
parserLiaison.getEntityResolver();
XalanDOMString theEmptyString(theManager);
if (theResolver == 0)
{
const XSLTInputSource inputSource(c_wstr(urlText), theManager);
theDocument = parserLiaison.parseXMLStream(inputSource, theEmptyString);
}
else
{
typedef XalanMemMgrAutoPtr<InputSourceType, true> AutoPtr;
const AutoPtr resolverInputSource(theManager,
theResolver->resolveEntity(0, c_wstr(urlText)));
if (resolverInputSource.get() != 0)
{
theDocument = parserLiaison.parseXMLStream(*resolverInputSource.get(), theEmptyString);
}
else
{
const XSLTInputSource inputSource(c_wstr(urlText), theManager);
theDocument = parserLiaison.parseXMLStream(inputSource, theEmptyString);
}
}
if (theDocument != 0)
{
setSourceDocument(urlText, theDocument);
}
}
return theDocument;
}
}
XalanDocument*
XSLTProcessorEnvSupportDefault::getSourceDocument(const XalanDOMString& theURI) const
{
return m_defaultSupport.getSourceDocument(theURI);
}
void
XSLTProcessorEnvSupportDefault::setSourceDocument(
const XalanDOMString& theURI,
XalanDocument* theDocument)
{
m_defaultSupport.setSourceDocument(theURI, theDocument);
}
const XalanDOMString&
XSLTProcessorEnvSupportDefault::findURIFromDoc(const XalanDocument* owner) const
{
return m_defaultSupport.findURIFromDoc(owner);
}
bool
XSLTProcessorEnvSupportDefault::elementAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
return m_defaultSupport.elementAvailable(theNamespace,
functionName);
}
bool
XSLTProcessorEnvSupportDefault::functionAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
return m_defaultSupport.functionAvailable(theNamespace,
functionName);
}
XObjectPtr
XSLTProcessorEnvSupportDefault::extFunction(
XPathExecutionContext& executionContext,
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
XalanNode* context,
const XObjectArgVectorType& argVec,
const LocatorType* locator) const
{
return m_defaultSupport.extFunction(
executionContext,
theNamespace,
functionName,
context,
argVec,
locator);
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource /* where */,
eClassification classification,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode,
const XalanDOMString& msg,
const XalanDOMChar* /* uri */,
int /* lineNo */,
int /* charOffset */) const
{
if (classification == XPathEnvSupport::eError)
{
m_processor->error(
msg,
sourceNode,
styleNode);
return true;
}
else if (classification == XPathEnvSupport::eWarning)
{
m_processor->warn(
msg,
sourceNode,
styleNode);
return false;
}
else
{
m_processor->message(
msg,
sourceNode,
styleNode);
return false;
}
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource /* where */,
eClassification classification,
const PrefixResolver* /* resolver */,
const XalanNode* sourceNode,
const XalanDOMString& msg,
const XalanDOMChar* /* uri */,
int /* lineNo */,
int /* charOffset */) const
{
if (classification == XPathEnvSupport::eError)
{
m_processor->error(
msg,
sourceNode);
return true;
}
else if (classification == XPathEnvSupport::eWarning)
{
m_processor->warn(
msg,
sourceNode);
return false;
}
else
{
m_processor->message(
msg,
sourceNode);
return false;
}
}
XALAN_CPP_NAMESPACE_END
<commit_msg>Further fix for XALANC-455.<commit_after>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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 "XSLTProcessorEnvSupportDefault.hpp"
#include <algorithm>
#include <xercesc/sax/EntityResolver.hpp>
#include <xercesc/util/XMLURL.hpp>
#include <xalanc/Include/STLHelper.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/URISupport.hpp>
#include <xalanc/XPath/ElementPrefixResolverProxy.hpp>
#include <xalanc/XPath/XPathExecutionContext.hpp>
#include <xalanc/XMLSupport/XMLParserLiaison.hpp>
#include "KeyTable.hpp"
#include "StylesheetRoot.hpp"
#include "XSLTProcessor.hpp"
#include "XSLTInputSource.hpp"
XALAN_CPP_NAMESPACE_BEGIN
XSLTProcessorEnvSupportDefault::XSLTProcessorEnvSupportDefault(
MemoryManagerType& theManager,
XSLTProcessor* theProcessor) :
XSLTProcessorEnvSupport(),
m_defaultSupport(theManager),
m_processor(theProcessor)
{
}
XSLTProcessorEnvSupportDefault::~XSLTProcessorEnvSupportDefault()
{
reset();
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
XPathEnvSupportDefault::installExternalFunctionGlobal(theNamespace, functionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
XPathEnvSupportDefault::uninstallExternalFunctionGlobal(theNamespace, functionName);
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
m_defaultSupport.installExternalFunctionLocal(theNamespace, functionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
m_defaultSupport.uninstallExternalFunctionLocal(theNamespace, functionName);
}
void
XSLTProcessorEnvSupportDefault::reset()
{
m_defaultSupport.reset();
}
XalanDocument*
XSLTProcessorEnvSupportDefault::parseXML(
MemoryManagerType& theManager,
const XalanDOMString& urlString,
const XalanDOMString& base)
{
if (m_processor == 0)
{
return m_defaultSupport.parseXML(theManager, urlString, base);
}
else
{
typedef URISupport::URLAutoPtrType URLAutoPtrType;
// $$$ ToDo: we should re-work this code to only use
// XMLRUL when necessary.
const URLAutoPtrType xslURL =
URISupport::getURLFromString(urlString, base, theManager);
const XalanDOMString urlText(xslURL->getURLText(), theManager);
// First see if it's already been parsed...
XalanDocument* theDocument =
getSourceDocument(urlText);
if (theDocument == 0)
{
XMLParserLiaison& parserLiaison =
m_processor->getXMLParserLiaison();
EntityResolverType* const theResolver =
parserLiaison.getEntityResolver();
const XalanDOMString theEmptyString(theManager);
if (theResolver == 0)
{
const XSLTInputSource inputSource(urlText.c_str(), theManager);
theDocument = parserLiaison.parseXMLStream(inputSource, theEmptyString);
}
else
{
XALAN_USING_XERCES(InputSource)
typedef XalanAutoPtr<InputSource> AutoPtrType;
const AutoPtrType resolverInputSource(
theResolver->resolveEntity(
0,
urlText.c_str()));
if (resolverInputSource.get() != 0)
{
theDocument = parserLiaison.parseXMLStream(*resolverInputSource.get(), theEmptyString);
}
else
{
const XSLTInputSource inputSource(urlText.c_str(), theManager);
theDocument = parserLiaison.parseXMLStream(inputSource, theEmptyString);
}
}
if (theDocument != 0)
{
setSourceDocument(urlText, theDocument);
}
}
return theDocument;
}
}
XalanDocument*
XSLTProcessorEnvSupportDefault::getSourceDocument(const XalanDOMString& theURI) const
{
return m_defaultSupport.getSourceDocument(theURI);
}
void
XSLTProcessorEnvSupportDefault::setSourceDocument(
const XalanDOMString& theURI,
XalanDocument* theDocument)
{
m_defaultSupport.setSourceDocument(theURI, theDocument);
}
const XalanDOMString&
XSLTProcessorEnvSupportDefault::findURIFromDoc(const XalanDocument* owner) const
{
return m_defaultSupport.findURIFromDoc(owner);
}
bool
XSLTProcessorEnvSupportDefault::elementAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
return m_defaultSupport.elementAvailable(theNamespace,
functionName);
}
bool
XSLTProcessorEnvSupportDefault::functionAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
return m_defaultSupport.functionAvailable(theNamespace,
functionName);
}
XObjectPtr
XSLTProcessorEnvSupportDefault::extFunction(
XPathExecutionContext& executionContext,
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
XalanNode* context,
const XObjectArgVectorType& argVec,
const LocatorType* locator) const
{
return m_defaultSupport.extFunction(
executionContext,
theNamespace,
functionName,
context,
argVec,
locator);
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource /* where */,
eClassification classification,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode,
const XalanDOMString& msg,
const XalanDOMChar* /* uri */,
int /* lineNo */,
int /* charOffset */) const
{
if (classification == XPathEnvSupport::eError)
{
m_processor->error(
msg,
sourceNode,
styleNode);
return true;
}
else if (classification == XPathEnvSupport::eWarning)
{
m_processor->warn(
msg,
sourceNode,
styleNode);
return false;
}
else
{
m_processor->message(
msg,
sourceNode,
styleNode);
return false;
}
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource /* where */,
eClassification classification,
const PrefixResolver* /* resolver */,
const XalanNode* sourceNode,
const XalanDOMString& msg,
const XalanDOMChar* /* uri */,
int /* lineNo */,
int /* charOffset */) const
{
if (classification == XPathEnvSupport::eError)
{
m_processor->error(
msg,
sourceNode);
return true;
}
else if (classification == XPathEnvSupport::eWarning)
{
m_processor->warn(
msg,
sourceNode);
return false;
}
else
{
m_processor->message(
msg,
sourceNode);
return false;
}
}
XALAN_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if TENSORFLOW_USE_SYCL
#include "tensorflow/core/common_runtime/sycl/sycl_device.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor.pb_text.h"
#include "tensorflow/core/platform/tracing.h"
namespace tensorflow {
static std::unordered_set<SYCLDevice*> live_devices;
static bool first_time = true;
void ShutdownSycl() {
for (auto device : live_devices) {
device->EnterLameDuckMode();
}
live_devices.clear();
}
void SYCLDevice::RegisterDevice() {
if (first_time) {
first_time = false;
atexit(ShutdownSycl);
}
live_devices.insert(this);
}
SYCLDevice::~SYCLDevice() {
device_context_->Unref();
sycl_allocator_->EnterLameDuckMode();
delete sycl_device_;
delete sycl_queue_;
live_devices.erase(this);
}
void SYCLDevice::EnterLameDuckMode() {
sycl_allocator_->EnterLameDuckMode();
delete sycl_device_;
sycl_device_ = nullptr;
delete sycl_queue_;
sycl_queue_ = nullptr;
}
void SYCLDevice::Compute(OpKernel *op_kernel, OpKernelContext *context) {
assert(context);
if (port::Tracing::IsActive()) {
// TODO(pbar) We really need a useful identifier of the graph node.
const uint64 id = Hash64(op_kernel->name());
port::Tracing::ScopedActivity region(port::Tracing::EventCategory::kCompute,
id);
}
op_kernel->Compute(context);
}
Allocator *SYCLDevice::GetAllocator(AllocatorAttributes attr) {
if (attr.on_host())
return cpu_allocator_;
else
return sycl_allocator_;
}
Status SYCLDevice::MakeTensorFromProto(const TensorProto &tensor_proto,
const AllocatorAttributes alloc_attrs,
Tensor *tensor) {
Tensor parsed(tensor_proto.dtype());
if (!parsed.FromProto(cpu_allocator_, tensor_proto)) {
return errors::InvalidArgument("Cannot parse tensor from proto: ",
tensor_proto.DebugString());
}
Status status;
if (alloc_attrs.on_host()) {
*tensor = parsed;
} else {
Tensor copy(GetAllocator(alloc_attrs), parsed.dtype(), parsed.shape());
device_context_->CopyCPUTensorToDevice(&parsed, this, ©,
[&status](const Status &s) {
status = s;
});
*tensor = copy;
}
return status;
}
Status SYCLDevice::FillContextMap(const Graph *graph,
DeviceContextMap *device_context_map) {
// Fill in the context map. It is OK for this map to contain
// duplicate DeviceContexts so long as we increment the refcount.
device_context_map->resize(graph->num_node_ids());
for (Node *n : graph->nodes()) {
device_context_->Ref();
(*device_context_map)[n->id()] = device_context_;
}
return Status::OK();
}
Status SYCLDevice::Sync() {
sycl_device_->synchronize();
return Status::OK();
}
} // namespace tensorflow
#endif // TENSORFLOW_USE_SYCL
<commit_msg>Synchronize the SYCL device before deleting it, to make sure the command queue is empty.<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if TENSORFLOW_USE_SYCL
#include "tensorflow/core/common_runtime/sycl/sycl_device.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor.pb_text.h"
#include "tensorflow/core/platform/tracing.h"
namespace tensorflow {
static std::unordered_set<SYCLDevice*> live_devices;
static bool first_time = true;
void ShutdownSycl() {
for (auto device : live_devices) {
device->EnterLameDuckMode();
}
live_devices.clear();
}
void SYCLDevice::RegisterDevice() {
if (first_time) {
first_time = false;
atexit(ShutdownSycl);
}
live_devices.insert(this);
}
SYCLDevice::~SYCLDevice() {
device_context_->Unref();
sycl_allocator_->EnterLameDuckMode();
if (sycl_device_) {
sycl_device_->synchronize();
delete sycl_device_;
}
if (sycl_queue_) {
delete sycl_queue_;
}
live_devices.erase(this);
}
void SYCLDevice::EnterLameDuckMode() {
sycl_allocator_->EnterLameDuckMode();
if (sycl_device_) {
sycl_device_->synchronize();
delete sycl_device_;
sycl_device_ = nullptr;
}
if (sycl_queue_) {
delete sycl_queue_;
sycl_queue_ = nullptr;
}
}
void SYCLDevice::Compute(OpKernel *op_kernel, OpKernelContext *context) {
assert(context);
if (port::Tracing::IsActive()) {
// TODO(pbar) We really need a useful identifier of the graph node.
const uint64 id = Hash64(op_kernel->name());
port::Tracing::ScopedActivity region(port::Tracing::EventCategory::kCompute,
id);
}
op_kernel->Compute(context);
}
Allocator *SYCLDevice::GetAllocator(AllocatorAttributes attr) {
if (attr.on_host())
return cpu_allocator_;
else
return sycl_allocator_;
}
Status SYCLDevice::MakeTensorFromProto(const TensorProto &tensor_proto,
const AllocatorAttributes alloc_attrs,
Tensor *tensor) {
Tensor parsed(tensor_proto.dtype());
if (!parsed.FromProto(cpu_allocator_, tensor_proto)) {
return errors::InvalidArgument("Cannot parse tensor from proto: ",
tensor_proto.DebugString());
}
Status status;
if (alloc_attrs.on_host()) {
*tensor = parsed;
} else {
Tensor copy(GetAllocator(alloc_attrs), parsed.dtype(), parsed.shape());
device_context_->CopyCPUTensorToDevice(&parsed, this, ©,
[&status](const Status &s) {
status = s;
});
*tensor = copy;
}
return status;
}
Status SYCLDevice::FillContextMap(const Graph *graph,
DeviceContextMap *device_context_map) {
// Fill in the context map. It is OK for this map to contain
// duplicate DeviceContexts so long as we increment the refcount.
device_context_map->resize(graph->num_node_ids());
for (Node *n : graph->nodes()) {
device_context_->Ref();
(*device_context_map)[n->id()] = device_context_;
}
return Status::OK();
}
Status SYCLDevice::Sync() {
sycl_device_->synchronize();
return Status::OK();
}
} // namespace tensorflow
#endif // TENSORFLOW_USE_SYCL
<|endoftext|> |
<commit_before>/*
* Advent of Code 2016
* Day 7 (part 1)
*
* Command: clang++ --std=c++14 day07a.cpp
*
*/
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
const string INPUT_FILE = "input07.txt";
const int MAX_LINE_LENGTH = 2000;
int main(void) {
// Open the input file
ifstream fin(INPUT_FILE);
if (!fin) {
cerr << "Error reading input file " << INPUT_FILE << endl;
return -1;
}
// Read the input
vector<string> input;
char cInput[MAX_LINE_LENGTH];
while (fin.getline(cInput, MAX_LINE_LENGTH)) {
input.push_back(string(cInput));
}
fin.close();
// Solve the problem
int count = 0;
for (auto line : input) {
int end = line.length() - 3;
bool inside = false;
bool abba = false;
for (int i = 0; i < end; i++) {
// Check to see if we've entered/ended a hypernet sequence
if (line.at(i) == '[') {
inside = true;
continue;
} else if (line.at(i) == ']') {
inside = false;
continue;
}
// Look for an ABBA
if (line.at(i) == line.at(i + 3)) {
if (line.at(i + 1) == line.at(i + 2)) {
if (line.at(i) != line.at(i + 1)) {
abba = true;
if (inside) {
break;
}
}
}
}
}
if (abba && !inside) {
count++;
}
}
cout << "Count: " << count << endl;
return 0;
}
<commit_msg>Remove unused header<commit_after>/*
* Advent of Code 2016
* Day 7 (part 1)
*
* Command: clang++ --std=c++14 day07a.cpp
*
*/
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const string INPUT_FILE = "input07.txt";
const int MAX_LINE_LENGTH = 2000;
int main(void) {
// Open the input file
ifstream fin(INPUT_FILE);
if (!fin) {
cerr << "Error reading input file " << INPUT_FILE << endl;
return -1;
}
// Read the input
vector<string> input;
char cInput[MAX_LINE_LENGTH];
while (fin.getline(cInput, MAX_LINE_LENGTH)) {
input.push_back(string(cInput));
}
fin.close();
// Solve the problem
int count = 0;
for (auto line : input) {
int end = line.length() - 3;
bool inside = false;
bool abba = false;
for (int i = 0; i < end; i++) {
// Check to see if we've entered/ended a hypernet sequence
if (line.at(i) == '[') {
inside = true;
continue;
} else if (line.at(i) == ']') {
inside = false;
continue;
}
// Look for an ABBA
if (line.at(i) == line.at(i + 3)) {
if (line.at(i + 1) == line.at(i + 2)) {
if (line.at(i) != line.at(i + 1)) {
abba = true;
if (inside) {
break;
}
}
}
}
}
if (abba && !inside) {
count++;
}
}
cout << "Count: " << count << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* input_slider.hpp : VolumeSlider and SeekSlider
****************************************************************************
* Copyright (C) 2006-2011 the VideoLAN team
* $Id$
*
* Authors: Clément Stenac <[email protected]>
* Jean-Baptiste Kempf <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef _INPUTSLIDER_H_
#define _INPUTSLIDER_H_
#include <QSlider>
#define MSTRTIME_MAX_SIZE 22
class QMouseEvent;
class QWheelEvent;
class QTimer;
/* Input Slider derived from QSlider */
class SeekSlider : public QSlider
{
Q_OBJECT
public:
SeekSlider( QWidget *_parent );
SeekSlider( Qt::Orientation q, QWidget *_parent );
protected:
virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mousePressEvent(QMouseEvent* event);
virtual void mouseReleaseEvent(QMouseEvent* event);
virtual void wheelEvent(QWheelEvent *event);
virtual void paintEvent( QPaintEvent* event );
QSize handleSize() const;
QSize sizeHint() const;
private:
bool b_isSliding; /* Whether we are currently sliding by user action */
int inputLength; /* InputLength that can change */
char psz_length[MSTRTIME_MAX_SIZE]; /* Used for the ToolTip */
QTimer *seekLimitTimer;
public slots:
void setPosition( float, int64_t, int );
private slots:
void startSeekTimer( int );
void updatePos();
signals:
void sliderDragged( float );
};
/* Sound Slider inherited directly from QAbstractSlider */
class QPaintEvent;
class SoundSlider : public QAbstractSlider
{
Q_OBJECT
public:
SoundSlider( QWidget *_parent, int _i_step, bool b_softamp, char * );
void setMuted( bool ); /* Set Mute status */
protected:
const static int paddingL = 3;
const static int paddingR = 2;
virtual void paintEvent(QPaintEvent *);
virtual void wheelEvent( QWheelEvent *event );
virtual void mousePressEvent( QMouseEvent * );
virtual void mouseMoveEvent( QMouseEvent * );
virtual void mouseReleaseEvent( QMouseEvent * );
private:
bool b_isSliding; /* Whether we are currently sliding by user action */
bool b_mouseOutside; /* Whether the mouse is outside or inside the Widget */
int i_oldvalue; /* Store the old Value before changing */
float f_step; /* How much do we increase each time we wheel */
bool b_isMuted;
QPixmap pixGradient; /* Gradient pix storage */
QPixmap pixGradient2; /* Muted Gradient pix storage */
QPixmap pixOutside; /* OutLine pix storage */
void changeValue( int x ); /* Function to modify the value from pixel x() */
};
#endif
<commit_msg>Qt: fix win32 compilation<commit_after>/*****************************************************************************
* input_slider.hpp : VolumeSlider and SeekSlider
****************************************************************************
* Copyright (C) 2006-2011 the VideoLAN team
* $Id$
*
* Authors: Clément Stenac <[email protected]>
* Jean-Baptiste Kempf <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef _INPUTSLIDER_H_
#define _INPUTSLIDER_H_
#include <QSlider>
#include <vlc_common.h>
#define MSTRTIME_MAX_SIZE 22
class QMouseEvent;
class QWheelEvent;
class QTimer;
/* Input Slider derived from QSlider */
class SeekSlider : public QSlider
{
Q_OBJECT
public:
SeekSlider( QWidget *_parent );
SeekSlider( Qt::Orientation q, QWidget *_parent );
protected:
virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mousePressEvent(QMouseEvent* event);
virtual void mouseReleaseEvent(QMouseEvent* event);
virtual void wheelEvent(QWheelEvent *event);
virtual void paintEvent( QPaintEvent* event );
QSize handleSize() const;
QSize sizeHint() const;
private:
bool b_isSliding; /* Whether we are currently sliding by user action */
int inputLength; /* InputLength that can change */
char psz_length[MSTRTIME_MAX_SIZE]; /* Used for the ToolTip */
QTimer *seekLimitTimer;
public slots:
void setPosition( float, int64_t, int );
private slots:
void startSeekTimer( int );
void updatePos();
signals:
void sliderDragged( float );
};
/* Sound Slider inherited directly from QAbstractSlider */
class QPaintEvent;
class SoundSlider : public QAbstractSlider
{
Q_OBJECT
public:
SoundSlider( QWidget *_parent, int _i_step, bool b_softamp, char * );
void setMuted( bool ); /* Set Mute status */
protected:
const static int paddingL = 3;
const static int paddingR = 2;
virtual void paintEvent(QPaintEvent *);
virtual void wheelEvent( QWheelEvent *event );
virtual void mousePressEvent( QMouseEvent * );
virtual void mouseMoveEvent( QMouseEvent * );
virtual void mouseReleaseEvent( QMouseEvent * );
private:
bool b_isSliding; /* Whether we are currently sliding by user action */
bool b_mouseOutside; /* Whether the mouse is outside or inside the Widget */
int i_oldvalue; /* Store the old Value before changing */
float f_step; /* How much do we increase each time we wheel */
bool b_isMuted;
QPixmap pixGradient; /* Gradient pix storage */
QPixmap pixGradient2; /* Muted Gradient pix storage */
QPixmap pixOutside; /* OutLine pix storage */
void changeValue( int x ); /* Function to modify the value from pixel x() */
};
#endif
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QPixmapCache>
//TESTED_FILES=
class tst_QPixmapCache : public QObject
{
Q_OBJECT
public:
tst_QPixmapCache();
virtual ~tst_QPixmapCache();
public slots:
void init();
void cleanup();
private slots:
void insert_data();
void insert();
void find_data();
void find();
void styleUseCaseComplexKey();
void styleUseCaseComplexKey_data();
};
tst_QPixmapCache::tst_QPixmapCache()
{
}
tst_QPixmapCache::~tst_QPixmapCache()
{
}
void tst_QPixmapCache::init()
{
}
void tst_QPixmapCache::cleanup()
{
}
void tst_QPixmapCache::insert_data()
{
QTest::addColumn<bool>("cacheType");
QTest::newRow("QPixmapCache") << true;
QTest::newRow("QPixmapCache (int API)") << false;
}
QList<QPixmapCache::Key> keys;
void tst_QPixmapCache::insert()
{
QFETCH(bool, cacheType);
QPixmap p;
if (cacheType) {
QBENCHMARK {
for (int i = 0 ; i <= 10000 ; i++)
{
QString tmp;
tmp.sprintf("my-key-%d", i);
QPixmapCache::insert(tmp, p);
}
}
} else {
QBENCHMARK {
for (int i = 0 ; i <= 10000 ; i++)
keys.append(QPixmapCache::insert(p));
}
}
}
void tst_QPixmapCache::find_data()
{
QTest::addColumn<bool>("cacheType");
QTest::newRow("QPixmapCache") << true;
QTest::newRow("QPixmapCache (int API)") << false;
}
void tst_QPixmapCache::find()
{
QFETCH(bool, cacheType);
QPixmap p;
if (cacheType) {
QBENCHMARK {
QString tmp;
for (int i = 0 ; i <= 10000 ; i++)
{
tmp.sprintf("my-key-%d", i);
QPixmapCache::find(tmp, p);
}
}
} else {
QBENCHMARK {
for (int i = 0 ; i <= 10000 ; i++)
QPixmapCache::find(keys.at(i), &p);
}
}
}
void tst_QPixmapCache::styleUseCaseComplexKey_data()
{
QTest::addColumn<bool>("cacheType");
QTest::newRow("QPixmapCache") << true;
QTest::newRow("QPixmapCache (int API)") << false;
}
struct styleStruct {
QString key;
uint state;
uint direction;
uint complex;
uint palette;
int width;
int height;
bool operator==(const styleStruct &str) const
{
return str.key == key && str.state == state && str.direction == direction
&& str.complex == complex && str.palette == palette && str.width == width
&& str.height == height;
}
};
uint qHash(const styleStruct &myStruct)
{
return qHash(myStruct.state);
}
void tst_QPixmapCache::styleUseCaseComplexKey()
{
QFETCH(bool, cacheType);
QPixmap p;
if (cacheType) {
QBENCHMARK {
for (int i = 0 ; i <= 10000 ; i++)
{
QString tmp;
tmp.sprintf("%s-%d-%d-%d-%d-%d-%d", QString("my-progressbar-%1").arg(i).toLatin1().constData(), 5, 3, 0, 358, 100, 200);
QPixmapCache::insert(tmp, p);
}
for (int i = 0 ; i <= 10000 ; i++)
{
QString tmp;
tmp.sprintf("%s-%d-%d-%d-%d-%d-%d", QString("my-progressbar-%1").arg(i).toLatin1().constData(), 5, 3, 0, 358, 100, 200);
QPixmapCache::find(tmp, p);
}
}
} else {
QHash<styleStruct, QPixmapCache::Key> hash;
QBENCHMARK {
for (int i = 0 ; i <= 10000 ; i++)
{
styleStruct myStruct;
myStruct.key = QString("my-progressbar-%1").arg(i);
myStruct.key = 5;
myStruct.key = 4;
myStruct.key = 3;
myStruct.palette = 358;
myStruct.width = 100;
myStruct.key = 200;
QPixmapCache::Key key = QPixmapCache::insert(p);
hash.insert(myStruct, key);
}
for (int i = 0 ; i <= 10000 ; i++)
{
styleStruct myStruct;
myStruct.key = QString("my-progressbar-%1").arg(i);
myStruct.key = 5;
myStruct.key = 4;
myStruct.key = 3;
myStruct.palette = 358;
myStruct.width = 100;
myStruct.key = 200;
QPixmapCache::Key key = hash.value(myStruct);
QPixmapCache::find(key, &p);
}
}
}
}
QTEST_MAIN(tst_QPixmapCache)
#include "tst_qpixmapcache.moc"
<commit_msg>Make the bench a bit faster.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QPixmapCache>
//TESTED_FILES=
class tst_QPixmapCache : public QObject
{
Q_OBJECT
public:
tst_QPixmapCache();
virtual ~tst_QPixmapCache();
public slots:
void init();
void cleanup();
private slots:
void insert_data();
void insert();
void find_data();
void find();
void styleUseCaseComplexKey();
void styleUseCaseComplexKey_data();
};
tst_QPixmapCache::tst_QPixmapCache()
{
}
tst_QPixmapCache::~tst_QPixmapCache()
{
}
void tst_QPixmapCache::init()
{
}
void tst_QPixmapCache::cleanup()
{
}
void tst_QPixmapCache::insert_data()
{
QTest::addColumn<bool>("cacheType");
QTest::newRow("QPixmapCache") << true;
QTest::newRow("QPixmapCache (int API)") << false;
}
QList<QPixmapCache::Key> keys;
void tst_QPixmapCache::insert()
{
QFETCH(bool, cacheType);
QPixmap p;
if (cacheType) {
QBENCHMARK {
for (int i = 0 ; i <= 10000 ; i++)
{
QString tmp;
tmp.sprintf("my-key-%d", i);
QPixmapCache::insert(tmp, p);
}
}
} else {
QBENCHMARK {
for (int i = 0 ; i <= 10000 ; i++)
keys.append(QPixmapCache::insert(p));
}
}
}
void tst_QPixmapCache::find_data()
{
QTest::addColumn<bool>("cacheType");
QTest::newRow("QPixmapCache") << true;
QTest::newRow("QPixmapCache (int API)") << false;
}
void tst_QPixmapCache::find()
{
QFETCH(bool, cacheType);
QPixmap p;
if (cacheType) {
QBENCHMARK {
QString tmp;
for (int i = 0 ; i <= 10000 ; i++)
{
tmp.sprintf("my-key-%d", i);
QPixmapCache::find(tmp, p);
}
}
} else {
QBENCHMARK {
for (int i = 0 ; i <= 10000 ; i++)
QPixmapCache::find(keys.at(i), &p);
}
}
}
void tst_QPixmapCache::styleUseCaseComplexKey_data()
{
QTest::addColumn<bool>("cacheType");
QTest::newRow("QPixmapCache") << true;
QTest::newRow("QPixmapCache (int API)") << false;
}
struct styleStruct {
QString key;
uint state;
uint direction;
uint complex;
uint palette;
int width;
int height;
bool operator==(const styleStruct &str) const
{
return str.state == state && str.direction == direction
&& str.complex == complex && str.palette == palette && str.width == width
&& str.height == height && str.key == key;
}
};
uint qHash(const styleStruct &myStruct)
{
return qHash(myStruct.state);
}
void tst_QPixmapCache::styleUseCaseComplexKey()
{
QFETCH(bool, cacheType);
QPixmap p;
if (cacheType) {
QBENCHMARK {
for (int i = 0 ; i <= 10000 ; i++)
{
QString tmp;
tmp.sprintf("%s-%d-%d-%d-%d-%d-%d", QString("my-progressbar-%1").arg(i).toLatin1().constData(), 5, 3, 0, 358, 100, 200);
QPixmapCache::insert(tmp, p);
}
for (int i = 0 ; i <= 10000 ; i++)
{
QString tmp;
tmp.sprintf("%s-%d-%d-%d-%d-%d-%d", QString("my-progressbar-%1").arg(i).toLatin1().constData(), 5, 3, 0, 358, 100, 200);
QPixmapCache::find(tmp, p);
}
}
} else {
QHash<styleStruct, QPixmapCache::Key> hash;
QBENCHMARK {
for (int i = 0 ; i <= 10000 ; i++)
{
styleStruct myStruct;
myStruct.key = QString("my-progressbar-%1").arg(i);
myStruct.key = 5;
myStruct.key = 4;
myStruct.key = 3;
myStruct.palette = 358;
myStruct.width = 100;
myStruct.key = 200;
QPixmapCache::Key key = QPixmapCache::insert(p);
hash.insert(myStruct, key);
}
for (int i = 0 ; i <= 10000 ; i++)
{
styleStruct myStruct;
myStruct.key = QString("my-progressbar-%1").arg(i);
myStruct.key = 5;
myStruct.key = 4;
myStruct.key = 3;
myStruct.palette = 358;
myStruct.width = 100;
myStruct.key = 200;
QPixmapCache::Key key = hash.value(myStruct);
QPixmapCache::find(key, &p);
}
}
}
}
QTEST_MAIN(tst_QPixmapCache)
#include "tst_qpixmapcache.moc"
<|endoftext|> |
<commit_before>// @(#)root/tmva/tmva/dnn:$Id$
// Author: Simon Pfreundschuh 20/07/16
/*************************************************************************
* Copyright (C) 2016, Simon Pfreundschuh *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
////////////////////////////////////////////////////////////
// Implementation of Helper arithmetic functions for the //
// multi-threaded CPU implementation of DNNs. //
////////////////////////////////////////////////////////////
#include "TMVA/DNN/Architectures/Cpu.h"
#ifdef R__HAS_TMVACPU
#include "TMVA/DNN/Architectures/Cpu/Blas.h"
#else
#include "TMVA/DNN/Architectures/Reference.h"
#endif
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
//#include "tbb/tbb.h"
#pragma GCC diagnostic pop
namespace TMVA
{
namespace DNN
{
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::Multiply(TCpuMatrix<AReal> &C,
const TCpuMatrix<AReal> &A,
const TCpuMatrix<AReal> &B)
{
int m = (int) A.GetNrows();
int k = (int) A.GetNcols();
int n = (int) B.GetNcols();
R__ASSERT((int) C.GetNrows() == m);
R__ASSERT((int) C.GetNcols() == n);
R__ASSERT((int) B.GetNrows() == k);
#ifdef R__HAS_TMVACPU
char transa = 'N';
char transb = 'N';
AReal alpha = 1.0;
AReal beta = 0.0;
const AReal * APointer = A.GetRawDataPointer();
const AReal * BPointer = B.GetRawDataPointer();
AReal * CPointer = C.GetRawDataPointer();
::TMVA::DNN::Blas::Gemm(&transa, &transb, &m, &n, &k, &alpha,
APointer, &m, BPointer, &k, &beta, CPointer, &m);
#else
TMatrixT<AReal> tmp(C.GetNrows(), C.GetNcols());
tmp.Mult(A,B);
C = tmp;
#endif
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::TransposeMultiply(TCpuMatrix<AReal> &C,
const TCpuMatrix<AReal> &A,
const TCpuMatrix<AReal> &B,
AReal alpha, AReal beta)
{
#ifdef R__HAS_TMVACPU
int m = (int) A.GetNcols();
int k = (int) A.GetNrows();
int n = (int) B.GetNcols();
R__ASSERT((int) C.GetNrows() == m);
R__ASSERT((int) C.GetNcols() == n);
R__ASSERT((int) B.GetNrows() == k);
char transa = 'T';
char transb = 'N';
//AReal alpha = 1.0;
//AReal beta = 0.0;
const AReal *APointer = A.GetRawDataPointer();
const AReal *BPointer = B.GetRawDataPointer();
AReal *CPointer = C.GetRawDataPointer();
::TMVA::DNN::Blas::Gemm(&transa, &transb, &m, &n, &k, &alpha,
APointer, &k, BPointer, &k, &beta, CPointer, &m);
#else
TMatrixT<AReal> tmp(C.GetNrows(), C.GetNcols());
tmp.TMult(A,B);
tmp = alpha*tmp + beta;
C = tmp;
#endif
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::Hadamard(TCpuMatrix<AReal> &B,
const TCpuMatrix<AReal> &A)
{
const AReal *dataA = A.GetRawDataPointer();
AReal *dataB = B.GetRawDataPointer();
size_t nElements = A.GetNoElements();
R__ASSERT(B.GetNoElements() == nElements);
size_t nSteps = TCpuMatrix<AReal>::GetNWorkItems(nElements);
auto f = [&](UInt_t workerID)
{
for (size_t j = 0; j < nSteps; ++j) {
size_t idx = workerID+j;
if (idx >= nElements) break;
dataB[idx] *= dataA[idx];
}
return 0;
};
if (nSteps < nElements) {
#ifdef DL_USE_MTE
B.GetThreadExecutor().Foreach(f, ROOT::TSeqI(0,nElements,nSteps));
#else
for (size_t i = 0; i < nElements ; i+= nSteps)
f(i);
#endif
}
else {
f(0);
}
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::Hadamard(TCpuTensor<AReal> &B,
const TCpuTensor<AReal> &A)
{
const AReal *dataA = A.GetRawDataPointer();
AReal *dataB = B.GetRawDataPointer();
size_t nElements = A.GetNoElements();
R__ASSERT(B.GetNoElements() == nElements);
size_t nSteps = TCpuMatrix<AReal>::GetNWorkItems(nElements);
auto f = [&](UInt_t workerID)
{
for (size_t j = 0; j < nSteps; ++j) {
size_t idx = workerID+j;
if (idx >= nElements) break;
dataB[idx] *= dataA[idx];
}
return 0;
};
if (nSteps < nElements) {
#ifdef DL_USE_MTE
TMVA::Config::Instance().GetThreadExecutor().Foreach(f, ROOT::TSeqI(0,nElements,nSteps));
#else
for (size_t i = 0; i < nElements ; i+= nSteps)
f(i);
#endif
}
else {
f(0);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Checks two matrices for element-wise equality.
/// \tparam AReal An architecture-specific floating point number type.
/// \param A The first matrix.
/// \param B The second matrix.
/// \param epsilon Equality tolerance, needed to address floating point arithmetic.
/// \return Whether the two matrices can be considered equal element-wise
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename AReal>
bool TCpu<AReal>::AlmostEquals(const TCpuMatrix<AReal> &A, const TCpuMatrix<AReal> &B, double epsilon)
{
if (A.GetNrows() != B.GetNrows() || A.GetNcols() != B.GetNcols()) {
Fatal("AlmostEquals", "The passed matrices have unequal shapes.");
}
const AReal *dataA = A.GetRawDataPointer();
const AReal *dataB = B.GetRawDataPointer();
size_t nElements = A.GetNoElements();
for(size_t i = 0; i < nElements; i++) {
if(fabs(dataA[i] - dataB[i]) > epsilon) return false;
}
return true;
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::SumColumns(TCpuMatrix<AReal> &B,
const TCpuMatrix<AReal> &A,
AReal alpha, AReal beta)
{
#ifdef R__HAS_TMVACPU
int m = (int) A.GetNrows();
int n = (int) A.GetNcols();
int inc = 1;
// AReal alpha = 1.0;
//AReal beta = 0.0;
char trans = 'T';
const AReal * APointer = A.GetRawDataPointer();
AReal * BPointer = B.GetRawDataPointer();
::TMVA::DNN::Blas::Gemv(&trans, &m, &n, &alpha, APointer, &m,
TCpuMatrix<AReal>::GetOnePointer(), &inc,
&beta, BPointer, &inc);
#else
TMatrixT<AReal> tmp(B.GetNrows(), B.GetNcols());
TReference<AReal>::SumColumns(tmp,A);
tmp = alpha*tmp + beta;
B = tmp;
#endif
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::ScaleAdd(TCpuMatrix<AReal> &B,
const TCpuMatrix<AReal> &A,
AReal alpha)
{
#ifdef R__HAS_TMVACPU
int n = (int) (A.GetNcols() * A.GetNrows());
int inc = 1;
const AReal *x = A.GetRawDataPointer();
AReal *y = B.GetRawDataPointer();
::TMVA::DNN::Blas::Axpy(&n, &alpha, x, &inc, y, &inc);
#else
TMatrixT<AReal> tmp;
TReference<AReal>::ScaleAdd(tmp, A, alpha);
B = tmp;
#endif
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::Copy(TCpuMatrix<AReal> &B,
const TCpuMatrix<AReal> &A)
{
auto f = [](AReal x) {return x;};
B.MapFrom(f, A);
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::ScaleAdd(TCpuTensor<AReal> &B,
const TCpuTensor<AReal> &A,
AReal alpha)
{
// should re-implemented at tensor level
for (size_t i = 0; i < B.GetFirstSize(); ++i) {
TCpuMatrix<AReal> B_m = B.At(i).GetMatrix();
ScaleAdd(B_m, A.At(i).GetMatrix(), alpha);
}
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::Copy(TCpuTensor<AReal> &B,
const TCpuTensor<AReal> &A)
{
auto f = [](AReal x) {return x;};
B.MapFrom(f, A);
}
//____________________________________________________________________________
template <typename AReal>
void TCpu<AReal>::ConstAdd(TCpuMatrix<AReal> &A, AReal beta)
{
auto f = [beta](AReal x) { return x + beta; };
A.Map(f);
}
//____________________________________________________________________________
template <typename AReal>
void TCpu<AReal>::ConstMult(TCpuMatrix<AReal> &A, AReal beta)
{
auto f = [beta](AReal x) { return x * beta; };
A.Map(f);
}
//____________________________________________________________________________
template <typename AReal>
void TCpu<AReal>::ReciprocalElementWise(TCpuMatrix<AReal> &A)
{
auto f = [](AReal x) { return 1.0 / x; };
A.Map(f);
}
//____________________________________________________________________________
template <typename AReal>
void TCpu<AReal>::SquareElementWise(TCpuMatrix<AReal> &A)
{
auto f = [](AReal x) { return x * x; };
A.Map(f);
}
//____________________________________________________________________________
template <typename AReal>
void TCpu<AReal>::SqrtElementWise(TCpuMatrix<AReal> &A)
{
auto f = [](AReal x) { return sqrt(x); };
A.Map(f);
}
/// Adam updates
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::AdamUpdate(TCpuMatrix<AReal> &A, const TCpuMatrix<AReal> & M, const TCpuMatrix<AReal> & V, AReal alpha, AReal eps)
{
// ADAM update the weights.
// Weight = Weight - alpha * M / (sqrt(V) + epsilon)
AReal * a = A.GetRawDataPointer();
const AReal * m = M.GetRawDataPointer();
const AReal * v = V.GetRawDataPointer();
for (size_t index = 0; index < A.GetNoElements() ; ++index) {
a[index] = a[index] - alpha * m[index]/( sqrt(v[index]) + eps);
}
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::AdamUpdateFirstMom(TCpuMatrix<AReal> &A, const TCpuMatrix<AReal> & B, AReal beta)
{
// First momentum weight gradient update for ADAM
// Mt = beta1 * Mt-1 + (1-beta1) * WeightGradients
AReal * a = A.GetRawDataPointer();
const AReal * b = B.GetRawDataPointer();
for (size_t index = 0; index < A.GetNoElements() ; ++index) {
a[index] = beta * a[index] + (1.-beta) * b[index];
}
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::AdamUpdateSecondMom(TCpuMatrix<AReal> &A, const TCpuMatrix<AReal> & B, AReal beta)
{
// Second momentum weight gradient update for ADAM
// Vt = beta2 * Vt-1 + (1-beta2) * WeightGradients^2
AReal * a = A.GetRawDataPointer();
const AReal * b = B.GetRawDataPointer();
for (size_t index = 0; index < A.GetNoElements() ; ++index) {
a[index] = beta * a[index] + (1.-beta) * b[index] * b[index];
}
}
} // DNN
} // TMVA
<commit_msg>Fix "unknown pragma" warnings on Windows<commit_after>// @(#)root/tmva/tmva/dnn:$Id$
// Author: Simon Pfreundschuh 20/07/16
/*************************************************************************
* Copyright (C) 2016, Simon Pfreundschuh *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
////////////////////////////////////////////////////////////
// Implementation of Helper arithmetic functions for the //
// multi-threaded CPU implementation of DNNs. //
////////////////////////////////////////////////////////////
#include "TMVA/DNN/Architectures/Cpu.h"
#ifdef R__HAS_TMVACPU
#include "TMVA/DNN/Architectures/Cpu/Blas.h"
#else
#include "TMVA/DNN/Architectures/Reference.h"
#endif
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
//#include "tbb/tbb.h"
#pragma GCC diagnostic pop
#endif
namespace TMVA
{
namespace DNN
{
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::Multiply(TCpuMatrix<AReal> &C,
const TCpuMatrix<AReal> &A,
const TCpuMatrix<AReal> &B)
{
int m = (int) A.GetNrows();
int k = (int) A.GetNcols();
int n = (int) B.GetNcols();
R__ASSERT((int) C.GetNrows() == m);
R__ASSERT((int) C.GetNcols() == n);
R__ASSERT((int) B.GetNrows() == k);
#ifdef R__HAS_TMVACPU
char transa = 'N';
char transb = 'N';
AReal alpha = 1.0;
AReal beta = 0.0;
const AReal * APointer = A.GetRawDataPointer();
const AReal * BPointer = B.GetRawDataPointer();
AReal * CPointer = C.GetRawDataPointer();
::TMVA::DNN::Blas::Gemm(&transa, &transb, &m, &n, &k, &alpha,
APointer, &m, BPointer, &k, &beta, CPointer, &m);
#else
TMatrixT<AReal> tmp(C.GetNrows(), C.GetNcols());
tmp.Mult(A,B);
C = tmp;
#endif
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::TransposeMultiply(TCpuMatrix<AReal> &C,
const TCpuMatrix<AReal> &A,
const TCpuMatrix<AReal> &B,
AReal alpha, AReal beta)
{
#ifdef R__HAS_TMVACPU
int m = (int) A.GetNcols();
int k = (int) A.GetNrows();
int n = (int) B.GetNcols();
R__ASSERT((int) C.GetNrows() == m);
R__ASSERT((int) C.GetNcols() == n);
R__ASSERT((int) B.GetNrows() == k);
char transa = 'T';
char transb = 'N';
//AReal alpha = 1.0;
//AReal beta = 0.0;
const AReal *APointer = A.GetRawDataPointer();
const AReal *BPointer = B.GetRawDataPointer();
AReal *CPointer = C.GetRawDataPointer();
::TMVA::DNN::Blas::Gemm(&transa, &transb, &m, &n, &k, &alpha,
APointer, &k, BPointer, &k, &beta, CPointer, &m);
#else
TMatrixT<AReal> tmp(C.GetNrows(), C.GetNcols());
tmp.TMult(A,B);
tmp = alpha*tmp + beta;
C = tmp;
#endif
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::Hadamard(TCpuMatrix<AReal> &B,
const TCpuMatrix<AReal> &A)
{
const AReal *dataA = A.GetRawDataPointer();
AReal *dataB = B.GetRawDataPointer();
size_t nElements = A.GetNoElements();
R__ASSERT(B.GetNoElements() == nElements);
size_t nSteps = TCpuMatrix<AReal>::GetNWorkItems(nElements);
auto f = [&](UInt_t workerID)
{
for (size_t j = 0; j < nSteps; ++j) {
size_t idx = workerID+j;
if (idx >= nElements) break;
dataB[idx] *= dataA[idx];
}
return 0;
};
if (nSteps < nElements) {
#ifdef DL_USE_MTE
B.GetThreadExecutor().Foreach(f, ROOT::TSeqI(0,nElements,nSteps));
#else
for (size_t i = 0; i < nElements ; i+= nSteps)
f(i);
#endif
}
else {
f(0);
}
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::Hadamard(TCpuTensor<AReal> &B,
const TCpuTensor<AReal> &A)
{
const AReal *dataA = A.GetRawDataPointer();
AReal *dataB = B.GetRawDataPointer();
size_t nElements = A.GetNoElements();
R__ASSERT(B.GetNoElements() == nElements);
size_t nSteps = TCpuMatrix<AReal>::GetNWorkItems(nElements);
auto f = [&](UInt_t workerID)
{
for (size_t j = 0; j < nSteps; ++j) {
size_t idx = workerID+j;
if (idx >= nElements) break;
dataB[idx] *= dataA[idx];
}
return 0;
};
if (nSteps < nElements) {
#ifdef DL_USE_MTE
TMVA::Config::Instance().GetThreadExecutor().Foreach(f, ROOT::TSeqI(0,nElements,nSteps));
#else
for (size_t i = 0; i < nElements ; i+= nSteps)
f(i);
#endif
}
else {
f(0);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Checks two matrices for element-wise equality.
/// \tparam AReal An architecture-specific floating point number type.
/// \param A The first matrix.
/// \param B The second matrix.
/// \param epsilon Equality tolerance, needed to address floating point arithmetic.
/// \return Whether the two matrices can be considered equal element-wise
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename AReal>
bool TCpu<AReal>::AlmostEquals(const TCpuMatrix<AReal> &A, const TCpuMatrix<AReal> &B, double epsilon)
{
if (A.GetNrows() != B.GetNrows() || A.GetNcols() != B.GetNcols()) {
Fatal("AlmostEquals", "The passed matrices have unequal shapes.");
}
const AReal *dataA = A.GetRawDataPointer();
const AReal *dataB = B.GetRawDataPointer();
size_t nElements = A.GetNoElements();
for(size_t i = 0; i < nElements; i++) {
if(fabs(dataA[i] - dataB[i]) > epsilon) return false;
}
return true;
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::SumColumns(TCpuMatrix<AReal> &B,
const TCpuMatrix<AReal> &A,
AReal alpha, AReal beta)
{
#ifdef R__HAS_TMVACPU
int m = (int) A.GetNrows();
int n = (int) A.GetNcols();
int inc = 1;
// AReal alpha = 1.0;
//AReal beta = 0.0;
char trans = 'T';
const AReal * APointer = A.GetRawDataPointer();
AReal * BPointer = B.GetRawDataPointer();
::TMVA::DNN::Blas::Gemv(&trans, &m, &n, &alpha, APointer, &m,
TCpuMatrix<AReal>::GetOnePointer(), &inc,
&beta, BPointer, &inc);
#else
TMatrixT<AReal> tmp(B.GetNrows(), B.GetNcols());
TReference<AReal>::SumColumns(tmp,A);
tmp = alpha*tmp + beta;
B = tmp;
#endif
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::ScaleAdd(TCpuMatrix<AReal> &B,
const TCpuMatrix<AReal> &A,
AReal alpha)
{
#ifdef R__HAS_TMVACPU
int n = (int) (A.GetNcols() * A.GetNrows());
int inc = 1;
const AReal *x = A.GetRawDataPointer();
AReal *y = B.GetRawDataPointer();
::TMVA::DNN::Blas::Axpy(&n, &alpha, x, &inc, y, &inc);
#else
TMatrixT<AReal> tmp;
TReference<AReal>::ScaleAdd(tmp, A, alpha);
B = tmp;
#endif
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::Copy(TCpuMatrix<AReal> &B,
const TCpuMatrix<AReal> &A)
{
auto f = [](AReal x) {return x;};
B.MapFrom(f, A);
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::ScaleAdd(TCpuTensor<AReal> &B,
const TCpuTensor<AReal> &A,
AReal alpha)
{
// should re-implemented at tensor level
for (size_t i = 0; i < B.GetFirstSize(); ++i) {
TCpuMatrix<AReal> B_m = B.At(i).GetMatrix();
ScaleAdd(B_m, A.At(i).GetMatrix(), alpha);
}
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::Copy(TCpuTensor<AReal> &B,
const TCpuTensor<AReal> &A)
{
auto f = [](AReal x) {return x;};
B.MapFrom(f, A);
}
//____________________________________________________________________________
template <typename AReal>
void TCpu<AReal>::ConstAdd(TCpuMatrix<AReal> &A, AReal beta)
{
auto f = [beta](AReal x) { return x + beta; };
A.Map(f);
}
//____________________________________________________________________________
template <typename AReal>
void TCpu<AReal>::ConstMult(TCpuMatrix<AReal> &A, AReal beta)
{
auto f = [beta](AReal x) { return x * beta; };
A.Map(f);
}
//____________________________________________________________________________
template <typename AReal>
void TCpu<AReal>::ReciprocalElementWise(TCpuMatrix<AReal> &A)
{
auto f = [](AReal x) { return 1.0 / x; };
A.Map(f);
}
//____________________________________________________________________________
template <typename AReal>
void TCpu<AReal>::SquareElementWise(TCpuMatrix<AReal> &A)
{
auto f = [](AReal x) { return x * x; };
A.Map(f);
}
//____________________________________________________________________________
template <typename AReal>
void TCpu<AReal>::SqrtElementWise(TCpuMatrix<AReal> &A)
{
auto f = [](AReal x) { return sqrt(x); };
A.Map(f);
}
/// Adam updates
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::AdamUpdate(TCpuMatrix<AReal> &A, const TCpuMatrix<AReal> & M, const TCpuMatrix<AReal> & V, AReal alpha, AReal eps)
{
// ADAM update the weights.
// Weight = Weight - alpha * M / (sqrt(V) + epsilon)
AReal * a = A.GetRawDataPointer();
const AReal * m = M.GetRawDataPointer();
const AReal * v = V.GetRawDataPointer();
for (size_t index = 0; index < A.GetNoElements() ; ++index) {
a[index] = a[index] - alpha * m[index]/( sqrt(v[index]) + eps);
}
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::AdamUpdateFirstMom(TCpuMatrix<AReal> &A, const TCpuMatrix<AReal> & B, AReal beta)
{
// First momentum weight gradient update for ADAM
// Mt = beta1 * Mt-1 + (1-beta1) * WeightGradients
AReal * a = A.GetRawDataPointer();
const AReal * b = B.GetRawDataPointer();
for (size_t index = 0; index < A.GetNoElements() ; ++index) {
a[index] = beta * a[index] + (1.-beta) * b[index];
}
}
//____________________________________________________________________________
template<typename AReal>
void TCpu<AReal>::AdamUpdateSecondMom(TCpuMatrix<AReal> &A, const TCpuMatrix<AReal> & B, AReal beta)
{
// Second momentum weight gradient update for ADAM
// Vt = beta2 * Vt-1 + (1-beta2) * WeightGradients^2
AReal * a = A.GetRawDataPointer();
const AReal * b = B.GetRawDataPointer();
for (size_t index = 0; index < A.GetNoElements() ; ++index) {
a[index] = beta * a[index] + (1.-beta) * b[index] * b[index];
}
}
} // DNN
} // TMVA
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgstreamercamerafocuscontrol_maemo.h"
#include "qgstreamercapturesession_maemo.h"
#include <gst/interfaces/photography.h>
QGstreamerCameraFocusControl::QGstreamerCameraFocusControl(GstElement &camerabin, QGstreamerCaptureSession *session)
:QCameraFocusControl(session),
m_session(session),
m_camerabin(camerabin)
{
}
QGstreamerCameraFocusControl::~QGstreamerCameraFocusControl()
{
}
QCamera::FocusMode QGstreamerCameraFocusControl::focusMode() const
{
return QCamera::AutoFocus;
}
void QGstreamerCameraFocusControl::setFocusMode(QCamera::FocusMode mode)
{
if (mode == QCamera::AutoFocus)
gst_photography_set_autofocus(GST_PHOTOGRAPHY(&m_camerabin), TRUE);
}
QCamera::FocusModes QGstreamerCameraFocusControl::supportedFocusModes() const
{
return QCamera::AutoFocus;
}
QCamera::FocusStatus QGstreamerCameraFocusControl::focusStatus() const
{
}
bool QGstreamerCameraFocusControl::macroFocusingEnabled() const
{
}
bool QGstreamerCameraFocusControl::isMacroFocusingSupported() const
{
return false;
}
void QGstreamerCameraFocusControl::setMacroFocusingEnabled(bool)
{
return false;
}
qreal QGstreamerCameraFocusControl::maximumOpticalZoom() const
{
}
qreal QGstreamerCameraFocusControl::maximumDigitalZoom() const
{
}
qreal QGstreamerCameraFocusControl::opticalZoom() const
{
}
qreal QGstreamerCameraFocusControl::digitalZoom() const
{
}
void QGstreamerCameraFocusControl::zoomTo(qreal optical, qreal digital)
{
}
QCamera::FocusPointMode QGstreamerCameraFocusControl::focusPointMode() const
{
}
void QGstreamerCameraFocusControl::setFocusPointMode(QCamera::FocusPointMode mode)
{
}
QCamera::FocusPointModes QGstreamerCameraFocusControl::supportedFocusPointModes() const
{
}
QPointF QGstreamerCameraFocusControl::customFocusPoint() const
{
}
void QGstreamerCameraFocusControl::setCustomFocusPoint(const QPointF &point)
{
Q_UNUSED(point);
}
QList<QRectF> QGstreamerCameraFocusControl::focusZones() const
{
return QList<QRectF> ();
}
void QGstreamerCameraFocusControl::startFocusing()
{
}
void QGstreamerCameraFocusControl::cancelFocusing()
{
}
<commit_msg>Macro focusing isn't supported<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgstreamercamerafocuscontrol_maemo.h"
#include "qgstreamercapturesession_maemo.h"
#include <gst/interfaces/photography.h>
QGstreamerCameraFocusControl::QGstreamerCameraFocusControl(GstElement &camerabin, QGstreamerCaptureSession *session)
:QCameraFocusControl(session),
m_session(session),
m_camerabin(camerabin)
{
}
QGstreamerCameraFocusControl::~QGstreamerCameraFocusControl()
{
}
QCamera::FocusMode QGstreamerCameraFocusControl::focusMode() const
{
return QCamera::AutoFocus;
}
void QGstreamerCameraFocusControl::setFocusMode(QCamera::FocusMode mode)
{
if (mode == QCamera::AutoFocus)
gst_photography_set_autofocus(GST_PHOTOGRAPHY(&m_camerabin), TRUE);
}
QCamera::FocusModes QGstreamerCameraFocusControl::supportedFocusModes() const
{
return QCamera::AutoFocus;
}
QCamera::FocusStatus QGstreamerCameraFocusControl::focusStatus() const
{
}
bool QGstreamerCameraFocusControl::macroFocusingEnabled() const
{
}
bool QGstreamerCameraFocusControl::isMacroFocusingSupported() const
{
return false;
}
void QGstreamerCameraFocusControl::setMacroFocusingEnabled(bool)
{
// Macro focusing isn't supported
}
qreal QGstreamerCameraFocusControl::maximumOpticalZoom() const
{
}
qreal QGstreamerCameraFocusControl::maximumDigitalZoom() const
{
}
qreal QGstreamerCameraFocusControl::opticalZoom() const
{
}
qreal QGstreamerCameraFocusControl::digitalZoom() const
{
}
void QGstreamerCameraFocusControl::zoomTo(qreal optical, qreal digital)
{
}
QCamera::FocusPointMode QGstreamerCameraFocusControl::focusPointMode() const
{
}
void QGstreamerCameraFocusControl::setFocusPointMode(QCamera::FocusPointMode mode)
{
}
QCamera::FocusPointModes QGstreamerCameraFocusControl::supportedFocusPointModes() const
{
}
QPointF QGstreamerCameraFocusControl::customFocusPoint() const
{
}
void QGstreamerCameraFocusControl::setCustomFocusPoint(const QPointF &point)
{
Q_UNUSED(point);
}
QList<QRectF> QGstreamerCameraFocusControl::focusZones() const
{
return QList<QRectF> ();
}
void QGstreamerCameraFocusControl::startFocusing()
{
}
void QGstreamerCameraFocusControl::cancelFocusing()
{
}
<|endoftext|> |
<commit_before>// HACK - lifted from https://github.com/harto/realpath-osx
#include <climits>
#include <cstring>
#include <cstdio>
#include <cstdlib>
int main (int argc, char** argv)
{
size_t pathIdx = 1;
if (argc == 3 && strcmp (argv[1], "--canonicalize-missing") == 0) {
pathIdx += 1;
}
else if (argc != 2) {
fprintf (stderr, "Usage: realpath <path>\n");
return 1;
}
char* path = argv[pathIdx];
char result[PATH_MAX];
if (realpath (path, result)) {
printf ("%s\n", result);
return 0;
}
else {
fprintf (stderr, "Bad path: %s\n", result);
return 2;
}
}
<commit_msg>cosmetic<commit_after>// HACK - lifted from https://github.com/harto/realpath-osx
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
int main (int argc, char** argv)
{
size_t pathIdx = 1;
if (argc == 3 && strcmp (argv[1], "--canonicalize-missing") == 0) {
pathIdx += 1;
}
else if (argc != 2) {
fprintf (stderr, "Usage: realpath <path>\n");
return 1;
}
char* path = argv[pathIdx];
char result[PATH_MAX];
if (realpath (path, result)) {
printf ("%s\n", result);
return 0;
}
else {
fprintf (stderr, "Bad path: %s\n", result);
return 2;
}
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/averaged_fan.h"
// GRINS
#include "grins/generic_ic_handler.h"
// libMesh
#include "libmesh/quadrature.h"
#include "libmesh/boundary_info.h"
#include "libmesh/parsed_function.h"
#include "libmesh/zero_function.h"
namespace GRINS
{
AveragedFan::AveragedFan( const std::string& physics_name, const GetPot& input )
: IncompressibleNavierStokesBase(physics_name, input)
{
this->read_input_options(input);
return;
}
AveragedFan::~AveragedFan()
{
return;
}
void AveragedFan::read_input_options( const GetPot& input )
{
std::string base_function =
input("Physics/"+averaged_fan+"/base_velocity",
std::string("0"));
if (base_function == "0")
libmesh_error_msg("Error! Zero AveragedFan specified!" <<
std::endl);
if (base_function == "0")
this->base_velocity_function.reset
(new libMesh::ZeroFunction<libMesh::Number>());
else
this->base_velocity_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(base_function));
std::string vertical_function =
input("Physics/"+averaged_fan+"/local_vertical",
std::string("0"));
if (vertical_function == "0")
libmesh_error_msg("Warning! Zero LocalVertical specified!" <<
std::endl);
this->local_vertical_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(vertical_function));
std::string lift_function_string =
input("Physics/"+averaged_fan+"/lift",
std::string("0"));
if (lift_function_string == "0")
std::cout << "Warning! Zero lift function specified!" << std::endl;
this->lift_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(lift_function_string));
std::string drag_function_string =
input("Physics/"+averaged_fan+"/drag",
std::string("0"));
if (drag_function_string == "0")
std::cout << "Warning! Zero drag function specified!" << std::endl;
this->drag_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(drag_function_string));
std::string chord_function_string =
input("Physics/"+averaged_fan+"/chord_length",
std::string("0"));
if (chord_function_string == "0")
libmesh_error_msg("Warning! Zero chord function specified!" <<
std::endl);
this->chord_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(chord_function_string));
std::string area_function_string =
input("Physics/"+averaged_fan+"/area_swept",
std::string("0"));
if (area_function_string == "0")
libmesh_error_msg("Warning! Zero area_swept_function specified!" <<
std::endl);
this->area_swept_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(area_function_string));
std::string aoa_function_string =
input("Physics/"+averaged_fan+"/angle_of_attack",
std::string("00000"));
if (aoa_function_string == "00000")
libmesh_error_msg("Warning! No angle-of-attack specified!" <<
std::endl);
this->aoa_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(aoa_function_string));
}
void AveragedFan::element_time_derivative( bool compute_jacobian,
AssemblyContext& context,
CachedValues& /* cache */ )
{
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->BeginTimer("AveragedFan::element_time_derivative");
#endif
// Element Jacobian * quadrature weights for interior integration
const std::vector<libMesh::Real> &JxW =
context.get_element_fe(this->_flow_vars.u_var())->get_JxW();
// The shape functions at interior quadrature points.
const std::vector<std::vector<libMesh::Real> >& u_phi =
context.get_element_fe(this->_flow_vars.u_var())->get_phi();
const std::vector<libMesh::Point>& u_qpoint =
context.get_element_fe(this->_flow_vars.u_var())->get_xyz();
// The number of local degrees of freedom in each variable
const unsigned int n_u_dofs = context.get_dof_indices(_flow_vars.u_var()).size();
// The subvectors and submatrices we need to fill:
libMesh::DenseSubMatrix<libMesh::Number> &Kuu = context.get_elem_jacobian(_flow_vars.u_var(), _flow_vars.u_var()); // R_{u},{u}
libMesh::DenseSubMatrix<libMesh::Number> &Kuv = context.get_elem_jacobian(_flow_vars.u_var(), _flow_vars.v_var()); // R_{u},{v}
libMesh::DenseSubMatrix<libMesh::Number> &Kvu = context.get_elem_jacobian(_flow_vars.v_var(), _flow_vars.u_var()); // R_{v},{u}
libMesh::DenseSubMatrix<libMesh::Number> &Kvv = context.get_elem_jacobian(_flow_vars.v_var(), _flow_vars.v_var()); // R_{v},{v}
libMesh::DenseSubMatrix<libMesh::Number>* Kwu = NULL;
libMesh::DenseSubMatrix<libMesh::Number>* Kwv = NULL;
libMesh::DenseSubMatrix<libMesh::Number>* Kww = NULL;
libMesh::DenseSubMatrix<libMesh::Number>* Kuw = NULL;
libMesh::DenseSubMatrix<libMesh::Number>* Kvw = NULL;
libMesh::DenseSubVector<libMesh::Number> &Fu = context.get_elem_residual(_flow_vars.u_var()); // R_{u}
libMesh::DenseSubVector<libMesh::Number> &Fv = context.get_elem_residual(_flow_vars.v_var()); // R_{v}
libMesh::DenseSubVector<libMesh::Number>* Fw = NULL;
if( this->_dim == 3 )
{
Kuw = &context.get_elem_jacobian(_flow_vars.u_var(), _flow_vars.w_var()); // R_{u},{w}
Kvw = &context.get_elem_jacobian(_flow_vars.v_var(), _flow_vars.w_var()); // R_{v},{w}
Kwu = &context.get_elem_jacobian(_flow_vars.w_var(), _flow_vars.u_var()); // R_{w},{u}
Kwv = &context.get_elem_jacobian(_flow_vars.w_var(), _flow_vars.v_var()); // R_{w},{v}
Kww = &context.get_elem_jacobian(_flow_vars.w_var(), _flow_vars.w_var()); // R_{w},{w}
Fw = &context.get_elem_residual(_flow_vars.w_var()); // R_{w}
}
unsigned int n_qpoints = context.get_element_qrule().n_points();
for (unsigned int qp=0; qp != n_qpoints; qp++)
{
// Compute the solution & its gradient at the old Newton iterate.
libMesh::Number u, v;
u = context.interior_value(_flow_vars.u_var(), qp);
v = context.interior_value(_flow_vars.v_var(), qp);
libMesh::NumberVectorValue U(u,v);
if (_dim == 3)
U(2) = context.interior_value(_flow_vars.w_var(), qp); // w
// Find base velocity of moving fan at this point
libmesh_assert(base_velocity_function.get());
libMesh::DenseVector<libMesh::Number> output_vec(3);
(*base_velocity_function)(u_qpoint[qp], context.time,
output_vec);
const libMesh::NumberVectorValue U_B(output_vec(0),
output_vec(1),
output_vec(2));
// Normal in fan velocity direction
const libMesh::NumberVectorValue N_B = U_B.unit();
(*local_vertical_function)(u_qpoint[qp], context.time,
output_vec);
// Normal in fan vertical direction
const libMesh::NumberVectorValue N_V(output_vec(0),
output_vec(1),
output_vec(2));
// Normal in radial direction
const libMesh::NumberVectorValue N_R = N_V.cross(N_B);
// Fan-wing-plane component of local relative velocity
const libMesh::NumberVectorValue U_P = U - (U*N_R)*N_R - U_B;
// Direction opposing drag
const libMesh::NumberVectorValue N_drag = -U_P.unit();
// Direction opposing lift
const libMesh::NumberVectorValue N_lift = N_drag.cross(N_R);
// "Forward" velocity
const libMesh::Number u_fwd = -(U_P * N_B);
// "Upward" velocity
const libMesh::Number u_up = U_P * N_V;
// Angle WRT fan velocity direction
const libMesh::Number part_angle = std::atan2(u_up, u_fwd);
// Angle WRT fan chord
const libMesh::Number angle = part_angle +
(*aoa_function)(u_qpoint[qp], context.time);
const libMesh::Number C_lift = (*lift_function)(u_qpoint[qp], angle);
const libMesh::Number C_drag = (*drag_function)(u_qpoint[qp], angle);
const libMesh::Number chord = (*chord_function)(u_qpoint[qp], context.time);
const libMesh::Number area = (*area_swept_function)(u_qpoint[qp], context.time);
const libMesh::Number v_sq = U_P*U_P;
const libMesh::Number lift = C_lift / 2 * this->_rho * v_sq * chord / area;
const libMesh::Number drag = C_drag / 2 * this->_rho * v_sq * chord / area;
// Force
const libMesh::NumberVectorValue F = lift * N_lift + drag * N_drag;
for (unsigned int i=0; i != n_u_dofs; i++)
{
Fu(i) += F(0)*u_phi[i][qp]*JxW[qp];
Fv(i) += F(1)*u_phi[i][qp]*JxW[qp];
if (_dim == 3)
(*Fw)(i) += F(2)*u_phi[i][qp]*JxW[qp];
if (compute_jacobian)
{
for (unsigned int j=0; j != n_u_dofs; j++)
{
Kuu(i,j) += 0*u_phi[i][qp]*JxW[qp];
Kvv(i,j) += 0*u_phi[i][qp]*JxW[qp];
if (_dim == 3)
{
(*Kww)(i,j) += 0*u_phi[i][qp]*JxW[qp];
}
} // End j dof loop
} // End compute_jacobian check
} // End i dof loop
}
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->EndTimer("AveragedFan::element_time_derivative");
#endif
return;
}
} // namespace GRINS
<commit_msg>Partial Jacobians for AveragedFan<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/averaged_fan.h"
// GRINS
#include "grins/generic_ic_handler.h"
// libMesh
#include "libmesh/quadrature.h"
#include "libmesh/boundary_info.h"
#include "libmesh/parsed_function.h"
#include "libmesh/zero_function.h"
namespace GRINS
{
AveragedFan::AveragedFan( const std::string& physics_name, const GetPot& input )
: IncompressibleNavierStokesBase(physics_name, input)
{
this->read_input_options(input);
return;
}
AveragedFan::~AveragedFan()
{
return;
}
void AveragedFan::read_input_options( const GetPot& input )
{
std::string base_function =
input("Physics/"+averaged_fan+"/base_velocity",
std::string("0"));
if (base_function == "0")
libmesh_error_msg("Error! Zero AveragedFan specified!" <<
std::endl);
if (base_function == "0")
this->base_velocity_function.reset
(new libMesh::ZeroFunction<libMesh::Number>());
else
this->base_velocity_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(base_function));
std::string vertical_function =
input("Physics/"+averaged_fan+"/local_vertical",
std::string("0"));
if (vertical_function == "0")
libmesh_error_msg("Warning! Zero LocalVertical specified!" <<
std::endl);
this->local_vertical_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(vertical_function));
std::string lift_function_string =
input("Physics/"+averaged_fan+"/lift",
std::string("0"));
if (lift_function_string == "0")
std::cout << "Warning! Zero lift function specified!" << std::endl;
this->lift_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(lift_function_string));
std::string drag_function_string =
input("Physics/"+averaged_fan+"/drag",
std::string("0"));
if (drag_function_string == "0")
std::cout << "Warning! Zero drag function specified!" << std::endl;
this->drag_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(drag_function_string));
std::string chord_function_string =
input("Physics/"+averaged_fan+"/chord_length",
std::string("0"));
if (chord_function_string == "0")
libmesh_error_msg("Warning! Zero chord function specified!" <<
std::endl);
this->chord_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(chord_function_string));
std::string area_function_string =
input("Physics/"+averaged_fan+"/area_swept",
std::string("0"));
if (area_function_string == "0")
libmesh_error_msg("Warning! Zero area_swept_function specified!" <<
std::endl);
this->area_swept_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(area_function_string));
std::string aoa_function_string =
input("Physics/"+averaged_fan+"/angle_of_attack",
std::string("00000"));
if (aoa_function_string == "00000")
libmesh_error_msg("Warning! No angle-of-attack specified!" <<
std::endl);
this->aoa_function.reset
(new libMesh::ParsedFunction<libMesh::Number>(aoa_function_string));
}
void AveragedFan::element_time_derivative( bool compute_jacobian,
AssemblyContext& context,
CachedValues& /* cache */ )
{
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->BeginTimer("AveragedFan::element_time_derivative");
#endif
// Element Jacobian * quadrature weights for interior integration
const std::vector<libMesh::Real> &JxW =
context.get_element_fe(this->_flow_vars.u_var())->get_JxW();
// The shape functions at interior quadrature points.
const std::vector<std::vector<libMesh::Real> >& u_phi =
context.get_element_fe(this->_flow_vars.u_var())->get_phi();
const std::vector<libMesh::Point>& u_qpoint =
context.get_element_fe(this->_flow_vars.u_var())->get_xyz();
// The number of local degrees of freedom in each variable
const unsigned int n_u_dofs = context.get_dof_indices(_flow_vars.u_var()).size();
// The subvectors and submatrices we need to fill:
libMesh::DenseSubMatrix<libMesh::Number> &Kuu = context.get_elem_jacobian(_flow_vars.u_var(), _flow_vars.u_var()); // R_{u},{u}
libMesh::DenseSubMatrix<libMesh::Number> &Kuv = context.get_elem_jacobian(_flow_vars.u_var(), _flow_vars.v_var()); // R_{u},{v}
libMesh::DenseSubMatrix<libMesh::Number> &Kvu = context.get_elem_jacobian(_flow_vars.v_var(), _flow_vars.u_var()); // R_{v},{u}
libMesh::DenseSubMatrix<libMesh::Number> &Kvv = context.get_elem_jacobian(_flow_vars.v_var(), _flow_vars.v_var()); // R_{v},{v}
libMesh::DenseSubMatrix<libMesh::Number>* Kwu = NULL;
libMesh::DenseSubMatrix<libMesh::Number>* Kwv = NULL;
libMesh::DenseSubMatrix<libMesh::Number>* Kww = NULL;
libMesh::DenseSubMatrix<libMesh::Number>* Kuw = NULL;
libMesh::DenseSubMatrix<libMesh::Number>* Kvw = NULL;
libMesh::DenseSubVector<libMesh::Number> &Fu = context.get_elem_residual(_flow_vars.u_var()); // R_{u}
libMesh::DenseSubVector<libMesh::Number> &Fv = context.get_elem_residual(_flow_vars.v_var()); // R_{v}
libMesh::DenseSubVector<libMesh::Number>* Fw = NULL;
if( this->_dim == 3 )
{
Kuw = &context.get_elem_jacobian(_flow_vars.u_var(), _flow_vars.w_var()); // R_{u},{w}
Kvw = &context.get_elem_jacobian(_flow_vars.v_var(), _flow_vars.w_var()); // R_{v},{w}
Kwu = &context.get_elem_jacobian(_flow_vars.w_var(), _flow_vars.u_var()); // R_{w},{u}
Kwv = &context.get_elem_jacobian(_flow_vars.w_var(), _flow_vars.v_var()); // R_{w},{v}
Kww = &context.get_elem_jacobian(_flow_vars.w_var(), _flow_vars.w_var()); // R_{w},{w}
Fw = &context.get_elem_residual(_flow_vars.w_var()); // R_{w}
}
unsigned int n_qpoints = context.get_element_qrule().n_points();
for (unsigned int qp=0; qp != n_qpoints; qp++)
{
// Compute the solution & its gradient at the old Newton iterate.
libMesh::Number u, v;
u = context.interior_value(_flow_vars.u_var(), qp);
v = context.interior_value(_flow_vars.v_var(), qp);
libMesh::NumberVectorValue U(u,v);
if (_dim == 3)
U(2) = context.interior_value(_flow_vars.w_var(), qp); // w
// Find base velocity of moving fan at this point
libmesh_assert(base_velocity_function.get());
libMesh::DenseVector<libMesh::Number> output_vec(3);
(*base_velocity_function)(u_qpoint[qp], context.time,
output_vec);
const libMesh::NumberVectorValue U_B(output_vec(0),
output_vec(1),
output_vec(2));
// Normal in fan velocity direction
const libMesh::NumberVectorValue N_B = U_B.unit();
(*local_vertical_function)(u_qpoint[qp], context.time,
output_vec);
// Normal in fan vertical direction
const libMesh::NumberVectorValue N_V(output_vec(0),
output_vec(1),
output_vec(2));
// Normal in radial direction
const libMesh::NumberVectorValue N_R = N_V.cross(N_B);
// Fan-wing-plane component of local relative velocity
const libMesh::NumberVectorValue U_P = U - (U*N_R)*N_R - U_B;
// Direction opposing drag
const libMesh::NumberVectorValue N_drag = -U_P.unit();
// Direction opposing lift
const libMesh::NumberVectorValue N_lift = N_drag.cross(N_R);
// "Forward" velocity
const libMesh::Number u_fwd = -(U_P * N_B);
// "Upward" velocity
const libMesh::Number u_up = U_P * N_V;
// Angle WRT fan velocity direction
const libMesh::Number part_angle = std::atan2(u_up, u_fwd);
// Angle WRT fan chord
const libMesh::Number angle = part_angle +
(*aoa_function)(u_qpoint[qp], context.time);
const libMesh::Number C_lift = (*lift_function)(u_qpoint[qp], angle);
const libMesh::Number C_drag = (*drag_function)(u_qpoint[qp], angle);
const libMesh::Number chord = (*chord_function)(u_qpoint[qp], context.time);
const libMesh::Number area = (*area_swept_function)(u_qpoint[qp], context.time);
const libMesh::Number v_sq = U_P*U_P;
const libMesh::Number LDfactor = 0.5 * this->_rho * v_sq * chord / area;
const libMesh::Number lift = C_lift * LDfactor;
const libMesh::Number drag = C_drag * LDfactor;
// Force
const libMesh::NumberVectorValue F = lift * N_lift + drag * N_drag;
for (unsigned int i=0; i != n_u_dofs; i++)
{
Fu(i) += F(0)*u_phi[i][qp]*JxW[qp];
Fv(i) += F(1)*u_phi[i][qp]*JxW[qp];
if (_dim == 3)
(*Fw)(i) += F(2)*u_phi[i][qp]*JxW[qp];
if (compute_jacobian)
{
// FIXME: Jacobians here are very inexact!
// Dropping all AoA dependence on U terms!
for (unsigned int j=0; j != n_u_dofs; j++)
{
libMesh::Number UPNR = U_P*N_R;
libMesh::Number
dV2_du = 2 * u_phi[j][qp] *
(U_P(0) - N_R(0)*UPNR);
libMesh::Number
dV2_dv = 2 * u_phi[j][qp] *
(U_P(1) - N_R(1)*UPNR);
const libMesh::Number
LDderivfactor =
(N_lift*C_lift+N_drag*C_drag) *
0.5 * this->_rho * chord / area;
Kuu(i,j) += LDderivfactor(0) * dV2_du *
u_phi[i][qp]*JxW[qp];
Kuv(i,j) += LDderivfactor(0) * dV2_dv *
u_phi[i][qp]*JxW[qp];
Kvu(i,j) += LDderivfactor(1) * dV2_du *
u_phi[i][qp]*JxW[qp];
Kvv(i,j) += LDderivfactor(1) * dV2_dv *
u_phi[i][qp]*JxW[qp];
if (_dim == 3)
{
dV2_dw = 2 * u_phi[j][qp] *
(U_P(2) - N_R(2)*UPNR);
(*Kuw)(i,j) += LDderivfactor(0) * dV2_dw *
u_phi[i][qp]*JxW[qp];
(*Kvw)(i,j) += LDderivfactor(1) * dV2_dw *
u_phi[i][qp]*JxW[qp];
(*Kwu)(i,j) += LDderivfactor(2) * dV2_du *
u_phi[i][qp]*JxW[qp];
(*Kwv)(i,j) += LDderivfactor(2) * dV2_dv *
u_phi[i][qp]*JxW[qp];
(*Kww)(i,j) += LDderivfactor(2) * dV2_dw *
u_phi[i][qp]*JxW[qp];
}
} // End j dof loop
} // End compute_jacobian check
} // End i dof loop
}
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->EndTimer("AveragedFan::element_time_derivative");
#endif
return;
}
} // namespace GRINS
<|endoftext|> |
<commit_before>#include "JPetHLDReader.h"
#include <iostream>
bool JPetHLDReader::OpenFile (const char* filename){
JPetReader::OpenFile(filename);
ReadData("T");
fBranch->SetAddress(fEvent);
}<commit_msg>drobna poprawka<commit_after>#include "JPetHLDReader.h"
#include <iostream>
bool JPetHLDReader::OpenFile (const char* filename){
JPetReader::OpenFile(filename);
ReadData("T");
fBranch->SetAddress(&fEvent);
}<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "character_skills_layout.h"
using namespace std;
using namespace glm;
namespace asdf
{
namespace gurps_track
{
using namespace ui::layout_constants;
character_skills_layout_t::character_skills_layout_t(std::shared_ptr<character_t> _character)
: ui_list_view_t()
, character(_character)
{
// add_cell<label_t>("Skills");
skill_library = add_cell<character_skill_library_t>(character);
skill_library->set_size(100, 400);
}
character_skill_library_entry_t::character_skill_library_entry_t(character_skill_library_t* _library, size_t _index)
: collapsable_list_view_t("test_name")
, skill_name(button->label)
, library(_library)
, index(_index)
{
point_cost = button->add_child<ui_label_t>("0.5", Content.fonts[info_font]);
effective_skill = button->add_child<ui_label_t>("00", Content.fonts[info_font]);
extra_info = add_cell<label_t>("(W/W) 00 + 0");
increment_button = extra_info->add_child<button_view_t>("+", [this](ui_base_t*){ this->increment_point_value(); } );
decrement_button = extra_info->add_child<button_view_t>("-", [this](ui_base_t*){ this->decrement_point_value(); } );
skill_name-> alignment = ui_align_left;
point_cost-> alignment = ui_align_right;
effective_skill->alignment = ui_align_right;
extra_info->label->alignment = ui_align_left;
extra_info->label->offset.x = minor_padding;
skill_name-> offset.x = minor_padding;
point_cost-> offset.x = -96;
effective_skill->offset.x = -50;
increment_button->alignment = ui_align_right;
increment_button->set_size(40,40);
increment_button->offset.x = -60.0f - minor_padding;
decrement_button->alignment = ui_align_right;
decrement_button->set_size(40,40);
set_data(library->character->skills[index]);
}
void character_skill_library_entry_t::set_data(skill_listing_t const& skill_listing)
{
skill_name-> set_text(skill_listing.skill.name);
if(skill_listing.point_cost() == 0)
point_cost->set_text("(0.5)");
else
point_cost->set_text("(" + std::to_string(skill_listing.point_cost()) + ")" );
int skill_value = skill_listing.get_effective_skill (library->character.get());
effective_skill->set_text(std::to_string(skill_value));
std::string extra_info_str = "(" + std::string(skill_difficulty_abbreviations[skill_listing.skill.difficulty]) + ") ";
//todo: handle display of bonuses
extra_info->set_text(std::move(extra_info_str));
}
void character_skill_library_entry_t::change_point_value(bool positive)
{
library->character->improve_skill(index);
set_data(library->character->skills[index]);
}
void character_skill_library_entry_t::increment_point_value()
{
change_point_value(true);
}
void character_skill_library_entry_t::decrement_point_value()
{
LOG("todo: character_skill_library_entry_t::decrement_point_value()");
// change_point_value(false);
}
character_skill_library_t::character_skill_library_t(std::shared_ptr<character_t> _character)
: ui_list_view_t()
, character(std::move(_character))
{
physical_skills = add_cell<collapsable_list_view_t>("Physical");
mental_skills = add_cell<collapsable_list_view_t>("Mental");
rebuild_list();
}
void character_skill_library_t::rebuild_list()
{
//todo: do something more optimal than destroying all cells and rebuilding
physical_skills->cells.erase(physical_skills->cells.begin() + 1, physical_skills->cells.end());
mental_skills->cells.erase( mental_skills->cells.begin() + 1, mental_skills->cells.end());
for(size_t i = 0; i < character->skills.size(); ++i)
{
if(character->skills[i].skill.is_physical())
{
physical_skills->add_cell<character_skill_library_entry_t>(this, i);
}
else
{
mental_skills->add_cell<character_skill_library_entry_t>(this, i);
}
}
top_parent()->align();
}
void character_skill_library_t::update(float dt)
{
if(prev_skill_count != character->skills.size())
{
rebuild_list();
}
prev_skill_count = character->skills.size();
}
}
}<commit_msg>attempting to fix / debug some weird button callback issues<commit_after>#include "stdafx.h"
#include "character_skills_layout.h"
using namespace std;
using namespace glm;
namespace asdf
{
namespace gurps_track
{
using namespace ui::layout_constants;
character_skills_layout_t::character_skills_layout_t(std::shared_ptr<character_t> _character)
: ui_list_view_t()
, character(_character)
{
// add_cell<label_t>("Skills");
skill_library = add_cell<character_skill_library_t>(character);
skill_library->set_size(100, 400);
}
character_skill_library_entry_t::character_skill_library_entry_t(character_skill_library_t* _library, size_t _index)
: collapsable_list_view_t("test_name")
, skill_name(button->label)
, library(_library)
, index(_index)
{
point_cost = button->add_child<ui_label_t>("0.5", Content.fonts[info_font]);
effective_skill = button->add_child<ui_label_t>("00", Content.fonts[info_font]);
extra_info = add_cell<label_t>("(W/W) 00 + 0");
increment_button = extra_info->add_child<button_view_t>("+", [this](ui_base_t*){
this->increment_point_value(); } );
decrement_button = extra_info->add_child<button_view_t>("-", [this](ui_base_t*){ this->decrement_point_value(); } );
skill_name-> alignment = ui_align_left;
point_cost-> alignment = ui_align_right;
effective_skill->alignment = ui_align_right;
extra_info->label->alignment = ui_align_left;
extra_info->label->offset.x = minor_padding;
skill_name-> offset.x = minor_padding;
point_cost-> offset.x = -96;
effective_skill->offset.x = -50;
increment_button->alignment = ui_align_right;
increment_button->set_size(40,40);
increment_button->offset.x = -60.0f - minor_padding;
decrement_button->alignment = ui_align_right;
decrement_button->set_size(40,40);
set_data(library->character->skills[index]);
}
void character_skill_library_entry_t::set_data(skill_listing_t const& skill_listing)
{
skill_name-> set_text(skill_listing.skill.name);
if(skill_listing.point_cost() == 0)
point_cost->set_text("(0.5)");
else
point_cost->set_text("(" + std::to_string(skill_listing.point_cost()) + ")" );
int skill_value = skill_listing.get_effective_skill (library->character.get());
effective_skill->set_text(std::to_string(skill_value));
std::string extra_info_str = "(" + std::string(skill_difficulty_abbreviations[skill_listing.skill.difficulty]) + ") ";
//todo: handle display of bonuses
extra_info->set_text(std::move(extra_info_str));
}
void character_skill_library_entry_t::change_point_value(bool positive)
{
library->character->improve_skill(index);
set_data(library->character->skills[index]);
}
void character_skill_library_entry_t::increment_point_value()
{
change_point_value(true);
}
void character_skill_library_entry_t::decrement_point_value()
{
LOG("todo: character_skill_library_entry_t::decrement_point_value()");
// change_point_value(false);
}
character_skill_library_t::character_skill_library_t(std::shared_ptr<character_t> _character)
: ui_list_view_t()
, character(std::move(_character))
{
physical_skills = add_cell<collapsable_list_view_t>("Physical");
// mental_skills = add_cell<collapsable_list_view_t>("Mental");
rebuild_list();
}
void character_skill_library_t::rebuild_list()
{
//todo: do something more optimal than destroying all cells and rebuilding
physical_skills->cells.erase(physical_skills->cells.begin() + 1, physical_skills->cells.end());
// mental_skills->cells.erase( mental_skills->cells.begin() + 1, mental_skills->cells.end());
for(size_t i = 0; i < character->skills.size(); ++i)
{
if(character->skills[i].skill.is_physical())
{
physical_skills->add_cell<character_skill_library_entry_t>(this, i);
}
else
{
// mental_skills->add_cell<character_skill_library_entry_t>(this, i);
}
}
top_parent()->align();
}
void character_skill_library_t::update(float dt)
{
if(prev_skill_count != character->skills.size())
{
rebuild_list();
}
prev_skill_count = character->skills.size();
}
}
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "Sensors"
#include <hardware/sensors.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <math.h>
#include <poll.h>
#include <pthread.h>
#include <stdlib.h>
#include <linux/input.h>
#include <utils/Atomic.h>
#include <utils/Log.h>
#include "sensors.h"
#include "AccelSensor.h"
#include "LightSensor.h"
#include "ProximitySensor.h"
#include "AkmSensor.h"
#include "GyroSensor.h"
#include "PressureSensor.h"
/*****************************************************************************/
/* The SENSORS Module */
static const struct sensor_t sSensorList[] = {
/* Accelerometer */
{
"accelerometer",
"ST Micro",
1, /* hw/sw version */
SENSORS_ACCELERATION_HANDLE,
SENSOR_TYPE_ACCELEROMETER,
(2.0f * 9.81f),
(9.81f / 1024),
0.2f, /* mA */
2000, /* microseconds */
{ }
},
/* magnetic field sensor */
{
"AK8975",
"Asahi Kasei Microdevices",
1,
SENSORS_MAGNETIC_FIELD_HANDLE,
SENSOR_TYPE_MAGNETIC_FIELD,
2000.0f,
(1.0f/16.0f),
6.8f,
16667,
{ }
},
/* orientation sensor */
{
"AK8975",
"Asahi Kasei Microdevices",
1,
SENSORS_ORIENTATION_HANDLE,
SENSOR_TYPE_ORIENTATION,
360.0f,
(1.0f/64.0f),
7.8f,
16667 ,
{ }
},
/* light sensor name */
{
"TSL27713FN",
"Taos",
1,
SENSORS_LIGHT_HANDLE,
SENSOR_TYPE_LIGHT,
(powf(10, (280.0f / 47.0f)) * 4),
1.0f,
0.75f,
0,
{ }
},
/* proximity sensor */
{
"TSL27713FN",
"Taos",
1,
SENSORS_PROXIMITY_HANDLE,
SENSOR_TYPE_PROXIMITY,
5.0f,
5.0f,
0.75f,
0,
{ }
},
/* gyro scope */
{
"MPU3050",
"Invensense",
1,
SENSORS_GYROSCOPE_HANDLE,
SENSOR_TYPE_GYROSCOPE,
35.0f,
0.06f,
0.2f,
2000,
{ }
},
/* barometer */
{
"bmp180",
"Bosch",
1,
SENSORS_PRESSURE_HANDLE,
SENSOR_TYPE_PRESSURE,
1100.0f,
0.01f,
0.67f,
20000,
{ }
}
};
static int open_sensors(const struct hw_module_t* module, const char* id,
struct hw_device_t** device);
static int sensors__get_sensors_list(struct sensors_module_t* module,
struct sensor_t const** list)
{
*list = sSensorList;
return ARRAY_SIZE(sSensorList);
}
static struct hw_module_methods_t sensors_module_methods = {
open: open_sensors
};
struct sensors_module_t HAL_MODULE_INFO_SYM = {
common: {
tag: HARDWARE_MODULE_TAG,
version_major: 1,
version_minor: 0,
id: SENSORS_HARDWARE_MODULE_ID,
name: "Quic Sensor module",
author: "Quic",
methods: &sensors_module_methods,
},
get_sensors_list: sensors__get_sensors_list,
};
struct sensors_poll_context_t {
struct sensors_poll_device_t device; // must be first
sensors_poll_context_t();
~sensors_poll_context_t();
int activate(int handle, int enabled);
int setDelay(int handle, int64_t ns);
int pollEvents(sensors_event_t* data, int count);
private:
enum {
light = 0,
proximity = 1,
compass = 2,
gyro = 3,
accel = 4,
pressure = 5,
numSensorDrivers,
numFds,
};
static const size_t wake = numFds - 1;
static const char WAKE_MESSAGE = 'W';
struct pollfd mPollFds[numFds];
int mWritePipeFd;
SensorBase* mSensors[numSensorDrivers];
int handleToDriver(int handle) const {
switch (handle) {
case SENSORS_ACCELERATION_HANDLE:
return accel;
case SENSORS_MAGNETIC_FIELD_HANDLE:
case SENSORS_ORIENTATION_HANDLE:
return compass;
case SENSORS_PROXIMITY_HANDLE:
return proximity;
case SENSORS_LIGHT_HANDLE:
return light;
case SENSORS_GYROSCOPE_HANDLE:
return gyro;
case SENSORS_PRESSURE_HANDLE:
return pressure;
}
return -EINVAL;
}
};
/*****************************************************************************/
sensors_poll_context_t::sensors_poll_context_t()
{
mSensors[light] = new LightSensor();
mPollFds[light].fd = mSensors[light]->getFd();
mPollFds[light].events = POLLIN;
mPollFds[light].revents = 0;
mSensors[proximity] = new ProximitySensor();
mPollFds[proximity].fd = mSensors[proximity]->getFd();
mPollFds[proximity].events = POLLIN;
mPollFds[proximity].revents = 0;
mSensors[compass] = new AkmSensor();
mPollFds[compass].fd = mSensors[compass]->getFd();
mPollFds[compass].events = POLLIN;
mPollFds[compass].revents = 0;
mSensors[gyro] = new GyroSensor();
mPollFds[gyro].fd = mSensors[gyro]->getFd();
mPollFds[gyro].events = POLLIN;
mPollFds[gyro].revents = 0;
mSensors[accel] = new AccelSensor();
mPollFds[accel].fd = mSensors[accel]->getFd();
mPollFds[accel].events = POLLIN;
mPollFds[accel].revents = 0;
mSensors[pressure] = new PressureSensor();
mPollFds[pressure].fd = mSensors[pressure]->getFd();
mPollFds[pressure].events = POLLIN;
mPollFds[pressure].revents = 0;
int wakeFds[2];
int result = pipe(wakeFds);
ALOGE_IF(result<0, "error creating wake pipe (%s)", strerror(errno));
fcntl(wakeFds[0], F_SETFL, O_NONBLOCK);
fcntl(wakeFds[1], F_SETFL, O_NONBLOCK);
mWritePipeFd = wakeFds[1];
mPollFds[wake].fd = wakeFds[0];
mPollFds[wake].events = POLLIN;
mPollFds[wake].revents = 0;
}
sensors_poll_context_t::~sensors_poll_context_t() {
for (int i=0 ; i<numSensorDrivers ; i++) {
delete mSensors[i];
}
close(mPollFds[wake].fd);
close(mWritePipeFd);
}
int sensors_poll_context_t::activate(int handle, int enabled) {
int index = handleToDriver(handle);
if (index < 0) return index;
int err = mSensors[index]->enable(handle, enabled);
if (enabled && !err) {
const char wakeMessage(WAKE_MESSAGE);
int result = write(mWritePipeFd, &wakeMessage, 1);
ALOGE_IF(result<0, "error sending wake message (%s)", strerror(errno));
}
return err;
}
int sensors_poll_context_t::setDelay(int handle, int64_t ns) {
int index = handleToDriver(handle);
if (index < 0) return index;
return mSensors[index]->setDelay(handle, ns);
}
int sensors_poll_context_t::pollEvents(sensors_event_t* data, int count)
{
int nbEvents = 0;
int n = 0;
do {
// see if we have some leftover from the last poll()
for (int i=0 ; count && i<numSensorDrivers ; i++) {
SensorBase* const sensor(mSensors[i]);
if ((mPollFds[i].revents & POLLIN) || (sensor->hasPendingEvents())) {
int nb = sensor->readEvents(data, count);
if (nb < count) {
// no more data for this sensor
mPollFds[i].revents = 0;
}
count -= nb;
nbEvents += nb;
data += nb;
}
}
if (count) {
// we still have some room, so try to see if we can get
// some events immediately or just wait if we don't have
// anything to return
do {
n = poll(mPollFds, numFds, nbEvents ? 0 : -1);
} while (n < 0 && errno == EINTR);
if (n<0) {
ALOGE("poll() failed (%s)", strerror(errno));
return -errno;
}
if (mPollFds[wake].revents & POLLIN) {
char msg;
int result = read(mPollFds[wake].fd, &msg, 1);
ALOGE_IF(result<0, "error reading from wake pipe (%s)", strerror(errno));
ALOGE_IF(msg != WAKE_MESSAGE, "unknown message on wake queue (0x%02x)", int(msg));
mPollFds[wake].revents = 0;
}
}
// if we have events and space, go read them
} while (n && count);
return nbEvents;
}
/*****************************************************************************/
static int poll__close(struct hw_device_t *dev)
{
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
if (ctx) {
delete ctx;
}
return 0;
}
static int poll__activate(struct sensors_poll_device_t *dev,
int handle, int enabled) {
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
return ctx->activate(handle, enabled);
}
static int poll__setDelay(struct sensors_poll_device_t *dev,
int handle, int64_t ns) {
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
return ctx->setDelay(handle, ns);
}
static int poll__poll(struct sensors_poll_device_t *dev,
sensors_event_t* data, int count) {
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
return ctx->pollEvents(data, count);
}
/*****************************************************************************/
/** Open a new instance of a sensor device using name */
static int open_sensors(const struct hw_module_t* module, const char* id,
struct hw_device_t** device)
{
int status = -EINVAL;
sensors_poll_context_t *dev = new sensors_poll_context_t();
memset(&dev->device, 0, sizeof(sensors_poll_device_t));
dev->device.common.tag = HARDWARE_DEVICE_TAG;
dev->device.common.version = 0;
dev->device.common.module = const_cast<hw_module_t*>(module);
dev->device.common.close = poll__close;
dev->device.activate = poll__activate;
dev->device.setDelay = poll__setDelay;
dev->device.poll = poll__poll;
*device = &dev->device.common;
status = 0;
return status;
}
<commit_msg>Sensors: update the sensor list initialization<commit_after>/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "Sensors"
#include <hardware/sensors.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <math.h>
#include <poll.h>
#include <pthread.h>
#include <stdlib.h>
#include <linux/input.h>
#include <utils/Atomic.h>
#include <utils/Log.h>
#include "sensors.h"
#include "AccelSensor.h"
#include "LightSensor.h"
#include "ProximitySensor.h"
#include "AkmSensor.h"
#include "GyroSensor.h"
#include "PressureSensor.h"
/*****************************************************************************/
/* The SENSORS Module */
static const struct sensor_t sSensorList[] = {
/* Accelerometer */
{
"accelerometer",
"ST Micro",
1, /* hw/sw version */
SENSORS_ACCELERATION_HANDLE,
SENSOR_TYPE_ACCELEROMETER,
(2.0f * 9.81f),
(9.81f / 1024),
0.2f, /* mA */
2000, /* microseconds */
0,
0,
{ }
},
/* magnetic field sensor */
{
"AK8975",
"Asahi Kasei Microdevices",
1,
SENSORS_MAGNETIC_FIELD_HANDLE,
SENSOR_TYPE_MAGNETIC_FIELD,
2000.0f,
(1.0f/16.0f),
6.8f,
16667,
0,
0,
{ }
},
/* orientation sensor */
{
"AK8975",
"Asahi Kasei Microdevices",
1,
SENSORS_ORIENTATION_HANDLE,
SENSOR_TYPE_ORIENTATION,
360.0f,
(1.0f/64.0f),
7.8f,
16667 ,
0,
0,
{ }
},
/* light sensor name */
{
"TSL27713FN",
"Taos",
1,
SENSORS_LIGHT_HANDLE,
SENSOR_TYPE_LIGHT,
(powf(10, (280.0f / 47.0f)) * 4),
1.0f,
0.75f,
0,
0,
0,
{ }
},
/* proximity sensor */
{
"TSL27713FN",
"Taos",
1,
SENSORS_PROXIMITY_HANDLE,
SENSOR_TYPE_PROXIMITY,
5.0f,
5.0f,
0.75f,
0,
0,
0,
{ }
},
/* gyro scope */
{
"MPU3050",
"Invensense",
1,
SENSORS_GYROSCOPE_HANDLE,
SENSOR_TYPE_GYROSCOPE,
35.0f,
0.06f,
0.2f,
2000,
0,
0,
{ }
},
/* barometer */
{
"bmp180",
"Bosch",
1,
SENSORS_PRESSURE_HANDLE,
SENSOR_TYPE_PRESSURE,
1100.0f,
0.01f,
0.67f,
20000,
0,
0,
{ }
}
};
static int open_sensors(const struct hw_module_t* module, const char* id,
struct hw_device_t** device);
static int sensors__get_sensors_list(struct sensors_module_t* module,
struct sensor_t const** list)
{
*list = sSensorList;
return ARRAY_SIZE(sSensorList);
}
static struct hw_module_methods_t sensors_module_methods = {
open: open_sensors
};
struct sensors_module_t HAL_MODULE_INFO_SYM = {
common: {
tag: HARDWARE_MODULE_TAG,
version_major: 1,
version_minor: 0,
id: SENSORS_HARDWARE_MODULE_ID,
name: "Quic Sensor module",
author: "Quic",
methods: &sensors_module_methods,
},
get_sensors_list: sensors__get_sensors_list,
};
struct sensors_poll_context_t {
struct sensors_poll_device_t device; // must be first
sensors_poll_context_t();
~sensors_poll_context_t();
int activate(int handle, int enabled);
int setDelay(int handle, int64_t ns);
int pollEvents(sensors_event_t* data, int count);
private:
enum {
light = 0,
proximity = 1,
compass = 2,
gyro = 3,
accel = 4,
pressure = 5,
numSensorDrivers,
numFds,
};
static const size_t wake = numFds - 1;
static const char WAKE_MESSAGE = 'W';
struct pollfd mPollFds[numFds];
int mWritePipeFd;
SensorBase* mSensors[numSensorDrivers];
int handleToDriver(int handle) const {
switch (handle) {
case SENSORS_ACCELERATION_HANDLE:
return accel;
case SENSORS_MAGNETIC_FIELD_HANDLE:
case SENSORS_ORIENTATION_HANDLE:
return compass;
case SENSORS_PROXIMITY_HANDLE:
return proximity;
case SENSORS_LIGHT_HANDLE:
return light;
case SENSORS_GYROSCOPE_HANDLE:
return gyro;
case SENSORS_PRESSURE_HANDLE:
return pressure;
}
return -EINVAL;
}
};
/*****************************************************************************/
sensors_poll_context_t::sensors_poll_context_t()
{
mSensors[light] = new LightSensor();
mPollFds[light].fd = mSensors[light]->getFd();
mPollFds[light].events = POLLIN;
mPollFds[light].revents = 0;
mSensors[proximity] = new ProximitySensor();
mPollFds[proximity].fd = mSensors[proximity]->getFd();
mPollFds[proximity].events = POLLIN;
mPollFds[proximity].revents = 0;
mSensors[compass] = new AkmSensor();
mPollFds[compass].fd = mSensors[compass]->getFd();
mPollFds[compass].events = POLLIN;
mPollFds[compass].revents = 0;
mSensors[gyro] = new GyroSensor();
mPollFds[gyro].fd = mSensors[gyro]->getFd();
mPollFds[gyro].events = POLLIN;
mPollFds[gyro].revents = 0;
mSensors[accel] = new AccelSensor();
mPollFds[accel].fd = mSensors[accel]->getFd();
mPollFds[accel].events = POLLIN;
mPollFds[accel].revents = 0;
mSensors[pressure] = new PressureSensor();
mPollFds[pressure].fd = mSensors[pressure]->getFd();
mPollFds[pressure].events = POLLIN;
mPollFds[pressure].revents = 0;
int wakeFds[2];
int result = pipe(wakeFds);
ALOGE_IF(result<0, "error creating wake pipe (%s)", strerror(errno));
fcntl(wakeFds[0], F_SETFL, O_NONBLOCK);
fcntl(wakeFds[1], F_SETFL, O_NONBLOCK);
mWritePipeFd = wakeFds[1];
mPollFds[wake].fd = wakeFds[0];
mPollFds[wake].events = POLLIN;
mPollFds[wake].revents = 0;
}
sensors_poll_context_t::~sensors_poll_context_t() {
for (int i=0 ; i<numSensorDrivers ; i++) {
delete mSensors[i];
}
close(mPollFds[wake].fd);
close(mWritePipeFd);
}
int sensors_poll_context_t::activate(int handle, int enabled) {
int index = handleToDriver(handle);
if (index < 0) return index;
int err = mSensors[index]->enable(handle, enabled);
if (enabled && !err) {
const char wakeMessage(WAKE_MESSAGE);
int result = write(mWritePipeFd, &wakeMessage, 1);
ALOGE_IF(result<0, "error sending wake message (%s)", strerror(errno));
}
return err;
}
int sensors_poll_context_t::setDelay(int handle, int64_t ns) {
int index = handleToDriver(handle);
if (index < 0) return index;
return mSensors[index]->setDelay(handle, ns);
}
int sensors_poll_context_t::pollEvents(sensors_event_t* data, int count)
{
int nbEvents = 0;
int n = 0;
do {
// see if we have some leftover from the last poll()
for (int i=0 ; count && i<numSensorDrivers ; i++) {
SensorBase* const sensor(mSensors[i]);
if ((mPollFds[i].revents & POLLIN) || (sensor->hasPendingEvents())) {
int nb = sensor->readEvents(data, count);
if (nb < count) {
// no more data for this sensor
mPollFds[i].revents = 0;
}
count -= nb;
nbEvents += nb;
data += nb;
}
}
if (count) {
// we still have some room, so try to see if we can get
// some events immediately or just wait if we don't have
// anything to return
do {
n = poll(mPollFds, numFds, nbEvents ? 0 : -1);
} while (n < 0 && errno == EINTR);
if (n<0) {
ALOGE("poll() failed (%s)", strerror(errno));
return -errno;
}
if (mPollFds[wake].revents & POLLIN) {
char msg;
int result = read(mPollFds[wake].fd, &msg, 1);
ALOGE_IF(result<0, "error reading from wake pipe (%s)", strerror(errno));
ALOGE_IF(msg != WAKE_MESSAGE, "unknown message on wake queue (0x%02x)", int(msg));
mPollFds[wake].revents = 0;
}
}
// if we have events and space, go read them
} while (n && count);
return nbEvents;
}
/*****************************************************************************/
static int poll__close(struct hw_device_t *dev)
{
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
if (ctx) {
delete ctx;
}
return 0;
}
static int poll__activate(struct sensors_poll_device_t *dev,
int handle, int enabled) {
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
return ctx->activate(handle, enabled);
}
static int poll__setDelay(struct sensors_poll_device_t *dev,
int handle, int64_t ns) {
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
return ctx->setDelay(handle, ns);
}
static int poll__poll(struct sensors_poll_device_t *dev,
sensors_event_t* data, int count) {
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
return ctx->pollEvents(data, count);
}
/*****************************************************************************/
/** Open a new instance of a sensor device using name */
static int open_sensors(const struct hw_module_t* module, const char* id,
struct hw_device_t** device)
{
int status = -EINVAL;
sensors_poll_context_t *dev = new sensors_poll_context_t();
memset(&dev->device, 0, sizeof(sensors_poll_device_t));
dev->device.common.tag = HARDWARE_DEVICE_TAG;
dev->device.common.version = 0;
dev->device.common.module = const_cast<hw_module_t*>(module);
dev->device.common.close = poll__close;
dev->device.activate = poll__activate;
dev->device.setDelay = poll__setDelay;
dev->device.poll = poll__poll;
*device = &dev->device.common;
status = 0;
return status;
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#define max_cov 100000
#define CC0 50 // if summary coverage accross the window is 0, we artificially replace it with CC0 value, which should be approximately a half of read length
using namespace std;
int main( int argc , char** argv ) {
cout<<"This program ....\n";
cout<<"Usage: program unionbed_inputfile a A b B v l"<<endl;
if(argc<8) {cout<<"ERROR. unionbed_inputfile a A b B v l"<<endl; return 0;}
int a=0, A=max_cov, b=0, B=max_cov, v=1000, l=0; //!!! Default values for parameters !!!!
char sss[1000], fff[1000];
sprintf(sss,"%s",argv[1]);
cout<<sss<<endl;
std::ifstream unionbed_file( sss ) ;
cout<<"Running program with following parameters:\n";
sprintf(sss,"%s",argv[2]);
a=atoi(sss);
cout<<"Minimum coverage for sample1: a="<<a<<endl;
sprintf(sss,"%s",argv[3]);
A=atoi(sss);
cout<<"Maximum coverage for sample1: A="<<A<<endl;
sprintf(sss,"%s",argv[4]);
b=atoi(sss);
cout<<"Minimum coverage for sample2: b="<<b<<endl;
sprintf(sss,"%s",argv[5]);
B=atoi(sss);
cout<<"Maximum coverage for sample2: B="<<B<<endl;
sprintf(sss,"%s",argv[6]);
v=atoi(sss);
cout<<"Target number of valid bases in the window: v="<<v<<endl;
sprintf(sss,"%s",argv[7]);
l=atoi(sss);
cout<<"minimum size of window to output (window includes valid and non valid bases): l="<<l<<endl;
// DO BETTER INTERFACE with parameter analysis
std::string line;
string scaf = "", scaf_pred= "header_line", begs, ends, cov1s, cov2s, sample1_name, sample2_name;
int beg,end,cov1,cov2, sum1=0, sum2=0, k=0, wb=-1, r=0, window_size=v, linecount=0;
float ratio, av1, av2, av_sum_k1=0, av_sum_k2=0;
sprintf(fff, "%s.ratio_per_w_CC0_a%d_A%d_b%d_B%d_v%d_l%d", "sample1_sample2",a,A,b,B,v,l);
std::ofstream outfile(fff) ;
//read header line from unionbed
getline( unionbed_file , line );
//std::cout << "header line: " << line << endl; //supposing '\n' to be line end
stringstream ss(line);
getline(ss,scaf, '\t');
//cout << "scaf: " << scaf << " scaf_pred: "<<scaf_pred<<endl;
getline(ss,begs, '\t');
beg=atoi(begs.c_str());
getline(ss,ends, '\t');
end=atoi(ends.c_str());
getline(ss,sample1_name, '\t');
cout << "sample1 is "<<sample1_name<<endl;
getline(ss,sample2_name, '\t');
cout << "sample2 is "<< sample2_name<<endl;
//output header line to result file
outfile<<"scaffold\twindow_start\tsize_of_window\tnumber_of_valid_bases_in_window\t"<<sample1_name<<"_av_cov_over_valid_bs\t"<<sample2_name<<"_av_cov_over_valid_bs\tratio=sum_of_cov(sample1)/sum_of_cov(sample2)\n";
if ( unionbed_file ) {
while ( getline( unionbed_file , line ) ) {
//std::cout << linecount << ": " << line << '\n' ;//supposing '\n' to be line end
linecount++ ;
stringstream ss(line);
getline(ss,scaf, '\t');
//cout << "scaf: " << scaf << " scaf_pred: "<<scaf_pred<<endl;
getline(ss,begs, '\t');
beg=atoi(begs.c_str());
getline(ss,ends, '\t');
end=atoi(ends.c_str());
getline(ss,cov1s, '\t');
cov1=atoi(cov1s.c_str());
getline(ss,cov2s, '\t');
cov2=atoi(cov2s.c_str());
//cout << scaf << " " <<beg<<" "<<end<<" "<<cov1<<" "<<cov2<<endl;
if(scaf_pred != scaf)
{
if(sum1 == 0 && sum2 == 0)
{ratio=CC0*10000; //both are equal 0, on case if a>0, b>0 it is impossible, so will mean the ERROR
if(k>0) cout<<"There is a window "<< scaf_pred<<" "<<wb<<" with both samples having 0 coverage and k= "<<k<<endl;
}
else
{
if(sum1 == 0) sum1=(sum2<CC0)?sum2:CC0; // sample1 == 0 and sample2 >= b; but if sum2<CC0, - case of misalignment, or alignment on the flank, better to report equal ratio, as both samples are close to ZERO
if(sum2 == 0) sum2=(sum1<CC0)?sum1:CC0; // sample1 >=a and sample2 == 0
ratio=(float)sum1/sum2;
}
if(k!= 0)
{
av1=av_sum_k1/k;
av2=av_sum_k2/k;
cout <<"NT:"<<scaf_pred<<"\t"<<wb<<"\t"<<k<<"\t"<<sum1<<"\t"<<sum2<<"\t"<<av1<<"\t"<<av2<<"\t"<<ratio<<"\n";
// cout<<"r="<<r<<"\n";
if(r>=l)
// cout<<"rr="<<r<<"\n";
outfile<<scaf_pred<<"\t"<<wb<<"\t"<<r<<"\t"<<k<<"\t"<<av1<<"\t"<<av2<<"\t"<<ratio<<"\n";
}
sum1=0; sum2=0;
av_sum_k1=0; av_sum_k2=0;
k=0;
wb=-1;
r=0;
}//end if(scaf_pred!=scaf)
r+= end-beg;
// cout<<"R="<<r<<"\n";
if(wb == -1) wb=beg;
//at least one sample should have cov > low_limits && both should have coverage < upper limits !!!
if( (cov1>=a || cov2>=b) && (cov1<=A && cov2<=B) ){
k+= end-beg;
sum1+=cov1;
sum2+=cov2;
av_sum_k1+=cov1*(end-beg); av_sum_k2+=cov2*(end-beg);
cout<<"NT3:"<<"sum1="<<sum1<<" sum2="<<sum2<<"\n";
}
if(k>=window_size){
if(sum1 == 0 && sum2 == 0)
{ratio=CC0*10000; //both are equal 0, on case if a>0, b>0 it is impossible, so will mean the ERROR
cout<<"There is a window with both samples having 0 coverage: "<< scaf_pred<<"\t"<<wb<<endl;
}
else
{
if(sum1 == 0) sum1=(sum2<CC0)?sum2:CC0; // sample1 == 0 and sample2 >= b; but if sum2<CC0, - case of misalignment, or alignment on the flank, better to report equal ratio, as both samples are close to ZERO
if(sum2 == 0) sum2=(sum1<CC0)?sum1:CC0; // sample1 >=a and sample2 == 0
ratio=(float)sum1/sum2;
}
//av1=av_sum_k1;
av1=av_sum_k1/k;
av2=av_sum_k2/k;
cout <<"NT1:"<<scaf_pred<<"\t"<<wb<<"\t"<<k<<"\t"<<sum1<<"\t"<<sum2<<"\t"<<av1<<"\t"<<av2<<"\t"<<ratio<<"\n";
if(r>=l) outfile<<scaf_pred<<"\t"<<wb<<"\t"<<r<<"\t"<<k<<"\t"<<av1<<"\t"<<av2<<"\t"<<ratio<<"\n";
sum1=0; sum2=0;
av_sum_k1=0; av_sum_k2=0;
k=0;
wb=-1;
r=0;
}
scaf_pred=scaf;
} //end while
//processing last window in the file
if(sum1 == 0 && sum2 == 0)
{ratio=CC0*10000; //both are equal 0, on case if a>0, b>0 it is impossible, so will mean the ERROR
if(k>0) cout<<"There is a window "<< scaf_pred<<" "<<wb<<" with both samples having 0 coverage and k= "<<k<<endl;
}
else
{
if(sum1 == 0) sum1=(sum2<CC0)?sum2:CC0; // sample1 == 0 and sample2 >= b; but if sum2<CC0, - case of misalignment, or alignment on the flank, better to report equal ratio, as both samples are close to ZERO
if(sum2 == 0) sum2=(sum1<CC0)?sum1:CC0; // sample1 >=a and sample2 == 0
ratio=(float)sum1/sum2;
}
//av1=av_sum_k1/k;
av1=av_sum_k1/k;
av2=av_sum_k2/k;
if(r>=l) outfile<<scaf_pred<<"\t"<<wb<<"\t"<<r<<"\t"<<k<<"\t"<<av1<<"\t"<<av2<<"\t"<<ratio<<"\n";
outfile.close();
unionbed_file.close();
}
else {
/* could not open directory */
perror ("Can't open unionbed file ");
}
return 0 ;
}
<commit_msg>Delete from_unionbed_to_ratio_per_window_CC0.cpp<commit_after><|endoftext|> |
<commit_before>/**
*
* GAMS - General Algebraic Modeling System C++ API
*
* Copyright (c) 2017 GAMS Software GmbH <[email protected]>
* Copyright (c) 2017 GAMS Development Corp. <[email protected]>
*
* 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 "gams.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
using namespace gams;
using namespace std;
string getModelText()
{
return "Sets \n"
" i canning plants \n"
" j markets \n"
" \n"
"Parameters \n"
" a(i) capacity of plant i in cases \n"
" b(j) demand at market j in cases \n"
" d(i,j) distance in thousands of miles \n"
"Scalar f freight in dollars per case per thousand miles; \n"
" \n"
"$if not set gdxincname $abort 'no include file name for data file provided'\n"
"$gdxin %gdxincname% \n"
"$load i j a b d f \n"
"$gdxin \n"
" \n"
" Parameter c(i,j) transport cost in thousands of dollars per case ; \n"
" \n"
" c(i,j) = f * d(i,j) / 1000 ; \n"
" \n"
" Variables \n"
" x(i,j) shipment quantities in cases \n"
" z total transportation costs in thousands of dollars ; \n"
" \n"
" Positive Variable x ; \n"
" \n"
" Equations \n"
" \n"
" cost define objective function \n"
" supply(i) observe supply limit at plant i \n"
" demand(j) satisfy demand at market j ; \n"
" \n"
" cost .. z =e= sum((i,j), c(i,j)*x(i,j)) ; \n"
" \n"
" supply(i) .. sum(j, x(i,j)) =l= a(i) ; \n"
" \n"
" demand(j) .. sum(i, x(i,j)) =g= b(j) ; \n"
" \n"
" Model transport /all/ ; \n"
" \n"
" Solve transport using lp minimizing z ; \n"
" \n"
"Display x.l, x.m ; \n";
}
/// This is the 4th model in a series of tutorial examples. Here we show:
/// - How to define data using C++ data structures
/// - How to prepare a GAMSDatabase from C++ data structures
int main(int argc, char* argv[])
{
cout << "---------- Transport 4 --------------" << endl;
GAMSWorkspaceInfo wsInfo;
if (argc > 1)
wsInfo.setSystemDirectory(argv[1]);
GAMSWorkspace ws(wsInfo);
// define some data by using C++ data structures
vector<string> plants = {
"Seattle", "San-Diego"
};
vector<string> markets = {
"New-York", "Chicago", "Topeka"
};
map<string, double> capacity = {
{ "Seattle", 350.0 }, { "San-Diego", 600.0 }
};
map<string, double> demand = {
{ "New-York", 325.0 }, { "Chicago", 300.0 }, { "Topeka", 275.0 }
};
map<tuple<string, string>, double> distance = {
{ make_tuple("Seattle", "New-York"), 2.5 },
{ make_tuple("Seattle", "Chicago"), 1.7 },
{ make_tuple("Seattle", "Topeka"), 1.8 },
{ make_tuple("San-Diego", "New-York"), 2.5 },
{ make_tuple("San-Diego", "Chicago"), 1.8 },
{ make_tuple("San-Diego", "Topeka"), 1.4 }
};
// prepare a GAMSDatabase with data from the C++ data structures
GAMSDatabase db = ws.addDatabase();
GAMSSet i = db.addSet("i", 1, "canning plants");
for (string p: plants)
i.addRecord(p);
GAMSSet j = db.addSet("j", 1, "markets");
for (string m: markets)
j.addRecord(m);
GAMSParameter a = db.addParameter("a", "capacity of plant i in cases", i);
for (string p: plants)
a.addRecord(p).setValue(capacity[p]);
GAMSParameter b = db.addParameter("b", "demand at market j in cases", j);
for (string m: markets)
b.addRecord(m).setValue(demand[m]);
GAMSParameter d = db.addParameter("d", "distance in thousands of miles", i, j);
for (auto t : distance)
d.addRecord(get<0>(t.first), get<1>(t.first)).setValue(t.second);
GAMSParameter f = db.addParameter("f", "freight in dollars per case per thousand miles");
f.addRecord().setValue(90);
// run a job using data from the created GAMSDatabase
GAMSJob t4 = ws.addJobFromString(getModelText());
GAMSOptions opt = ws.addOptions();
opt.setDefine("gdxincname", db.name());
opt.setAllModelTypes("xpress");
t4.run(opt, db);
for (GAMSVariableRecord rec : t4.outDB().getVariable("x"))
cout << "x(" << rec.key(0) << "," << rec.key(1) << "):" << " level=" << rec.level() << " marginal=" << rec.marginal() << endl;
}
<commit_msg>Transport4 refactorization.<commit_after>/**
*
* GAMS - General Algebraic Modeling System C++ API
*
* Copyright (c) 2017 GAMS Software GmbH <[email protected]>
* Copyright (c) 2017 GAMS Development Corp. <[email protected]>
*
* 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 "gams.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
using namespace gams;
using namespace std;
string getModelText()
{
return "Sets \n"
" i canning plants \n"
" j markets \n"
" \n"
"Parameters \n"
" a(i) capacity of plant i in cases \n"
" b(j) demand at market j in cases \n"
" d(i,j) distance in thousands of miles \n"
"Scalar f freight in dollars per case per thousand miles; \n"
" \n"
"$if not set gdxincname $abort 'no include file name for data file provided'\n"
"$gdxin %gdxincname% \n"
"$load i j a b d f \n"
"$gdxin \n"
" \n"
" Parameter c(i,j) transport cost in thousands of dollars per case ; \n"
" \n"
" c(i,j) = f * d(i,j) / 1000 ; \n"
" \n"
" Variables \n"
" x(i,j) shipment quantities in cases \n"
" z total transportation costs in thousands of dollars ; \n"
" \n"
" Positive Variable x ; \n"
" \n"
" Equations \n"
" \n"
" cost define objective function \n"
" supply(i) observe supply limit at plant i \n"
" demand(j) satisfy demand at market j ; \n"
" \n"
" cost .. z =e= sum((i,j), c(i,j)*x(i,j)) ; \n"
" \n"
" supply(i) .. sum(j, x(i,j)) =l= a(i) ; \n"
" \n"
" demand(j) .. sum(i, x(i,j)) =g= b(j) ; \n"
" \n"
" Model transport /all/ ; \n"
" \n"
" Solve transport using lp minimizing z ; \n"
" \n"
"Display x.l, x.m ; \n";
}
/// This is the 4th model in a series of tutorial examples. Here we show:
/// - How to define data using C++ data structures
/// - How to prepare a GAMSDatabase from C++ data structures
int main(int argc, char* argv[])
{
cout << "---------- Transport 4 --------------" << endl;
GAMSWorkspaceInfo wsInfo;
if (argc > 1)
wsInfo.setSystemDirectory(argv[1]);
GAMSWorkspace ws(wsInfo);
// define some data by using C++ data structures
vector<string> plants = {
"Seattle", "San-Diego"
};
vector<string> markets = {
"New-York", "Chicago", "Topeka"
};
map<string, double> capacity = {
{ "Seattle", 350.0 }, { "San-Diego", 600.0 }
};
map<string, double> demand = {
{ "New-York", 325.0 }, { "Chicago", 300.0 }, { "Topeka", 275.0 }
};
map<tuple<string, string>, double> distance = {
{ make_tuple("Seattle", "New-York"), 2.5 },
{ make_tuple("Seattle", "Chicago"), 1.7 },
{ make_tuple("Seattle", "Topeka"), 1.8 },
{ make_tuple("San-Diego", "New-York"), 2.5 },
{ make_tuple("San-Diego", "Chicago"), 1.8 },
{ make_tuple("San-Diego", "Topeka"), 1.4 }
};
// prepare a GAMSDatabase with data from the C++ data structures
GAMSDatabase db = ws.addDatabase();
GAMSSet i = db.addSet("i", 1, "canning plants");
for (string p: plants)
i.addRecord(p);
GAMSSet j = db.addSet("j", 1, "markets");
for (string m: markets)
j.addRecord(m);
GAMSParameter a = db.addParameter("a", "capacity of plant i in cases", i);
for (string p: plants)
a.addRecord(p).setValue(capacity[p]);
GAMSParameter b = db.addParameter("b", "demand at market j in cases", j);
for (string m: markets)
b.addRecord(m).setValue(demand[m]);
GAMSParameter d = db.addParameter("d", "distance in thousands of miles", i, j);
for (auto t : distance)
d.addRecord(get<0>(t.first), get<1>(t.first)).setValue(t.second);
GAMSParameter f = db.addParameter("f", "freight in dollars per case per thousand miles");
f.addRecord().setValue(90);
// run a job using data from the created GAMSDatabase
GAMSJob t4 = ws.addJobFromString(getModelText());
GAMSOptions opt = ws.addOptions();
opt.setDefine("gdxincname", db.name());
opt.setAllModelTypes("xpress");
t4.run(opt, db);
for (GAMSVariableRecord rec : t4.outDB().getVariable("x"))
cout << "x(" << rec.key(0) << "," << rec.key(1) << "):" << " level=" << rec.level() << " marginal="
<< rec.marginal() << endl;
return 0;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <tuple>
#include <utility>
#include <iostream>
#include "currency.hpp"
#include "server.hpp"
#include "assets.hpp" // For get_default_currency
#include "http.hpp"
#include "date.hpp"
#include "config.hpp"
namespace {
struct currency_cache_key {
std::string date;
std::string from;
std::string to;
currency_cache_key(std::string date, std::string from, std::string to) : date(date), from(from), to(to) {}
friend bool operator<(const currency_cache_key & lhs, const currency_cache_key & rhs){
return std::tie(lhs.date, lhs.from, lhs.to) < std::tie(rhs.date, rhs.from, rhs.to);
}
friend bool operator==(const currency_cache_key & lhs, const currency_cache_key & rhs){
return std::tie(lhs.date, lhs.from, lhs.to) == std::tie(rhs.date, rhs.from, rhs.to);
}
};
std::map<currency_cache_key, double> exchanges;
// V1 is using free.currencyconverterapi.com
double get_rate_v1(const std::string& from, const std::string& to){
httplib::Client cli("free.currencyconverterapi.com", 80);
std::string api_complete = "/api/v3/convert?q=" + from + "_" + to + "&compact=ultra";
auto res = cli.Get(api_complete.c_str());
if (!res) {
std::cout << "Error accessing exchange rates (no response), setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
return 1.0;
} else if (res->status != 200) {
std::cout << "Error accessing exchange rates (not OK), setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
return 1.0;
} else {
auto& buffer = res->body;
if (buffer.find(':') == std::string::npos || buffer.find('}') == std::string::npos) {
std::cout << "Error parsing exchange rates, setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
return 1.0;
} else {
std::string ratio_result(buffer.begin() + buffer.find(':') + 1, buffer.begin() + buffer.find('}'));
return atof(ratio_result.c_str());
}
}
}
// V2 is using api.exchangeratesapi.io
double get_rate_v2(const std::string& from, const std::string& to, const std::string& date = "latest") {
httplib::SSLClient cli("api.exchangeratesapi.io", 443);
std::string api_complete = "/" + date + "?symbols=" + to + "&base=" + from;
auto res = cli.Get(api_complete.c_str());
if (!res) {
std::cout << "ERROR: Currency(v2): No response, setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
std::cout << "ERROR: Currency(v2): URL is " << api_complete << std::endl;
return 1.0;
} else if (res->status != 200) {
std::cout << "ERROR: Currency(v2): Error response " << res->status << ", setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
std::cout << "ERROR: Currency(v2): URL is " << api_complete << std::endl;
std::cout << "ERROR: Currency(v2): Response is " << res->body << std::endl;
return 1.0;
} else {
auto& buffer = res->body;
auto index = "\"" + to + "\":";
if (buffer.find(index) == std::string::npos || buffer.find('}') == std::string::npos) {
std::cout << "ERROR: Currency(v2): Error parsing exchange rates, setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
std::cout << "ERROR: Currency(v2): URL is " << api_complete << std::endl;
std::cout << "ERROR: Currency(v2): Response is " << res->body << std::endl;
return 1.0;
} else {
std::string ratio_result(buffer.begin() + buffer.find(index) + index.size(), buffer.begin() + buffer.find('}'));
return atof(ratio_result.c_str());
}
}
}
} // end of anonymous namespace
void budget::load_currency_cache(){
std::string file_path = budget::path_to_budget_file("currency.cache");
std::ifstream file(file_path);
if (!file.is_open() || !file.good()){
std::cout << "INFO: Impossible to load Currency Cache" << std::endl;
return;
}
std::string line;
while (file.good() && getline(file, line)) {
if (line.empty()) {
continue;
}
auto parts = split(line, ':');
currency_cache_key key(parts[0], parts[1], parts[2]);
exchanges[key] = budget::to_number<double>(parts[3]);
}
if (budget::is_server_running()) {
std::cout << "INFO: Currency Cache has been loaded from " << file_path << std::endl;
std::cout << "INFO: Currency Cache has " << exchanges.size() << " entries " << std::endl;
}
}
void budget::save_currency_cache() {
std::string file_path = budget::path_to_budget_file("currency.cache");
std::ofstream file(file_path);
if (!file.is_open() || !file.good()){
std::cout << "INFO: Impossible to save Currency Cache" << std::endl;
return;
}
for (auto & pair : exchanges) {
if (pair.second != 1.0) {
auto& key = pair.first;
file << key.date << ':' << key.from << ':' << key.to << ':' << pair.second << std::endl;
}
}
if (budget::is_server_running()) {
std::cout << "INFO: Currency Cache has been saved to " << file_path << std::endl;
std::cout << "INFO: Currency Cache has " << exchanges.size() << " entries " << std::endl;
}
}
void budget::refresh_currency_cache(){
// Refresh/Prefetch the current exchange rates
for (auto & pair : exchanges) {
auto& key = pair.first;
exchange_rate(key.from, key.to);
}
if (budget::is_server_running()) {
std::cout << "INFO: Currency Cache has been refreshed" << std::endl;
std::cout << "INFO: Currency Cache has " << exchanges.size() << " entries " << std::endl;
}
}
double budget::exchange_rate(const std::string& from){
return exchange_rate(from, get_default_currency());
}
double budget::exchange_rate(const std::string& from, const std::string& to){
return exchange_rate(from, to, budget::local_day());
}
double budget::exchange_rate(const std::string& from, budget::date d){
return exchange_rate(from, get_default_currency(), d);
}
double budget::exchange_rate(const std::string& from, const std::string& to, budget::date d){
if(from == to){
return 1.0;
} else {
auto date_str = budget::date_to_string(d);
currency_cache_key key(date_str, from, to);
currency_cache_key reverse_key(date_str, to, from);
if (!exchanges.count(key)) {
auto rate = get_rate_v2(from, to, date_str);
if (budget::is_server_running()) {
std::cout << "INFO: Currency: Rate (" << date_str << ")"
<< " from " << from << " to " << to << " = " << rate << std::endl;
}
exchanges[key] = rate;
exchanges[reverse_key] = 1.0 / rate;
}
return exchanges[key];
}
}
<commit_msg>Safety<commit_after>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <tuple>
#include <utility>
#include <iostream>
#include "currency.hpp"
#include "server.hpp"
#include "assets.hpp" // For get_default_currency
#include "http.hpp"
#include "date.hpp"
#include "config.hpp"
namespace {
struct currency_cache_key {
std::string date;
std::string from;
std::string to;
currency_cache_key(std::string date, std::string from, std::string to) : date(date), from(from), to(to) {}
friend bool operator<(const currency_cache_key & lhs, const currency_cache_key & rhs){
return std::tie(lhs.date, lhs.from, lhs.to) < std::tie(rhs.date, rhs.from, rhs.to);
}
friend bool operator==(const currency_cache_key & lhs, const currency_cache_key & rhs){
return std::tie(lhs.date, lhs.from, lhs.to) == std::tie(rhs.date, rhs.from, rhs.to);
}
};
std::map<currency_cache_key, double> exchanges;
// V1 is using free.currencyconverterapi.com
double get_rate_v1(const std::string& from, const std::string& to){
httplib::Client cli("free.currencyconverterapi.com", 80);
std::string api_complete = "/api/v3/convert?q=" + from + "_" + to + "&compact=ultra";
auto res = cli.Get(api_complete.c_str());
if (!res) {
std::cout << "Error accessing exchange rates (no response), setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
return 1.0;
} else if (res->status != 200) {
std::cout << "Error accessing exchange rates (not OK), setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
return 1.0;
} else {
auto& buffer = res->body;
if (buffer.find(':') == std::string::npos || buffer.find('}') == std::string::npos) {
std::cout << "Error parsing exchange rates, setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
return 1.0;
} else {
std::string ratio_result(buffer.begin() + buffer.find(':') + 1, buffer.begin() + buffer.find('}'));
return atof(ratio_result.c_str());
}
}
}
// V2 is using api.exchangeratesapi.io
double get_rate_v2(const std::string& from, const std::string& to, const std::string& date = "latest") {
httplib::SSLClient cli("api.exchangeratesapi.io", 443);
std::string api_complete = "/" + date + "?symbols=" + to + "&base=" + from;
auto res = cli.Get(api_complete.c_str());
if (!res) {
std::cout << "ERROR: Currency(v2): No response, setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
std::cout << "ERROR: Currency(v2): URL is " << api_complete << std::endl;
return 1.0;
} else if (res->status != 200) {
std::cout << "ERROR: Currency(v2): Error response " << res->status << ", setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
std::cout << "ERROR: Currency(v2): URL is " << api_complete << std::endl;
std::cout << "ERROR: Currency(v2): Response is " << res->body << std::endl;
return 1.0;
} else {
auto& buffer = res->body;
auto index = "\"" + to + "\":";
if (buffer.find(index) == std::string::npos || buffer.find('}') == std::string::npos) {
std::cout << "ERROR: Currency(v2): Error parsing exchange rates, setting exchange between " << from << " to " << to << " to 1/1" << std::endl;
std::cout << "ERROR: Currency(v2): URL is " << api_complete << std::endl;
std::cout << "ERROR: Currency(v2): Response is " << res->body << std::endl;
return 1.0;
} else {
std::string ratio_result(buffer.begin() + buffer.find(index) + index.size(), buffer.begin() + buffer.find('}'));
return atof(ratio_result.c_str());
}
}
}
} // end of anonymous namespace
void budget::load_currency_cache(){
std::string file_path = budget::path_to_budget_file("currency.cache");
std::ifstream file(file_path);
if (!file.is_open() || !file.good()){
std::cout << "INFO: Impossible to load Currency Cache" << std::endl;
return;
}
std::string line;
while (file.good() && getline(file, line)) {
if (line.empty()) {
continue;
}
auto parts = split(line, ':');
currency_cache_key key(parts[0], parts[1], parts[2]);
exchanges[key] = budget::to_number<double>(parts[3]);
}
if (budget::is_server_running()) {
std::cout << "INFO: Currency Cache has been loaded from " << file_path << std::endl;
std::cout << "INFO: Currency Cache has " << exchanges.size() << " entries " << std::endl;
}
}
void budget::save_currency_cache() {
std::string file_path = budget::path_to_budget_file("currency.cache");
std::ofstream file(file_path);
if (!file.is_open() || !file.good()){
std::cout << "INFO: Impossible to save Currency Cache" << std::endl;
return;
}
for (auto & pair : exchanges) {
if (pair.second != 1.0) {
auto& key = pair.first;
file << key.date << ':' << key.from << ':' << key.to << ':' << pair.second << std::endl;
}
}
if (budget::is_server_running()) {
std::cout << "INFO: Currency Cache has been saved to " << file_path << std::endl;
std::cout << "INFO: Currency Cache has " << exchanges.size() << " entries " << std::endl;
}
}
void budget::refresh_currency_cache(){
// Refresh/Prefetch the current exchange rates
for (auto & pair : exchanges) {
auto& key = pair.first;
exchange_rate(key.from, key.to);
}
if (budget::is_server_running()) {
std::cout << "INFO: Currency Cache has been refreshed" << std::endl;
std::cout << "INFO: Currency Cache has " << exchanges.size() << " entries " << std::endl;
}
}
double budget::exchange_rate(const std::string& from){
return exchange_rate(from, get_default_currency());
}
double budget::exchange_rate(const std::string& from, const std::string& to){
return exchange_rate(from, to, budget::local_day());
}
double budget::exchange_rate(const std::string& from, budget::date d){
return exchange_rate(from, get_default_currency(), d);
}
double budget::exchange_rate(const std::string& from, const std::string& to, budget::date d){
assert(from != "DESIRED" && to != "DESIRED");
if (from == to) {
return 1.0;
} else {
auto date_str = budget::date_to_string(d);
currency_cache_key key(date_str, from, to);
currency_cache_key reverse_key(date_str, to, from);
if (!exchanges.count(key)) {
auto rate = get_rate_v2(from, to, date_str);
if (budget::is_server_running()) {
std::cout << "INFO: Currency: Rate (" << date_str << ")"
<< " from " << from << " to " << to << " = " << rate << std::endl;
}
exchanges[key] = rate;
exchanges[reverse_key] = 1.0 / rate;
}
return exchanges[key];
}
}
<|endoftext|> |
<commit_before>//=================================================================================================
// Copyright (C) 2016 Olivier Mallet - All Rights Reserved
//=================================================================================================
#include "../include/URT.hpp"
namespace urt {
//=================================================================================================
// parameter constructor for computing ADF test for a given number of lags
template <typename T>
inline ADF<T>::ADF(const Vector<T>& data, int lags, const std::string& trend, bool regression) : ur(data, lags, trend, regression)
{
ur::test_name = _test_name;
ur::valid_trends = _valid_trends;
}
//*************************************************************************************************
// parameter constructor for computing ADF test with lag length optimization
template <typename T>
inline ADF<T>::ADF(const Vector<T>& data, const std::string& method, const std::string& trend, bool regression) : ur(data, method, trend, regression)
{
ur::test_name = _test_name;
ur::valid_trends = _valid_trends;
}
//*************************************************************************************************
// compute test statistic
template <typename T>
inline const T& ADF<T>::statistic()
{
// setting type of lags (if a default type of lags value has been chosen)
ur::set_lags_type();
// setting optimization method
ur::set_method();
// setting number of lags
ur::set_lags();
// setting regression trend
ur::set_trend();
// computing ADF test
ur::compute_adf();
return ur::stat;
}
//*************************************************************************************************
// compute test p-value
template <class T>
inline const T& ADF<T>::pvalue()
{
// computing test statistic
this->statistic();
// setting critical values coefficients pointer
ur::coeff_ptr = &coeff_adf.at(ur::trend);
// computing p-value
ur::pvalue();
return ur::pval;
}
//*************************************************************************************************
// output test results
template <class T>
void ADF<T>::show()
{
// in case user modified test type, for ADF it should always be empty
ur::test_type = std::string();
// computing p-value
this->pvalue();
// outputting results
ur::show();
}
//=================================================================================================
}
<commit_msg>Update ADF.cpp<commit_after>//=================================================================================================
// Copyright (C) 2016 Olivier Mallet - All Rights Reserved
//=================================================================================================
#include "../include/URT.hpp"
namespace urt {
//=================================================================================================
// parameter constructor for computing ADF test for a given number of lags
template <typename T>
inline ADF<T>::ADF(const Vector<T>& data, int lags, const std::string& trend, bool regression) : ur(data, lags, trend, regression)
{
ur::test_name = _test_name;
ur::valid_trends = _valid_trends;
}
//*************************************************************************************************
// parameter constructor for computing ADF test with lag length optimization
template <typename T>
inline ADF<T>::ADF(const Vector<T>& data, const std::string& method, const std::string& trend, bool regression) : ur(data, method, trend, regression)
{
ur::test_name = _test_name;
ur::valid_trends = _valid_trends;
}
//*************************************************************************************************
// compute test statistic
template <typename T>
inline const T& ADF<T>::statistic()
{
// setting type of lags (if a default type of lags value has been chosen)
ur::set_lags_type();
// setting optimization method
ur::set_method();
// setting number of lags
ur::set_lags();
// setting regression trend
ur::set_trend();
// computing ADF test
ur::compute_adf();
return ur::stat;
}
//*************************************************************************************************
// compute test p-value
template <class T>
inline const T& ADF<T>::pvalue()
{
// computing test statistic
this->statistic();
// setting critical values coefficients pointer
ur::coeff_ptr = &coeff_adf.at(ur::trend);
// computing p-value
ur::pvalue();
return ur::pval;
}
//*************************************************************************************************
// output test results
template <class T>
inline void ADF<T>::show()
{
// in case user modified test type, for ADF it should always be empty
ur::test_type = std::string();
// computing p-value
this->pvalue();
// outputting results
ur::show();
}
//=================================================================================================
}
<|endoftext|> |
<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/internal/resumable_upload_session.h"
#include "google/cloud/testing_util/status_matchers.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
namespace {
using ::google::cloud::testing_util::StatusIs;
using ::testing::HasSubstr;
TEST(ResumableUploadResponseTest, Base) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{200,
R"""({"name": "test-object-name"})""",
{{"ignored-header", "value"},
{"location", "location-value"},
{"range", "bytes=0-1999"}}})
.value();
ASSERT_TRUE(actual.payload.has_value());
EXPECT_EQ("test-object-name", actual.payload->name());
EXPECT_EQ("location-value", actual.upload_session_url);
EXPECT_EQ(2000, actual.committed_size);
EXPECT_EQ(ResumableUploadResponse::kDone, actual.upload_state);
std::ostringstream os;
os << actual;
auto actual_str = os.str();
EXPECT_THAT(actual_str, HasSubstr("upload_session_url=location-value"));
EXPECT_THAT(actual_str, HasSubstr("committed_size=2000"));
EXPECT_THAT(actual_str, HasSubstr("annotations="));
}
TEST(ResumableUploadResponseTest, NoLocation) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=0-1999"}}})
.value();
EXPECT_FALSE(actual.payload.has_value());
EXPECT_EQ("", actual.upload_session_url);
EXPECT_EQ(2000, actual.committed_size);
EXPECT_EQ(ResumableUploadResponse::kInProgress, actual.upload_state);
}
TEST(ResumableUploadResponseTest, NoRange) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{201,
R"""({"name": "test-object-name"})""",
{{"location", "location-value"}}})
.value();
ASSERT_TRUE(actual.payload.has_value());
EXPECT_EQ("test-object-name", actual.payload->name());
EXPECT_EQ("location-value", actual.upload_session_url);
EXPECT_FALSE(actual.committed_size.has_value());
EXPECT_EQ(ResumableUploadResponse::kDone, actual.upload_state);
}
TEST(ResumableUploadResponseTest, MissingBytesInRange) {
auto actual = ResumableUploadResponse::FromHttpResponse(HttpResponse{
308, {}, {{"location", "location-value"}, {"range", "units=0-2000"}}});
EXPECT_THAT(actual,
StatusIs(StatusCode::kInternal, HasSubstr("units=0-2000")));
}
TEST(ResumableUploadResponseTest, MissingRangeEnd) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=0-"}}});
EXPECT_THAT(actual, StatusIs(StatusCode::kInternal, HasSubstr("bytes=0-")));
}
TEST(ResumableUploadResponseTest, InvalidRangeEnd) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=0-abcd"}}});
EXPECT_THAT(actual,
StatusIs(StatusCode::kInternal, HasSubstr("bytes=0-abcd")));
}
TEST(ResumableUploadResponseTest, InvalidRangeBegin) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=abcd-2000"}}});
EXPECT_THAT(actual,
StatusIs(StatusCode::kInternal, HasSubstr("bytes=abcd-2000")));
}
TEST(ResumableUploadResponseTest, UnexpectedRangeBegin) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=3000-2000"}}});
EXPECT_THAT(actual,
StatusIs(StatusCode::kInternal, HasSubstr("bytes=3000-2000")));
}
TEST(ResumableUploadResponseTest, NegativeEnd) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=0--7"}}});
EXPECT_THAT(actual, StatusIs(StatusCode::kInternal, HasSubstr("bytes=0--7")));
}
} // namespace
} // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace storage
} // namespace cloud
} // namespace google
<commit_msg>test(storage): fix unsigned vs. signed warnings (#8071)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/internal/resumable_upload_session.h"
#include "google/cloud/testing_util/status_matchers.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
namespace {
using ::google::cloud::testing_util::StatusIs;
using ::testing::HasSubstr;
TEST(ResumableUploadResponseTest, Base) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{200,
R"""({"name": "test-object-name"})""",
{{"ignored-header", "value"},
{"location", "location-value"},
{"range", "bytes=0-1999"}}})
.value();
ASSERT_TRUE(actual.payload.has_value());
EXPECT_EQ("test-object-name", actual.payload->name());
EXPECT_EQ("location-value", actual.upload_session_url);
EXPECT_EQ(2000, actual.committed_size.value_or(0));
EXPECT_EQ(ResumableUploadResponse::kDone, actual.upload_state);
std::ostringstream os;
os << actual;
auto actual_str = os.str();
EXPECT_THAT(actual_str, HasSubstr("upload_session_url=location-value"));
EXPECT_THAT(actual_str, HasSubstr("committed_size=2000"));
EXPECT_THAT(actual_str, HasSubstr("annotations="));
}
TEST(ResumableUploadResponseTest, NoLocation) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=0-1999"}}})
.value();
EXPECT_FALSE(actual.payload.has_value());
EXPECT_EQ("", actual.upload_session_url);
EXPECT_EQ(2000, actual.committed_size.value_or(0));
EXPECT_EQ(ResumableUploadResponse::kInProgress, actual.upload_state);
}
TEST(ResumableUploadResponseTest, NoRange) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{201,
R"""({"name": "test-object-name"})""",
{{"location", "location-value"}}})
.value();
ASSERT_TRUE(actual.payload.has_value());
EXPECT_EQ("test-object-name", actual.payload->name());
EXPECT_EQ("location-value", actual.upload_session_url);
EXPECT_FALSE(actual.committed_size.has_value());
EXPECT_EQ(ResumableUploadResponse::kDone, actual.upload_state);
}
TEST(ResumableUploadResponseTest, MissingBytesInRange) {
auto actual = ResumableUploadResponse::FromHttpResponse(HttpResponse{
308, {}, {{"location", "location-value"}, {"range", "units=0-2000"}}});
EXPECT_THAT(actual,
StatusIs(StatusCode::kInternal, HasSubstr("units=0-2000")));
}
TEST(ResumableUploadResponseTest, MissingRangeEnd) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=0-"}}});
EXPECT_THAT(actual, StatusIs(StatusCode::kInternal, HasSubstr("bytes=0-")));
}
TEST(ResumableUploadResponseTest, InvalidRangeEnd) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=0-abcd"}}});
EXPECT_THAT(actual,
StatusIs(StatusCode::kInternal, HasSubstr("bytes=0-abcd")));
}
TEST(ResumableUploadResponseTest, InvalidRangeBegin) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=abcd-2000"}}});
EXPECT_THAT(actual,
StatusIs(StatusCode::kInternal, HasSubstr("bytes=abcd-2000")));
}
TEST(ResumableUploadResponseTest, UnexpectedRangeBegin) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=3000-2000"}}});
EXPECT_THAT(actual,
StatusIs(StatusCode::kInternal, HasSubstr("bytes=3000-2000")));
}
TEST(ResumableUploadResponseTest, NegativeEnd) {
auto actual = ResumableUploadResponse::FromHttpResponse(
HttpResponse{308, {}, {{"range", "bytes=0--7"}}});
EXPECT_THAT(actual, StatusIs(StatusCode::kInternal, HasSubstr("bytes=0--7")));
}
} // namespace
} // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace storage
} // namespace cloud
} // namespace google
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015-2021 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL 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 <modules/openglqt/shaderwidget.h>
#include <inviwo/core/util/raiiutils.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/colorconversion.h>
#include <modules/opengl/shader/shaderresource.h>
#include <modules/opengl/shader/shadermanager.h>
#include <modules/qtwidgets/syntaxhighlighter.h>
#include <modules/qtwidgets/inviwoqtutils.h>
#include <modules/qtwidgets/codeedit.h>
#include <modules/openglqt/glslsyntaxhighlight.h>
#include <fmt/format.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QToolBar>
#include <QMainWindow>
#include <QMenuBar>
#include <QCloseEvent>
#include <QMessageBox>
#include <QSignalBlocker>
#include <QScrollBar>
#include <warn/pop>
namespace inviwo {
ShaderWidget::ShaderWidget(ShaderObject* obj, QWidget* parent)
: InviwoDockWidget(utilqt::toQString(obj->getFileName()) + "[*]", parent, "ShaderEditorWidget")
, obj_{obj}
, shaderObjOnChange_{obj->onChange([this](ShaderObject*) { shaderObjectChanged(); })} {
setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
resize(utilqt::emToPx(this, QSizeF(50, 70))); // default size
setFloating(true);
setSticky(false);
QMainWindow* mainWindow = new QMainWindow();
mainWindow->setContextMenuPolicy(Qt::NoContextMenu);
QToolBar* toolBar = new QToolBar();
mainWindow->addToolBar(toolBar);
toolBar->setFloatable(false);
toolBar->setMovable(false);
setWidget(mainWindow);
shadercode_ = new CodeEdit{this};
auto settings = InviwoApplication::getPtr()->getSettingsByType<GLSLSyntaxHighlight>();
codeCallbacks_ = utilqt::setGLSLSyntaxHighlight(shadercode_->syntaxHighlighter(), *settings);
shadercode_->setObjectName("shaderwidgetcode");
shadercode_->setPlainText(utilqt::toQString(obj->print(false, false)));
apply_ = toolBar->addAction(QIcon(":/svgicons/run-script.svg"), tr("&Apply Changes"));
apply_->setToolTip(
"Replace the ShaderResource in the shader with a with this content. The "
"changes will only affect this shader and will not be persistent.");
apply_->setShortcut(Qt::CTRL | Qt::Key_R);
apply_->setShortcutContext(Qt::WidgetWithChildrenShortcut);
mainWindow->addAction(apply_);
connect(apply_, &QAction::triggered, this, &ShaderWidget::apply);
save_ = toolBar->addAction(QIcon(":/svgicons/save.svg"), tr("&Save Shader"));
save_->setToolTip(
"If a FileShaderResource saves changes to disk, changes will be persistent "
"and all shaders using the file will be reloaded. If a StringShaderResource "
"updates the string, changes will affect all shaders using the resource but will not be "
"persistent.");
save_->setShortcut(QKeySequence::Save);
save_->setShortcutContext(Qt::WidgetWithChildrenShortcut);
mainWindow->addAction(save_);
connect(save_, &QAction::triggered, this, &ShaderWidget::save);
revert_ = toolBar->addAction(QIcon(":/svgicons/revert.svg"), tr("Revert"));
revert_->setToolTip("Revert changes");
revert_->setShortcutContext(Qt::WidgetWithChildrenShortcut);
revert_->setEnabled(false);
QObject::connect(shadercode_, &QPlainTextEdit::modificationChanged, revert_,
&QAction::setEnabled);
QObject::connect(revert_, &QAction::triggered, this, &ShaderWidget::revert);
QPixmap enabled(":/svgicons/precompiled-enabled.svg");
QPixmap disabled(":/svgicons/precompiled-disabled.svg");
QIcon preicon;
preicon.addPixmap(enabled, QIcon::Normal, QIcon::Off);
preicon.addPixmap(disabled, QIcon::Normal, QIcon::On);
preprocess_ = toolBar->addAction(preicon, "Show Preprocessed Shader");
preprocess_->setChecked(false);
preprocess_->setCheckable(true);
toolBar->addSeparator();
auto undo = toolBar->addAction(QIcon(":/svgicons/undo.svg"), "&Undo");
undo->setShortcut(QKeySequence::Undo);
undo->setEnabled(false);
QObject::connect(undo, &QAction::triggered, this, [this]() { shadercode_->undo(); });
QObject::connect(shadercode_, &QPlainTextEdit::undoAvailable, undo, &QAction::setEnabled);
auto redo = toolBar->addAction(QIcon(":/svgicons/redo.svg"), "&Redo");
redo->setShortcut(QKeySequence::Redo);
redo->setEnabled(false);
QObject::connect(redo, &QAction::triggered, this, [this]() { shadercode_->redo(); });
QObject::connect(shadercode_, &QPlainTextEdit::redoAvailable, redo, &QAction::setEnabled);
QObject::connect(preprocess_, &QAction::toggled, this, [=](bool checked) {
if (checked && shadercode_->document()->isModified()) {
QMessageBox msgBox(
QMessageBox::Question, "Shader Editor", "Do you want to save unsaved changes?",
QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, this);
int retval = msgBox.exec();
if (retval == static_cast<int>(QMessageBox::Save)) {
this->save();
} else if (retval == static_cast<int>(QMessageBox::Cancel)) {
QSignalBlocker block(preprocess_);
preprocess_->setChecked(false);
return;
}
}
updateState();
});
QObject::connect(shadercode_, &QPlainTextEdit::modificationChanged, this,
&QDockWidget::setWindowModified);
shadercode_->installEventFilter(this);
mainWindow->setCentralWidget(shadercode_);
updateState();
loadState();
}
ShaderWidget::~ShaderWidget() = default;
void ShaderWidget::closeEvent(QCloseEvent* event) {
if (shadercode_->document()->isModified()) {
QMessageBox msgBox(QMessageBox::Question, "Shader Editor",
"Do you want to save unsaved changes?",
QMessageBox::Save | QMessageBox::Discard, this);
int retval = msgBox.exec();
if (retval == static_cast<int>(QMessageBox::Save)) {
save();
} else if (retval == static_cast<int>(QMessageBox::Cancel)) {
return;
}
}
InviwoDockWidget::closeEvent(event);
}
bool ShaderWidget::eventFilter(QObject* obj, QEvent* event) {
if (event->type() == QEvent::FocusIn) {
if (fileChangedInBackground_) {
queryReloadFile();
}
return false;
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
}
void ShaderWidget::save() {
ignoreNextUpdate_ = true;
// get the non-const version from the manager.
if (auto resource = ShaderManager::getPtr()->getShaderResource(obj_->getResource()->key())) {
resource->setSource(utilqt::fromQString(shadercode_->toPlainText()));
shadercode_->document()->setModified(false);
} else {
LogWarn(fmt::format(
"Could not save. The ShaderResource \"{}\" was not found in the ShaderManager. It "
"needs to be registered with the ShaderManager for saving to work.",
obj_->getResource()->key()));
}
}
void ShaderWidget::apply() {
ignoreNextUpdate_ = true;
if (!orignal_) {
orignal_ = obj_->getResource();
}
auto tmp = std::make_shared<StringShaderResource>(
"[tmp]", utilqt::fromQString(shadercode_->toPlainText()));
obj_->setResource(tmp);
setWindowTitle("<tmp file>[*]");
revert_->setEnabled(true);
shadercode_->document()->setModified(false);
}
void ShaderWidget::revert() {
if (orignal_) {
ignoreNextUpdate_ = true;
obj_->setResource(orignal_);
setWindowTitle(utilqt::toQString(obj_->getFileName()) + "[*]");
orignal_ = nullptr;
}
updateState();
}
void ShaderWidget::updateState() {
const bool checked = preprocess_->isChecked();
const auto code = obj_->print(false, checked);
const auto vPosition = shadercode_->verticalScrollBar()->value();
const auto hPosition = shadercode_->horizontalScrollBar()->value();
shadercode_->setPlainText(utilqt::toQString(code));
shadercode_->verticalScrollBar()->setValue(vPosition);
shadercode_->horizontalScrollBar()->setValue(hPosition);
if (checked) {
const auto lines = std::count(code.begin(), code.end(), '\n') + 1;
std::string::size_type width = 0;
for (size_t l = 0; l < static_cast<size_t>(lines); ++l) {
auto info = obj_->resolveLine(l);
auto pos = info.first.find_last_of('/');
width = std::max(width, info.first.size() - (pos + 1)); // note string::npos+1==0
}
const auto numberSize = std::to_string(lines).size();
shadercode_->setLineAnnotation([this, width, numberSize](int line) {
const auto&& [tag, num] = obj_->resolveLine(line - 1);
const auto pos = tag.find_last_of('/');
const auto file = std::string_view{tag}.substr(pos + 1);
return fmt::format(FMT_STRING("{0:<{2}}{1:>{3}}"), file, num, width + 1u, numberSize);
});
shadercode_->setAnnotationSpace(
[width, numberSize](int) { return static_cast<int>(width + 1 + numberSize); });
shadercode_->setLineAnnotationColor([this](int line, vec4 org) {
const auto&& [tag, num] = obj_->resolveLine(line - 1);
if (auto pos = tag.find_first_of('['); pos != std::string::npos) {
const auto resource = std::string_view{tag}.substr(0, pos);
auto hsv = color::rgb2hsv(vec3(org));
auto randH = static_cast<double>(std::hash<std::string_view>{}(resource)) /
static_cast<double>(std::numeric_limits<size_t>::max());
auto adjusted =
vec4{color::hsv2rgb(vec3(static_cast<float>(randH), std::max(0.75f, hsv.y),
std::max(0.25f, hsv.z))),
org.w};
return adjusted;
} else {
return org;
}
});
} else {
shadercode_->setLineAnnotation([](int line) { return std::to_string(line); });
shadercode_->setLineAnnotationColor([](int, vec4 org) { return org; });
shadercode_->setAnnotationSpace([](int maxDigits) { return maxDigits; });
}
shadercode_->setReadOnly(checked);
save_->setEnabled(!checked);
apply_->setEnabled(!checked);
preprocess_->setText(checked ? "Show Plain Shader Only" : "Show Preprocessed Shader");
shadercode_->document()->setModified(false);
}
inline void ShaderWidget::queryReloadFile() {
if (preprocess_->isChecked()) {
util::KeepTrueWhileInScope guard{&reloadQueryInProgress_};
updateState();
fileChangedInBackground_ = false;
return;
}
auto children = findChildren<QWidget*>();
auto focus =
std::any_of(children.begin(), children.end(), [](auto w) { return w->hasFocus(); });
if (focus && fileChangedInBackground_ && !reloadQueryInProgress_) {
util::KeepTrueWhileInScope guard{&reloadQueryInProgress_};
std::string msg =
"The shader source has been modified, do you want to reload its content?";
QMessageBox msgBox(QMessageBox::Question, "Shader Editor", utilqt::toQString(msg),
QMessageBox::Yes | QMessageBox::No, this);
msgBox.setWindowModality(Qt::WindowModal);
if (msgBox.exec() == QMessageBox::Yes) {
updateState();
} else {
shadercode_->document()->setModified(true);
}
fileChangedInBackground_ = false;
}
}
void ShaderWidget::shaderObjectChanged() {
if (ignoreNextUpdate_) {
ignoreNextUpdate_ = false;
return;
}
fileChangedInBackground_ = true;
queryReloadFile();
}
} // namespace inviwo
<commit_msg>Typo: Format<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015-2021 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL 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 <modules/openglqt/shaderwidget.h>
#include <inviwo/core/util/raiiutils.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/colorconversion.h>
#include <modules/opengl/shader/shaderresource.h>
#include <modules/opengl/shader/shadermanager.h>
#include <modules/qtwidgets/syntaxhighlighter.h>
#include <modules/qtwidgets/inviwoqtutils.h>
#include <modules/qtwidgets/codeedit.h>
#include <modules/openglqt/glslsyntaxhighlight.h>
#include <fmt/format.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QToolBar>
#include <QMainWindow>
#include <QMenuBar>
#include <QCloseEvent>
#include <QMessageBox>
#include <QSignalBlocker>
#include <QScrollBar>
#include <warn/pop>
namespace inviwo {
ShaderWidget::ShaderWidget(ShaderObject* obj, QWidget* parent)
: InviwoDockWidget(utilqt::toQString(obj->getFileName()) + "[*]", parent, "ShaderEditorWidget")
, obj_{obj}
, shaderObjOnChange_{obj->onChange([this](ShaderObject*) { shaderObjectChanged(); })} {
setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
resize(utilqt::emToPx(this, QSizeF(50, 70))); // default size
setFloating(true);
setSticky(false);
QMainWindow* mainWindow = new QMainWindow();
mainWindow->setContextMenuPolicy(Qt::NoContextMenu);
QToolBar* toolBar = new QToolBar();
mainWindow->addToolBar(toolBar);
toolBar->setFloatable(false);
toolBar->setMovable(false);
setWidget(mainWindow);
shadercode_ = new CodeEdit{this};
auto settings = InviwoApplication::getPtr()->getSettingsByType<GLSLSyntaxHighlight>();
codeCallbacks_ = utilqt::setGLSLSyntaxHighlight(shadercode_->syntaxHighlighter(), *settings);
shadercode_->setObjectName("shaderwidgetcode");
shadercode_->setPlainText(utilqt::toQString(obj->print(false, false)));
apply_ = toolBar->addAction(QIcon(":/svgicons/run-script.svg"), tr("&Apply Changes"));
apply_->setToolTip(
"Replace the ShaderResource in the shader with a with this content. The "
"changes will only affect this shader and will not be persistent.");
apply_->setShortcut(Qt::CTRL | Qt::Key_R);
apply_->setShortcutContext(Qt::WidgetWithChildrenShortcut);
mainWindow->addAction(apply_);
connect(apply_, &QAction::triggered, this, &ShaderWidget::apply);
save_ = toolBar->addAction(QIcon(":/svgicons/save.svg"), tr("&Save Shader"));
save_->setToolTip(
"If a FileShaderResource saves changes to disk, changes will be persistent "
"and all shaders using the file will be reloaded. If a StringShaderResource "
"updates the string, changes will affect all shaders using the resource but will not be "
"persistent.");
save_->setShortcut(QKeySequence::Save);
save_->setShortcutContext(Qt::WidgetWithChildrenShortcut);
mainWindow->addAction(save_);
connect(save_, &QAction::triggered, this, &ShaderWidget::save);
revert_ = toolBar->addAction(QIcon(":/svgicons/revert.svg"), tr("Revert"));
revert_->setToolTip("Revert changes");
revert_->setShortcutContext(Qt::WidgetWithChildrenShortcut);
revert_->setEnabled(false);
QObject::connect(shadercode_, &QPlainTextEdit::modificationChanged, revert_,
&QAction::setEnabled);
QObject::connect(revert_, &QAction::triggered, this, &ShaderWidget::revert);
QPixmap enabled(":/svgicons/precompiled-enabled.svg");
QPixmap disabled(":/svgicons/precompiled-disabled.svg");
QIcon preicon;
preicon.addPixmap(enabled, QIcon::Normal, QIcon::Off);
preicon.addPixmap(disabled, QIcon::Normal, QIcon::On);
preprocess_ = toolBar->addAction(preicon, "Show Preprocessed Shader");
preprocess_->setChecked(false);
preprocess_->setCheckable(true);
toolBar->addSeparator();
auto undo = toolBar->addAction(QIcon(":/svgicons/undo.svg"), "&Undo");
undo->setShortcut(QKeySequence::Undo);
undo->setEnabled(false);
QObject::connect(undo, &QAction::triggered, this, [this]() { shadercode_->undo(); });
QObject::connect(shadercode_, &QPlainTextEdit::undoAvailable, undo, &QAction::setEnabled);
auto redo = toolBar->addAction(QIcon(":/svgicons/redo.svg"), "&Redo");
redo->setShortcut(QKeySequence::Redo);
redo->setEnabled(false);
QObject::connect(redo, &QAction::triggered, this, [this]() { shadercode_->redo(); });
QObject::connect(shadercode_, &QPlainTextEdit::redoAvailable, redo, &QAction::setEnabled);
QObject::connect(preprocess_, &QAction::toggled, this, [=](bool checked) {
if (checked && shadercode_->document()->isModified()) {
QMessageBox msgBox(
QMessageBox::Question, "Shader Editor", "Do you want to save unsaved changes?",
QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, this);
int retval = msgBox.exec();
if (retval == static_cast<int>(QMessageBox::Save)) {
this->save();
} else if (retval == static_cast<int>(QMessageBox::Cancel)) {
QSignalBlocker block(preprocess_);
preprocess_->setChecked(false);
return;
}
}
updateState();
});
QObject::connect(shadercode_, &QPlainTextEdit::modificationChanged, this,
&QDockWidget::setWindowModified);
shadercode_->installEventFilter(this);
mainWindow->setCentralWidget(shadercode_);
updateState();
loadState();
}
ShaderWidget::~ShaderWidget() = default;
void ShaderWidget::closeEvent(QCloseEvent* event) {
if (shadercode_->document()->isModified()) {
QMessageBox msgBox(QMessageBox::Question, "Shader Editor",
"Do you want to save unsaved changes?",
QMessageBox::Save | QMessageBox::Discard, this);
int retval = msgBox.exec();
if (retval == static_cast<int>(QMessageBox::Save)) {
save();
} else if (retval == static_cast<int>(QMessageBox::Cancel)) {
return;
}
}
InviwoDockWidget::closeEvent(event);
}
bool ShaderWidget::eventFilter(QObject* obj, QEvent* event) {
if (event->type() == QEvent::FocusIn) {
if (fileChangedInBackground_) {
queryReloadFile();
}
return false;
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
}
void ShaderWidget::save() {
ignoreNextUpdate_ = true;
// get the non-const version from the manager.
if (auto resource = ShaderManager::getPtr()->getShaderResource(obj_->getResource()->key())) {
resource->setSource(utilqt::fromQString(shadercode_->toPlainText()));
shadercode_->document()->setModified(false);
} else {
LogWarn(fmt::format(
"Could not save. The ShaderResource \"{}\" was not found in the ShaderManager. It "
"needs to be registered with the ShaderManager for saving to work.",
obj_->getResource()->key()));
}
}
void ShaderWidget::apply() {
ignoreNextUpdate_ = true;
if (!orignal_) {
orignal_ = obj_->getResource();
}
auto tmp = std::make_shared<StringShaderResource>(
"[tmp]", utilqt::fromQString(shadercode_->toPlainText()));
obj_->setResource(tmp);
setWindowTitle("<tmp file>[*]");
revert_->setEnabled(true);
shadercode_->document()->setModified(false);
}
void ShaderWidget::revert() {
if (orignal_) {
ignoreNextUpdate_ = true;
obj_->setResource(orignal_);
setWindowTitle(utilqt::toQString(obj_->getFileName()) + "[*]");
orignal_ = nullptr;
}
updateState();
}
void ShaderWidget::updateState() {
const bool checked = preprocess_->isChecked();
const auto code = obj_->print(false, checked);
const auto vPosition = shadercode_->verticalScrollBar()->value();
const auto hPosition = shadercode_->horizontalScrollBar()->value();
shadercode_->setPlainText(utilqt::toQString(code));
shadercode_->verticalScrollBar()->setValue(vPosition);
shadercode_->horizontalScrollBar()->setValue(hPosition);
if (checked) {
const auto lines = std::count(code.begin(), code.end(), '\n') + 1;
std::string::size_type width = 0;
for (size_t l = 0; l < static_cast<size_t>(lines); ++l) {
auto info = obj_->resolveLine(l);
auto pos = info.first.find_last_of('/');
width = std::max(width, info.first.size() - (pos + 1)); // note string::npos+1==0
}
const auto numberSize = std::to_string(lines).size();
shadercode_->setLineAnnotation([this, width, numberSize](int line) {
const auto&& [tag, num] = obj_->resolveLine(line - 1);
const auto pos = tag.find_last_of('/');
const auto file = std::string_view{tag}.substr(pos + 1);
return fmt::format(FMT_STRING("{0:<{2}}{1:>{3}}"), file, num, width + 1u, numberSize);
});
shadercode_->setAnnotationSpace(
[width, numberSize](int) { return static_cast<int>(width + 1 + numberSize); });
shadercode_->setLineAnnotationColor([this](int line, vec4 org) {
const auto&& [tag, num] = obj_->resolveLine(line - 1);
if (auto pos = tag.find_first_of('['); pos != std::string::npos) {
const auto resource = std::string_view{tag}.substr(0, pos);
auto hsv = color::rgb2hsv(vec3(org));
auto randH = static_cast<double>(std::hash<std::string_view>{}(resource)) /
static_cast<double>(std::numeric_limits<size_t>::max());
auto adjusted =
vec4{color::hsv2rgb(vec3(static_cast<float>(randH), std::max(0.75f, hsv.y),
std::max(0.25f, hsv.z))),
org.w};
return adjusted;
} else {
return org;
}
});
} else {
shadercode_->setLineAnnotation([](int line) { return std::to_string(line); });
shadercode_->setLineAnnotationColor([](int, vec4 org) { return org; });
shadercode_->setAnnotationSpace([](int maxDigits) { return maxDigits; });
}
shadercode_->setReadOnly(checked);
save_->setEnabled(!checked);
apply_->setEnabled(!checked);
preprocess_->setText(checked ? "Show Plain Shader Only" : "Show Preprocessed Shader");
shadercode_->document()->setModified(false);
}
inline void ShaderWidget::queryReloadFile() {
if (preprocess_->isChecked()) {
util::KeepTrueWhileInScope guard{&reloadQueryInProgress_};
updateState();
fileChangedInBackground_ = false;
return;
}
auto children = findChildren<QWidget*>();
auto focus =
std::any_of(children.begin(), children.end(), [](auto w) { return w->hasFocus(); });
if (focus && fileChangedInBackground_ && !reloadQueryInProgress_) {
util::KeepTrueWhileInScope guard{&reloadQueryInProgress_};
std::string msg = "The shader source has been modified, do you want to reload its content?";
QMessageBox msgBox(QMessageBox::Question, "Shader Editor", utilqt::toQString(msg),
QMessageBox::Yes | QMessageBox::No, this);
msgBox.setWindowModality(Qt::WindowModal);
if (msgBox.exec() == QMessageBox::Yes) {
updateState();
} else {
shadercode_->document()->setModified(true);
}
fileChangedInBackground_ = false;
}
}
void ShaderWidget::shaderObjectChanged() {
if (ignoreNextUpdate_) {
ignoreNextUpdate_ = false;
return;
}
fileChangedInBackground_ = true;
queryReloadFile();
}
} // namespace inviwo
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <chrono>
#include <vector>
#include <folly/DynamicConverter.h>
#include <gtest/gtest.h>
#include <wangle/client/ssl/SSLSession.h>
#include <wangle/client/ssl/SSLSessionCacheData.h>
#include <wangle/client/ssl/SSLSessionCacheUtils.h>
#include <wangle/client/ssl/test/TestUtil.h>
#include <wangle/ssl/SSLUtil.h>
using namespace std::chrono;
using namespace testing;
using namespace wangle;
using SSLCtxDeleter = folly::static_function_deleter<SSL_CTX, &SSL_CTX_free>;
using SSLCtxPtr = std::unique_ptr<SSL_CTX, SSLCtxDeleter>;
class SSLSessionCacheDataTest : public Test {
public:
void SetUp() override {
sessions_ = getSessions();
}
void TearDown() override {
for (const auto& it : sessions_) {
SSL_SESSION_free(it.first);
}
sessions_.clear();
}
protected:
std::vector<std::pair<SSL_SESSION*, size_t>> sessions_;
};
TEST_F(SSLSessionCacheDataTest, Basic) {
SSLSessionCacheData data;
data.sessionData = folly::fbstring("some session data");
data.addedTime = system_clock::now();
data.serviceIdentity = "some service";
auto d = folly::toDynamic(data);
auto deserializedData = folly::convertTo<SSLSessionCacheData>(d);
EXPECT_EQ(deserializedData.sessionData, data.sessionData);
EXPECT_EQ(deserializedData.addedTime, data.addedTime);
EXPECT_EQ(deserializedData.serviceIdentity, data.serviceIdentity);
}
TEST_F(SSLSessionCacheDataTest, CloneSSLSession) {
for (auto& it : sessions_) {
auto sess = SSLSessionPtr(cloneSSLSession(it.first));
EXPECT_TRUE(sess);
}
}
TEST_F(SSLSessionCacheDataTest, ServiceIdentity) {
auto sessionPtr = SSLSessionPtr(cloneSSLSession(sessions_[0].first));
auto session = sessionPtr.get();
auto ident = getSessionServiceIdentity(session);
EXPECT_FALSE(ident);
std::string id("serviceId");
EXPECT_TRUE(setSessionServiceIdentity(session, id));
ident = getSessionServiceIdentity(session);
EXPECT_TRUE(ident);
EXPECT_EQ(ident.value(), id);
auto cloned = SSLSessionPtr(session);
EXPECT_TRUE(cloned);
ident = getSessionServiceIdentity(cloned.get());
EXPECT_TRUE(ident);
EXPECT_EQ(ident.value(), id);
auto cacheDataOpt = getCacheDataForSession(session);
EXPECT_TRUE(cacheDataOpt);
auto& cacheData = cacheDataOpt.value();
EXPECT_EQ(id, cacheData.serviceIdentity);
auto deserialized = SSLSessionPtr(getSessionFromCacheData(cacheData));
EXPECT_TRUE(deserialized);
ident = getSessionServiceIdentity(deserialized.get());
EXPECT_TRUE(ident);
EXPECT_EQ(ident.value(), id);
}
<commit_msg>Fix failing buck clang asan<commit_after>/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <chrono>
#include <vector>
#include <folly/DynamicConverter.h>
#include <gtest/gtest.h>
#include <wangle/client/ssl/SSLSession.h>
#include <wangle/client/ssl/SSLSessionCacheData.h>
#include <wangle/client/ssl/SSLSessionCacheUtils.h>
#include <wangle/client/ssl/test/TestUtil.h>
#include <wangle/ssl/SSLUtil.h>
using namespace std::chrono;
using namespace testing;
using namespace wangle;
using SSLCtxDeleter = folly::static_function_deleter<SSL_CTX, &SSL_CTX_free>;
using SSLCtxPtr = std::unique_ptr<SSL_CTX, SSLCtxDeleter>;
class SSLSessionCacheDataTest : public Test {
public:
void SetUp() override {
sessions_ = getSessions();
}
void TearDown() override {
for (const auto& it : sessions_) {
SSL_SESSION_free(it.first);
}
sessions_.clear();
}
protected:
std::vector<std::pair<SSL_SESSION*, size_t>> sessions_;
};
TEST_F(SSLSessionCacheDataTest, Basic) {
SSLSessionCacheData data;
data.sessionData = folly::fbstring("some session data");
data.addedTime = system_clock::now();
data.serviceIdentity = "some service";
auto d = folly::toDynamic(data);
auto deserializedData = folly::convertTo<SSLSessionCacheData>(d);
EXPECT_EQ(deserializedData.sessionData, data.sessionData);
EXPECT_EQ(deserializedData.addedTime, data.addedTime);
EXPECT_EQ(deserializedData.serviceIdentity, data.serviceIdentity);
}
TEST_F(SSLSessionCacheDataTest, CloneSSLSession) {
for (auto& it : sessions_) {
auto sess = SSLSessionPtr(cloneSSLSession(it.first));
EXPECT_TRUE(sess);
}
}
TEST_F(SSLSessionCacheDataTest, ServiceIdentity) {
auto sessionPtr = SSLSessionPtr(cloneSSLSession(sessions_[0].first));
auto session = sessionPtr.get();
auto ident = getSessionServiceIdentity(session);
EXPECT_FALSE(ident);
std::string id("serviceId");
EXPECT_TRUE(setSessionServiceIdentity(session, id));
ident = getSessionServiceIdentity(session);
EXPECT_TRUE(ident);
EXPECT_EQ(ident.value(), id);
auto cloned = SSLSessionPtr(cloneSSLSession(session));
EXPECT_TRUE(cloned);
ident = getSessionServiceIdentity(cloned.get());
EXPECT_TRUE(ident);
EXPECT_EQ(ident.value(), id);
auto cacheDataOpt = getCacheDataForSession(session);
EXPECT_TRUE(cacheDataOpt);
auto& cacheData = cacheDataOpt.value();
EXPECT_EQ(id, cacheData.serviceIdentity);
auto deserialized = SSLSessionPtr(getSessionFromCacheData(cacheData));
EXPECT_TRUE(deserialized);
ident = getSessionServiceIdentity(deserialized.get());
EXPECT_TRUE(ident);
EXPECT_EQ(ident.value(), id);
}
<|endoftext|> |
<commit_before>#include "assets.gen.h"
#include "coders_crux.gen.h"
#include "Element.h"
#include "ElementCube.h"
#include "periodic.h"
#include <sifteo.h>
using namespace Sifteo;
#define NUM_CUBES 3
#define MAX_REACTION_SIZE 3
static Metadata M = Metadata()
.title("Periodic Project")
.package("edu.ksu.periodic", "0.1")
.icon(Icon)
.cubeRange(NUM_CUBES)
;
//! Array of the ElementCube instances used in this program. There should be one for every cube in the simulation.
ElementCube cubes[NUM_CUBES] =
{
ElementCube(0, "H"),
ElementCube(1, "Be"),
ElementCube(2, "H")
};
//! Internal accounting for OnTouch, used to separate presses from releases.
static bool isRelease[CUBE_ALLOCATION];//TODO: Investigate if this should be initialized with CubeID.isTouch on startup.
//! Counts the number of neighbors in the given neighborhood
int CountNeighbors(Neighborhood* nh);
//! Returns true if elementCube is found in the specified reactants array of size numReactants
bool IsReactant(ElementCube** reactants, int numReactants, ElementCube* elementCube);
//! This function recursively walks all cubes currently touching or indirectly touching the specified root cube and adds them to the speicifed reactants array.
//! The size of the reactants array must be at least MAX_REACTION_SIZE, the used size will be placed in numReactants.
void FindReactants(ElementCube** reactants, int* numReactants, ElementCube* root);
//! Processes the entire Sifteo Cube neighborhood and handles any reactions present in it
void ProcessNeighborhood();
//! Called when a specific cube is pressed (as in, touched after not being touched.)
void OnPress(unsigned cubeId);
//! Called when a specific cube is released (as in, not touched after being touched.)
void OnRelease(unsigned cubeId);
//! Raw Sifteo event handler for OnTocuh, you probably want to use OnPress and OnRelease instead.
void OnTouch(void* sender, unsigned cubeId);
//! Raw Sifteo event handler used to process cubes touching
void OnNeighborAdd(void* sender, unsigned firstId, unsigned firstSide, unsigned secondId, unsigned secondSide);
//! Raw Sifteo event handler used to process cubes untouching
void OnNeighborRemove(void* sender, unsigned firstId, unsigned firstSide, unsigned secondId, unsigned secondSide);
//! Program entry-point, initializes all state and event handlers, and handles the main program loop
void main()
{
Events::cubeTouch.set(OnTouch);
Events::neighborAdd.set(OnNeighborAdd);
Events::neighborRemove.set(OnNeighborRemove);
TimeStep timeStep;
while (1)
{
for (unsigned i = 0; i < NUM_CUBES; i++)
{
cubes[i].Render();
}
System::paint();
timeStep.next();
}
}
int CountNeighbors(Neighborhood* nh)
{
int ret = 0;
for (int i = 0; i < NUM_SIDES; i++)
{
if (nh->hasCubeAt((Side)i))
{
ret++;
}
}
return ret;
}
bool IsReactant(ElementCube** reactants, int numReactants, ElementCube* elementCube)
{
for (int i = 0; i < numReactants; i++)
{
if (reactants[i] == elementCube)
{
return true;
}
}
return false;
}
void FindReactants(ElementCube** reactants, int* numReactants, ElementCube* root)
{
LOG("Adding %d to reactant collection.\n", root->GetCubeId());
reactants[*numReactants] = root;
(*numReactants)++;
Neighborhood nh(root->GetCubeId());
for (int i = 0; i < NUM_SIDES; i++)
{
if (nh.hasNeighborAt((Side)i))
{
ElementCube* neighbor = &cubes[nh.cubeAt((Side)i)];
// If this neighbor isn't already in the reactant collection, we search it too.
if (!IsReactant(reactants, *numReactants, neighbor))
{ FindReactants(reactants, numReactants, neighbor); }
}
}
}
void ProcessNeighborhood()
{
// Reset all of the cubes:
for (int i = 0; i < NUM_CUBES; i++)
{ cubes[i].ResetElement(); }
//TODO: Currently only handles a single reaction. (IE: You can't use 8 cubes and make two separate reactions.)
// Look or a cube that has neighbors
int rootCube = -1;
for (int i = 0; i < NUM_CUBES; i++)
{
Neighborhood nh(i);
int numNeighbors = CountNeighbors(&nh);
if (numNeighbors == 0)
{
continue;
}
rootCube = i;
LOG("Cube #%d with %d neighbors chosen as root of reaction\n", i, numNeighbors);
break;
}
// No reaction
if (rootCube == -1)
{
return;
}
// Find all cubes in reaction:
ElementCube* reactants[MAX_REACTION_SIZE];
int numReactants = 0;
FindReactants(reactants, &numReactants, &cubes[rootCube]);
LOG("Got %d reactants.\n", numReactants);
if (numReactants == 3)
{
reactants[0]->ReactWith(reactants[1], reactants[2]);
}
else if (numReactants == 2)
{
reactants[0]->ReactWith(reactants[1]);
}
else
{
// Currently this is an unexpected condition
ASSERT(false);
}
}
void OnPress(unsigned cubeId)
{
}
void OnRelease(unsigned cubeId)
{
LOG("Going to next elemenet on cube %d.\n", cubeId);
// Move the tapped cube to the next element
cubes[cubeId].GoToNextElement();
ProcessNeighborhood();
}
void OnTouch(void* sender, unsigned cubeId)
{
if (isRelease[cubeId])
{
OnRelease(cubeId);
}
else
{
OnPress(cubeId);
}
isRelease[cubeId] = !isRelease[cubeId];//Next touch event on this cube will be a release event
}
void OnNeighborAdd(void* sender, unsigned firstId, unsigned firstSide, unsigned secondId, unsigned secondSide)
{
ProcessNeighborhood();
}
void OnNeighborRemove(void* sender, unsigned firstId, unsigned firstSide, unsigned secondId, unsigned secondSide)
{
ProcessNeighborhood();
}
<commit_msg>Bumped version number.<commit_after>#include "assets.gen.h"
#include "coders_crux.gen.h"
#include "Element.h"
#include "ElementCube.h"
#include "periodic.h"
#include <sifteo.h>
using namespace Sifteo;
#define NUM_CUBES 3
#define MAX_REACTION_SIZE 3
static Metadata M = Metadata()
.title("Periodic Project")
.package("edu.ksu.periodic", "0.2")
.icon(Icon)
.cubeRange(NUM_CUBES)
;
//! Array of the ElementCube instances used in this program. There should be one for every cube in the simulation.
ElementCube cubes[NUM_CUBES] =
{
ElementCube(0, "H"),
ElementCube(1, "Be"),
ElementCube(2, "H")
};
//! Internal accounting for OnTouch, used to separate presses from releases.
static bool isRelease[CUBE_ALLOCATION];//TODO: Investigate if this should be initialized with CubeID.isTouch on startup.
//! Counts the number of neighbors in the given neighborhood
int CountNeighbors(Neighborhood* nh);
//! Returns true if elementCube is found in the specified reactants array of size numReactants
bool IsReactant(ElementCube** reactants, int numReactants, ElementCube* elementCube);
//! This function recursively walks all cubes currently touching or indirectly touching the specified root cube and adds them to the speicifed reactants array.
//! The size of the reactants array must be at least MAX_REACTION_SIZE, the used size will be placed in numReactants.
void FindReactants(ElementCube** reactants, int* numReactants, ElementCube* root);
//! Processes the entire Sifteo Cube neighborhood and handles any reactions present in it
void ProcessNeighborhood();
//! Called when a specific cube is pressed (as in, touched after not being touched.)
void OnPress(unsigned cubeId);
//! Called when a specific cube is released (as in, not touched after being touched.)
void OnRelease(unsigned cubeId);
//! Raw Sifteo event handler for OnTocuh, you probably want to use OnPress and OnRelease instead.
void OnTouch(void* sender, unsigned cubeId);
//! Raw Sifteo event handler used to process cubes touching
void OnNeighborAdd(void* sender, unsigned firstId, unsigned firstSide, unsigned secondId, unsigned secondSide);
//! Raw Sifteo event handler used to process cubes untouching
void OnNeighborRemove(void* sender, unsigned firstId, unsigned firstSide, unsigned secondId, unsigned secondSide);
//! Program entry-point, initializes all state and event handlers, and handles the main program loop
void main()
{
Events::cubeTouch.set(OnTouch);
Events::neighborAdd.set(OnNeighborAdd);
Events::neighborRemove.set(OnNeighborRemove);
TimeStep timeStep;
while (1)
{
for (unsigned i = 0; i < NUM_CUBES; i++)
{
cubes[i].Render();
}
System::paint();
timeStep.next();
}
}
int CountNeighbors(Neighborhood* nh)
{
int ret = 0;
for (int i = 0; i < NUM_SIDES; i++)
{
if (nh->hasCubeAt((Side)i))
{
ret++;
}
}
return ret;
}
bool IsReactant(ElementCube** reactants, int numReactants, ElementCube* elementCube)
{
for (int i = 0; i < numReactants; i++)
{
if (reactants[i] == elementCube)
{
return true;
}
}
return false;
}
void FindReactants(ElementCube** reactants, int* numReactants, ElementCube* root)
{
LOG("Adding %d to reactant collection.\n", root->GetCubeId());
reactants[*numReactants] = root;
(*numReactants)++;
Neighborhood nh(root->GetCubeId());
for (int i = 0; i < NUM_SIDES; i++)
{
if (nh.hasNeighborAt((Side)i))
{
ElementCube* neighbor = &cubes[nh.cubeAt((Side)i)];
// If this neighbor isn't already in the reactant collection, we search it too.
if (!IsReactant(reactants, *numReactants, neighbor))
{ FindReactants(reactants, numReactants, neighbor); }
}
}
}
void ProcessNeighborhood()
{
// Reset all of the cubes:
for (int i = 0; i < NUM_CUBES; i++)
{ cubes[i].ResetElement(); }
//TODO: Currently only handles a single reaction. (IE: You can't use 8 cubes and make two separate reactions.)
// Look or a cube that has neighbors
int rootCube = -1;
for (int i = 0; i < NUM_CUBES; i++)
{
Neighborhood nh(i);
int numNeighbors = CountNeighbors(&nh);
if (numNeighbors == 0)
{
continue;
}
rootCube = i;
LOG("Cube #%d with %d neighbors chosen as root of reaction\n", i, numNeighbors);
break;
}
// No reaction
if (rootCube == -1)
{
return;
}
// Find all cubes in reaction:
ElementCube* reactants[MAX_REACTION_SIZE];
int numReactants = 0;
FindReactants(reactants, &numReactants, &cubes[rootCube]);
LOG("Got %d reactants.\n", numReactants);
if (numReactants == 3)
{
reactants[0]->ReactWith(reactants[1], reactants[2]);
}
else if (numReactants == 2)
{
reactants[0]->ReactWith(reactants[1]);
}
else
{
// Currently this is an unexpected condition
ASSERT(false);
}
}
void OnPress(unsigned cubeId)
{
}
void OnRelease(unsigned cubeId)
{
LOG("Going to next elemenet on cube %d.\n", cubeId);
// Move the tapped cube to the next element
cubes[cubeId].GoToNextElement();
ProcessNeighborhood();
}
void OnTouch(void* sender, unsigned cubeId)
{
if (isRelease[cubeId])
{
OnRelease(cubeId);
}
else
{
OnPress(cubeId);
}
isRelease[cubeId] = !isRelease[cubeId];//Next touch event on this cube will be a release event
}
void OnNeighborAdd(void* sender, unsigned firstId, unsigned firstSide, unsigned secondId, unsigned secondSide)
{
ProcessNeighborhood();
}
void OnNeighborRemove(void* sender, unsigned firstId, unsigned firstSide, unsigned secondId, unsigned secondSide)
{
ProcessNeighborhood();
}
<|endoftext|> |
<commit_before>/*
This file is part of "libarchive-ruby-swig", a simple SWIG wrapper around
libarchive.
Copyright 2011, Tobias Koch <[email protected]>
libarchive-ruby-swig is licensed under a simplified BSD License. A copy of the
license text can be found in the file LICENSE.txt distributed with the source.
*/
#include <cstring>
#include <string>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <archive.h>
#include <archive_entry.h>
#include <ruby.h>
#include "entry.h"
#include "error.h"
Entry::Entry(struct archive_entry *entry)
: _entry(entry)
{}
Entry::~Entry()
{
if(_entry) {
archive_entry_free(_entry);
_entry = 0;
}
}
bool Entry::is_file()
{
if(S_ISREG(archive_entry_filetype(_entry)) &&
!this->is_hardlink()) {
return true;
}
return false;
}
bool Entry::is_directory()
{
return S_ISDIR(archive_entry_filetype(_entry));
}
bool Entry::is_symbolic_link()
{
return S_ISLNK(archive_entry_filetype(_entry));
}
bool Entry::is_block_special()
{
return S_ISBLK(archive_entry_filetype(_entry));
}
bool Entry::is_character_special()
{
return S_ISCHR(archive_entry_filetype(_entry));
}
bool Entry::is_fifo()
{
return S_ISFIFO(archive_entry_filetype(_entry));
}
bool Entry::is_socket()
{
return S_ISSOCK(archive_entry_filetype(_entry));
}
bool Entry::is_hardlink()
{
if(archive_entry_hardlink(_entry) != 0)
return true;
return false;
}
unsigned int Entry::filetype()
{
return archive_entry_filetype(_entry);
}
void Entry::set_filetype(unsigned int filetype)
{
archive_entry_set_filetype(_entry, filetype);
}
unsigned int Entry::devmajor()
{
return archive_entry_devmajor(_entry);
}
void Entry::set_devmajor(unsigned int devmajor)
{
archive_entry_set_devmajor(_entry, devmajor);
}
unsigned int Entry::devminor()
{
return archive_entry_devminor(_entry);
}
void Entry::set_devminor(unsigned int devminor)
{
archive_entry_set_devminor(_entry, devminor);
}
unsigned long Entry::atime()
{
archive_entry_atime(_entry);
}
void Entry::set_atime(unsigned long atime)
{
archive_entry_set_atime(_entry, atime, 0);
}
void Entry::clear()
{
archive_entry_clear(_entry);
}
Entry *Entry::clone()
{
new Entry(archive_entry_clone(_entry));
}
unsigned long Entry::dev()
{
return archive_entry_dev(_entry);
}
void Entry::set_dev(unsigned long dev)
{
archive_entry_set_dev(_entry, dev);
}
unsigned long Entry::gid()
{
return archive_entry_gid(_entry);
}
void Entry::set_gid(unsigned long gid)
{
archive_entry_set_gid(_entry, gid);
}
const char *Entry::gname()
{
return archive_entry_gname(_entry);
}
void Entry::set_gname(const char *gname)
{
archive_entry_copy_gname(_entry, gname);
}
const char *Entry::hardlink()
{
return archive_entry_hardlink(_entry);
}
void Entry::set_hardlink(const char *hardlink)
{
archive_entry_copy_hardlink(_entry, hardlink);
}
unsigned long Entry::ino()
{
return archive_entry_ino(_entry);
}
void Entry::set_ino(unsigned long ino)
{
archive_entry_set_ino(_entry, ino);
}
int Entry::mode()
{
return archive_entry_mode(_entry);
}
void Entry::set_mode(int mode)
{
archive_entry_set_mode(_entry, mode);
}
unsigned long Entry::mtime()
{
return archive_entry_mtime(_entry);
}
void Entry::set_mtime(unsigned long mtime)
{
archive_entry_set_mtime(_entry, mtime, 0);
}
unsigned int Entry::nlink()
{
return archive_entry_nlink(_entry);
}
void Entry::set_nlink(unsigned int nlink)
{
archive_entry_set_nlink(_entry, nlink);
}
const char *Entry::pathname()
{
return archive_entry_pathname(_entry);
}
void Entry::set_pathname(const char *pathname)
{
archive_entry_copy_pathname(_entry, pathname);
}
unsigned int Entry::rdevmajor()
{
return archive_entry_rdevmajor(_entry);
}
void Entry::set_rdevmajor(unsigned int rdevmajor)
{
archive_entry_set_rdevmajor(_entry, rdevmajor);
}
unsigned int Entry::rdevminor()
{
return archive_entry_rdevminor(_entry);
}
void Entry::set_rdevminor(unsigned int rdevminor)
{
archive_entry_set_rdevminor(_entry, rdevminor);
}
unsigned long Entry::size()
{
return archive_entry_size(_entry);
}
void Entry::set_size(unsigned long size)
{
archive_entry_set_size(_entry, size);
}
const char *Entry::symlink()
{
return archive_entry_symlink(_entry);
}
void Entry::set_symlink(const char *symlink)
{
archive_entry_copy_symlink(_entry, symlink);
}
unsigned long Entry::uid()
{
return archive_entry_uid(_entry);
}
void Entry::set_uid(unsigned long uid)
{
archive_entry_set_uid(_entry, uid);
}
const char *Entry::uname()
{
return archive_entry_uname(_entry);
}
void Entry::set_uname(const char *uname)
{
archive_entry_copy_uname(_entry, uname);
}
void Entry::copy_stat_helper(const char *filename)
{
struct stat sb;
if(lstat(filename, &sb) == -1) {
std::string error_msg = strerror(errno);
throw Error(error_msg);
}
archive_entry_copy_stat(_entry, &sb);
}
<commit_msg>entry.cpp: add missing return statements!<commit_after>/*
This file is part of "libarchive-ruby-swig", a simple SWIG wrapper around
libarchive.
Copyright 2011, Tobias Koch <[email protected]>
libarchive-ruby-swig is licensed under a simplified BSD License. A copy of the
license text can be found in the file LICENSE.txt distributed with the source.
*/
#include <cstring>
#include <string>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <archive.h>
#include <archive_entry.h>
#include <ruby.h>
#include "entry.h"
#include "error.h"
Entry::Entry(struct archive_entry *entry)
: _entry(entry)
{}
Entry::~Entry()
{
if(_entry) {
archive_entry_free(_entry);
_entry = 0;
}
}
bool Entry::is_file()
{
if(S_ISREG(archive_entry_filetype(_entry)) &&
!this->is_hardlink()) {
return true;
}
return false;
}
bool Entry::is_directory()
{
return S_ISDIR(archive_entry_filetype(_entry));
}
bool Entry::is_symbolic_link()
{
return S_ISLNK(archive_entry_filetype(_entry));
}
bool Entry::is_block_special()
{
return S_ISBLK(archive_entry_filetype(_entry));
}
bool Entry::is_character_special()
{
return S_ISCHR(archive_entry_filetype(_entry));
}
bool Entry::is_fifo()
{
return S_ISFIFO(archive_entry_filetype(_entry));
}
bool Entry::is_socket()
{
return S_ISSOCK(archive_entry_filetype(_entry));
}
bool Entry::is_hardlink()
{
if(archive_entry_hardlink(_entry) != 0)
return true;
return false;
}
unsigned int Entry::filetype()
{
return archive_entry_filetype(_entry);
}
void Entry::set_filetype(unsigned int filetype)
{
archive_entry_set_filetype(_entry, filetype);
}
unsigned int Entry::devmajor()
{
return archive_entry_devmajor(_entry);
}
void Entry::set_devmajor(unsigned int devmajor)
{
archive_entry_set_devmajor(_entry, devmajor);
}
unsigned int Entry::devminor()
{
return archive_entry_devminor(_entry);
}
void Entry::set_devminor(unsigned int devminor)
{
archive_entry_set_devminor(_entry, devminor);
}
unsigned long Entry::atime()
{
return archive_entry_atime(_entry);
}
void Entry::set_atime(unsigned long atime)
{
archive_entry_set_atime(_entry, atime, 0);
}
void Entry::clear()
{
archive_entry_clear(_entry);
}
Entry *Entry::clone()
{
return new Entry(archive_entry_clone(_entry));
}
unsigned long Entry::dev()
{
return archive_entry_dev(_entry);
}
void Entry::set_dev(unsigned long dev)
{
archive_entry_set_dev(_entry, dev);
}
unsigned long Entry::gid()
{
return archive_entry_gid(_entry);
}
void Entry::set_gid(unsigned long gid)
{
archive_entry_set_gid(_entry, gid);
}
const char *Entry::gname()
{
return archive_entry_gname(_entry);
}
void Entry::set_gname(const char *gname)
{
archive_entry_copy_gname(_entry, gname);
}
const char *Entry::hardlink()
{
return archive_entry_hardlink(_entry);
}
void Entry::set_hardlink(const char *hardlink)
{
archive_entry_copy_hardlink(_entry, hardlink);
}
unsigned long Entry::ino()
{
return archive_entry_ino(_entry);
}
void Entry::set_ino(unsigned long ino)
{
archive_entry_set_ino(_entry, ino);
}
int Entry::mode()
{
return archive_entry_mode(_entry);
}
void Entry::set_mode(int mode)
{
archive_entry_set_mode(_entry, mode);
}
unsigned long Entry::mtime()
{
return archive_entry_mtime(_entry);
}
void Entry::set_mtime(unsigned long mtime)
{
archive_entry_set_mtime(_entry, mtime, 0);
}
unsigned int Entry::nlink()
{
return archive_entry_nlink(_entry);
}
void Entry::set_nlink(unsigned int nlink)
{
archive_entry_set_nlink(_entry, nlink);
}
const char *Entry::pathname()
{
return archive_entry_pathname(_entry);
}
void Entry::set_pathname(const char *pathname)
{
archive_entry_copy_pathname(_entry, pathname);
}
unsigned int Entry::rdevmajor()
{
return archive_entry_rdevmajor(_entry);
}
void Entry::set_rdevmajor(unsigned int rdevmajor)
{
archive_entry_set_rdevmajor(_entry, rdevmajor);
}
unsigned int Entry::rdevminor()
{
return archive_entry_rdevminor(_entry);
}
void Entry::set_rdevminor(unsigned int rdevminor)
{
archive_entry_set_rdevminor(_entry, rdevminor);
}
unsigned long Entry::size()
{
return archive_entry_size(_entry);
}
void Entry::set_size(unsigned long size)
{
archive_entry_set_size(_entry, size);
}
const char *Entry::symlink()
{
return archive_entry_symlink(_entry);
}
void Entry::set_symlink(const char *symlink)
{
archive_entry_copy_symlink(_entry, symlink);
}
unsigned long Entry::uid()
{
return archive_entry_uid(_entry);
}
void Entry::set_uid(unsigned long uid)
{
archive_entry_set_uid(_entry, uid);
}
const char *Entry::uname()
{
return archive_entry_uname(_entry);
}
void Entry::set_uname(const char *uname)
{
archive_entry_copy_uname(_entry, uname);
}
void Entry::copy_stat_helper(const char *filename)
{
struct stat sb;
if(lstat(filename, &sb) == -1) {
std::string error_msg = strerror(errno);
throw Error(error_msg);
}
archive_entry_copy_stat(_entry, &sb);
}
<|endoftext|> |
<commit_before>#if defined(__WINDOWS__)
#define WIN32_LEAN_AND_MEAN
#define NOGDI
#include <windows.h>
#else
#include <sys/stat.h>
#include <signal.h>
#include <unistd.h> // isatty
#endif
#include <string.h> // strncpy, strcmp
#include "Config.h"
#include "Common.h"
const char* Format( const char* format, ... )
{
static char buffer[512];
va_list vl;
va_start(vl, format);
vsprintf(buffer, format, vl);
va_end(vl);
return buffer;
}
static void SimpleLogHandler( LogLevel level, const char* line )
{
const char* prefix = "";
const char* postfix = "";
FILE* file = NULL;
switch(level)
{
case LOG_INFO:
file = stdout;
break;
case LOG_ERROR:
prefix = "ERROR: ";
file = stderr;
break;
case LOG_FATAL_ERROR:
prefix = "FATAL ERROR: ";
file = stderr;
break;
}
fprintf(file, "%s%s%s\n", prefix, line, postfix);
}
static void ColorLogHandler( LogLevel level, const char* line )
{
const char* prefix = "";
const char* postfix = "";
FILE* file = NULL;
switch(level)
{
case LOG_INFO:
file = stdout;
break;
case LOG_ERROR:
prefix = "\033[31mERROR: ";
postfix = "\033[0m";
file = stderr;
break;
case LOG_FATAL_ERROR:
prefix = "\033[31;1mFATAL ERROR: ";
postfix = "\033[0m";
file = stderr;
break;
}
fprintf(file, "%s%s%s\n", prefix, line, postfix);
}
static LogHandler g_LogHandler = SimpleLogHandler;
void SetLogHandler( LogHandler handler )
{
assert(handler != NULL);
g_LogHandler = handler;
}
LogHandler GetLogHandler()
{
return g_LogHandler;
}
void LogV( LogLevel level, const char* format, va_list vl )
{
static char buffer[512];
vsprintf(buffer, format, vl);
const char* start = buffer;
for(char* current = buffer; ; ++current)
{
if(*current == '\n')
{
*current = '\0';
g_LogHandler(level, start);
start = current+1;
}
else if(*current == '\0')
{
g_LogHandler(level, start);
break;
}
}
}
void Log( const char* format, ... )
{
va_list vl;
va_start(vl, format);
LogV(LOG_INFO, format, vl);
va_end(vl);
}
void Error( const char* format, ... )
{
va_list vl;
va_start(vl, format);
LogV(LOG_ERROR, format, vl);
va_end(vl);
}
void FatalError( const char* format, ... )
{
va_list vl;
va_start(vl, format);
LogV(LOG_ERROR, format, vl);
va_end(vl);
//raise(SIGTRAP);
exit(EXIT_FAILURE);
}
#if defined(__WINDOWS__)
static LogHandler AutodetectLogHandler()
{
return ColorLogHandler;
}
#else
static LogHandler AutodetectLogHandler()
{
if(isatty(fileno(stdout)) && isatty(fileno(stderr)))
return ColorLogHandler;
else
return SimpleLogHandler;
}
#endif
bool PostConfigInitLog()
{
const char* handlerName = GetConfigString("debug.log-handler", "auto");
LogHandler handler = NULL;
if(strcmp(handlerName, "simple") == 0)
handler = SimpleLogHandler;
else if(strcmp(handlerName, "color") == 0)
handler = ColorLogHandler;
else if(strcmp(handlerName, "auto") == 0)
handler = AutodetectLogHandler();
if(handler)
{
SetLogHandler(handler);
return true;
}
else
{
Error("Unknown log handler '%s'.", handlerName);
return false;
}
}
#if defined(__WINDOWS__)
static LogHandler AutodetectLogHandler()
{
return ColorLogHandler;
}
#else
static LogHandler AutodetectLogHandler()
{
if(isatty(fileno(stdout)) && isatty(fileno(stderr)))
return ColorLogHandler;
else
return SimpleLogHandler;
}
#endif
bool PostConfigInitLog()
{
const char* handlerName = GetConfigString("debug.log-handler", "auto");
LogHandler handler = NULL;
if(strcmp(handlerName, "simple") == 0)
handler = SimpleLogHandler;
else if(strcmp(handlerName, "color") == 0)
handler = ColorLogHandler;
else if(strcmp(handlerName, "auto") == 0)
handler = AutodetectLogHandler();
if(handler)
{
SetLogHandler(handler);
return true;
}
else
{
Error("Unknown log handler '%s'.", handlerName);
return false;
}
}
bool CopyString( const char* source, char* destination, int destinationSize )
{
assert(source && destination && destinationSize > 0);
strncpy(destination, source, destinationSize);
if(destination[destinationSize-1] == '\0')
{
return true;
}
else
{
destination[destinationSize-1] = '\0';
return false;
}
}
#if defined(__WINDOWS__)
FileType GetFileType( const char* path )
{
DWORD type = GetFileAttributesA(path);
if(type == INVALID_FILE_ATTRIBUTES)
return FILE_TYPE_INVALID;
if(type & FILE_ATTRIBUTE_DIRECTORY)
return FILE_TYPE_DIRECTORY;
else
return FILE_TYPE_REGULAR;
}
#else
FileType GetFileType( const char* path )
{
struct stat info;
if(stat(path, &info) == -1)
return FILE_TYPE_INVALID;
if(info.st_mode & S_IFREG)
return FILE_TYPE_REGULAR;
else if(info.st_mode & S_IFDIR)
return FILE_TYPE_DIRECTORY;
else
return FILE_TYPE_UNKNOWN;
}
#endif
<commit_msg>Removed duplicated logging code.<commit_after>#if defined(__WINDOWS__)
#define WIN32_LEAN_AND_MEAN
#define NOGDI
#include <windows.h>
#else
#include <sys/stat.h>
#include <signal.h>
#include <unistd.h> // isatty
#endif
#include <string.h> // strncpy, strcmp
#include "Config.h"
#include "Common.h"
const char* Format( const char* format, ... )
{
static char buffer[512];
va_list vl;
va_start(vl, format);
vsprintf(buffer, format, vl);
va_end(vl);
return buffer;
}
static void SimpleLogHandler( LogLevel level, const char* line )
{
const char* prefix = "";
const char* postfix = "";
FILE* file = NULL;
switch(level)
{
case LOG_INFO:
file = stdout;
break;
case LOG_ERROR:
prefix = "ERROR: ";
file = stderr;
break;
case LOG_FATAL_ERROR:
prefix = "FATAL ERROR: ";
file = stderr;
break;
}
fprintf(file, "%s%s%s\n", prefix, line, postfix);
}
static void ColorLogHandler( LogLevel level, const char* line )
{
const char* prefix = "";
const char* postfix = "";
FILE* file = NULL;
switch(level)
{
case LOG_INFO:
file = stdout;
break;
case LOG_ERROR:
prefix = "\033[31mERROR: ";
postfix = "\033[0m";
file = stderr;
break;
case LOG_FATAL_ERROR:
prefix = "\033[31;1mFATAL ERROR: ";
postfix = "\033[0m";
file = stderr;
break;
}
fprintf(file, "%s%s%s\n", prefix, line, postfix);
}
static LogHandler g_LogHandler = SimpleLogHandler;
void SetLogHandler( LogHandler handler )
{
assert(handler != NULL);
g_LogHandler = handler;
}
LogHandler GetLogHandler()
{
return g_LogHandler;
}
void LogV( LogLevel level, const char* format, va_list vl )
{
static char buffer[512];
vsprintf(buffer, format, vl);
const char* start = buffer;
for(char* current = buffer; ; ++current)
{
if(*current == '\n')
{
*current = '\0';
g_LogHandler(level, start);
start = current+1;
}
else if(*current == '\0')
{
g_LogHandler(level, start);
break;
}
}
}
void Log( const char* format, ... )
{
va_list vl;
va_start(vl, format);
LogV(LOG_INFO, format, vl);
va_end(vl);
}
void Error( const char* format, ... )
{
va_list vl;
va_start(vl, format);
LogV(LOG_ERROR, format, vl);
va_end(vl);
}
void FatalError( const char* format, ... )
{
va_list vl;
va_start(vl, format);
LogV(LOG_ERROR, format, vl);
va_end(vl);
//raise(SIGTRAP);
exit(EXIT_FAILURE);
}
#if defined(__WINDOWS__)
static LogHandler AutodetectLogHandler()
{
return ColorLogHandler;
}
#else
static LogHandler AutodetectLogHandler()
{
if(isatty(fileno(stdout)) && isatty(fileno(stderr)))
return ColorLogHandler;
else
return SimpleLogHandler;
}
#endif
bool PostConfigInitLog()
{
const char* handlerName = GetConfigString("debug.log-handler", "auto");
LogHandler handler = NULL;
if(strcmp(handlerName, "simple") == 0)
handler = SimpleLogHandler;
else if(strcmp(handlerName, "color") == 0)
handler = ColorLogHandler;
else if(strcmp(handlerName, "auto") == 0)
handler = AutodetectLogHandler();
if(handler)
{
SetLogHandler(handler);
return true;
}
else
{
Error("Unknown log handler '%s'.", handlerName);
return false;
}
}
bool CopyString( const char* source, char* destination, int destinationSize )
{
assert(source && destination && destinationSize > 0);
strncpy(destination, source, destinationSize);
if(destination[destinationSize-1] == '\0')
{
return true;
}
else
{
destination[destinationSize-1] = '\0';
return false;
}
}
#if defined(__WINDOWS__)
FileType GetFileType( const char* path )
{
DWORD type = GetFileAttributesA(path);
if(type == INVALID_FILE_ATTRIBUTES)
return FILE_TYPE_INVALID;
if(type & FILE_ATTRIBUTE_DIRECTORY)
return FILE_TYPE_DIRECTORY;
else
return FILE_TYPE_REGULAR;
}
#else
FileType GetFileType( const char* path )
{
struct stat info;
if(stat(path, &info) == -1)
return FILE_TYPE_INVALID;
if(info.st_mode & S_IFREG)
return FILE_TYPE_REGULAR;
else if(info.st_mode & S_IFDIR)
return FILE_TYPE_DIRECTORY;
else
return FILE_TYPE_UNKNOWN;
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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.
OTHER DEALINGS IN THE SOFTWARE.
*/
#include <cstdlib>
#include "Config.h"
#include "Device.h"
#include "Accelerometer.h"
#include "Args.h"
#include "DiskFile.h"
#include "DiskFilesystem.h"
#include "JSONParser.h"
#include "Keyboard.h"
#include "Log.h"
#include "LuaEnvironment.h"
#include "Memory.h"
#include "Mouse.h"
#include "OS.h"
#include "OsWindow.h"
#include "Renderer.h"
#include "ResourceManager.h"
#include "StringSetting.h"
#include "StringUtils.h"
#include "TextReader.h"
#include "Touch.h"
#include "Types.h"
#include "Bundle.h"
#include "TempAllocator.h"
#include "ResourcePackage.h"
#include "ConsoleServer.h"
#include "World.h"
#include "LuaStack.h"
#include "WorldManager.h"
#include "NetworkFilesystem.h"
#include "LuaSystem.h"
#if defined(LINUX) || defined(WINDOWS)
#include "BundleCompiler.h"
#endif
#if defined(ANDROID)
#include "ApkFilesystem.h"
#endif
#define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024
namespace crown
{
//-----------------------------------------------------------------------------
Device::Device()
: m_allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)
, m_argc(0)
, m_argv(NULL)
, m_fileserver(0)
, m_console_port(10001)
, m_is_init(false)
, m_is_running(false)
, m_is_paused(false)
, m_frame_count(0)
, m_last_time(0)
, m_current_time(0)
, m_last_delta_time(0.0f)
, m_time_since_start(0.0)
, m_filesystem(NULL)
, m_lua_environment(NULL)
, m_renderer(NULL)
, m_bundle_compiler(NULL)
, m_console(NULL)
, m_resource_manager(NULL)
, m_resource_bundle(NULL)
, m_world_manager(NULL)
{
// Bundle dir is current dir by default.
string::strncpy(m_bundle_dir, os::get_cwd(), MAX_PATH_LENGTH);
string::strncpy(m_source_dir, "", MAX_PATH_LENGTH);
string::strncpy(m_boot_file, "lua/game", MAX_PATH_LENGTH);
}
//-----------------------------------------------------------------------------
Device::~Device()
{
}
//-----------------------------------------------------------------------------
void Device::init()
{
// Initialize
Log::i("Initializing Crown Engine %d.%d.%d...", CROWN_VERSION_MAJOR, CROWN_VERSION_MINOR, CROWN_VERSION_MICRO);
// RPC only in debug or development builds
#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
m_console = CE_NEW(m_allocator, ConsoleServer)(m_console_port);
m_console->init(false);
#endif
Log::d("Creating filesystem...");
// Default bundle filesystem
#if defined (LINUX) || defined(WINDOWS)
if (m_fileserver == 1)
{
m_filesystem = CE_NEW(m_allocator, NetworkFilesystem)(NetAddress(127, 0, 0, 1), 10001);
}
else
{
m_filesystem = CE_NEW(m_allocator, DiskFilesystem)(m_bundle_dir);
}
#elif defined(ANDROID)
if (m_fileserver == 1)
{
m_filesystem = CE_NEW(m_allocator, NetworkFilesystem)(NetAddress(192, 168, 0, 7), 10001);
}
else
{
m_filesystem = CE_NEW(m_allocator, ApkFilesystem)();
}
#endif
m_resource_bundle = Bundle::create(m_allocator, *m_filesystem);
// Create resource manager
Log::d("Creating resource manager...");
m_resource_manager = CE_NEW(m_allocator, ResourceManager)(*m_resource_bundle, 0);
Log::d("Resource seed: %d", m_resource_manager->seed());
// Create world manager
Log::d("Creating world manager...");
m_world_manager = CE_NEW(m_allocator, WorldManager)();
// Create window
Log::d("Creating main window...");
m_window = CE_NEW(m_allocator, OsWindow);
// Create input devices
m_keyboard = CE_NEW(m_allocator, Keyboard);
m_mouse = CE_NEW(m_allocator, Mouse);
m_touch = CE_NEW(m_allocator, Touch);
// Create renderer
Log::d("Creating renderer...");
m_renderer = CE_NEW(m_allocator, Renderer)(m_allocator);
m_renderer->init();
Log::d("Creating lua system...");
lua_system::init();
m_lua_environment = CE_NEW(m_allocator, LuaEnvironment)(lua_system::state());
Log::d("Creating physics...");
physics_system::init();
Log::d("Creating audio...");
audio_system::init();
Log::d("Crown Engine initialized.");
Log::d("Initializing Game...");
m_physics_config = m_resource_manager->load(PHYSICS_CONFIG_EXTENSION, "global");
m_resource_manager->flush();
m_is_init = true;
start();
// Execute lua boot file
m_lua_environment->load_and_execute(m_boot_file);
m_lua_environment->call_global("init", 0);
Log::d("Total allocated size: %ld", m_allocator.allocated_size());
}
//-----------------------------------------------------------------------------
void Device::shutdown()
{
CE_ASSERT(is_init(), "Engine is not initialized");
// Shutdowns the game
m_lua_environment->call_global("shutdown", 0);
m_resource_manager->unload(m_physics_config);
Log::d("Releasing audio...");
audio_system::shutdown();
Log::d("Releasing physics...");
physics_system::shutdown();
Log::d("Releasing lua system...");
lua_system::shutdown();
if (m_lua_environment)
{
CE_DELETE(m_allocator, m_lua_environment);
}
Log::d("Releasing input devices...");
CE_DELETE(m_allocator, m_touch);
CE_DELETE(m_allocator, m_mouse);
CE_DELETE(m_allocator, m_keyboard);
Log::d("Releasing renderer...");
if (m_renderer)
{
m_renderer->shutdown();
CE_DELETE(m_allocator, m_renderer);
}
Log::d("Releasing world manager...");
CE_DELETE(m_allocator, m_world_manager);
Log::d("Releasing resource manager...");
if (m_resource_manager)
{
CE_DELETE(m_allocator, m_resource_manager);
}
if (m_resource_bundle)
{
Bundle::destroy(m_allocator, m_resource_bundle);
}
Log::d("Releasing filesystem...");
if (m_filesystem)
{
CE_DELETE(m_allocator, m_filesystem);
}
#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
m_console->shutdown();
CE_DELETE(m_allocator, m_console);
m_console = NULL;
#endif
m_allocator.clear();
m_is_init = false;
}
//-----------------------------------------------------------------------------
bool Device::is_init() const
{
return m_is_init;
}
//-----------------------------------------------------------------------------
bool Device::is_paused() const
{
return m_is_paused;
}
//-----------------------------------------------------------------------------
Filesystem* Device::filesystem()
{
return m_filesystem;
}
//-----------------------------------------------------------------------------
ResourceManager* Device::resource_manager()
{
return m_resource_manager;
}
//-----------------------------------------------------------------------------
LuaEnvironment* Device::lua_environment()
{
return m_lua_environment;
}
//-----------------------------------------------------------------------------
OsWindow* Device::window()
{
return m_window;
}
//-----------------------------------------------------------------------------
Renderer* Device::renderer()
{
return m_renderer;
}
//-----------------------------------------------------------------------------
Keyboard* Device::keyboard()
{
return m_keyboard;
}
//-----------------------------------------------------------------------------
Mouse* Device::mouse()
{
return m_mouse;
}
//-----------------------------------------------------------------------------
Touch* Device::touch()
{
return m_touch;
}
//-----------------------------------------------------------------------------
Accelerometer* Device::accelerometer()
{
return NULL;
}
//-----------------------------------------------------------------------------
void Device::start()
{
CE_ASSERT(m_is_init, "Cannot start uninitialized engine.");
m_is_running = true;
m_last_time = os::milliseconds();
}
//-----------------------------------------------------------------------------
void Device::stop()
{
CE_ASSERT(m_is_init, "Cannot stop uninitialized engine.");
m_is_running = false;
}
//-----------------------------------------------------------------------------
void Device::pause()
{
m_is_paused = true;
}
//-----------------------------------------------------------------------------
void Device::unpause()
{
m_is_paused = false;
}
//-----------------------------------------------------------------------------
bool Device::is_running() const
{
return m_is_running;
}
//-----------------------------------------------------------------------------
uint64_t Device::frame_count() const
{
return m_frame_count;
}
//-----------------------------------------------------------------------------
float Device::last_delta_time() const
{
return m_last_delta_time;
}
//-----------------------------------------------------------------------------
double Device::time_since_start() const
{
return m_time_since_start;
}
//-----------------------------------------------------------------------------
void Device::frame()
{
m_current_time = os::microseconds();
m_last_delta_time = (m_current_time - m_last_time) / 1000000.0f;
m_last_time = m_current_time;
m_time_since_start += m_last_delta_time;
#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
m_console->update();
#endif
if (!m_is_paused)
{
m_resource_manager->poll_resource_loader();
m_lua_environment->call_global("frame", 1, ARGUMENT_FLOAT, last_delta_time());
m_renderer->frame();
}
lua_system::clear_temporaries();
m_frame_count++;
}
//-----------------------------------------------------------------------------
void Device::update_world(World* world, float dt)
{
world->update(dt);
}
//-----------------------------------------------------------------------------
void Device::render_world(World* world, Camera* camera)
{
world->render(camera);
}
//-----------------------------------------------------------------------------
WorldId Device::create_world()
{
return m_world_manager->create_world();
}
//-----------------------------------------------------------------------------
void Device::destroy_world(WorldId world)
{
m_world_manager->destroy_world(world);
}
//-----------------------------------------------------------------------------
ResourcePackage* Device::create_resource_package(const char* name)
{
CE_ASSERT_NOT_NULL(name);
ResourceId package_id = m_resource_manager->load("package", name);
m_resource_manager->flush();
PackageResource* package_res = (PackageResource*) m_resource_manager->data(package_id);
ResourcePackage* package = CE_NEW(default_allocator(), ResourcePackage)(*m_resource_manager, package_id, package_res);
return package;
}
//-----------------------------------------------------------------------------
void Device::destroy_resource_package(ResourcePackage* package)
{
CE_ASSERT_NOT_NULL(package);
m_resource_manager->unload(package->resource_id());
CE_DELETE(default_allocator(), package);
}
//-----------------------------------------------------------------------------
void Device::compile(const char* , const char* , const char* )
{
}
//-----------------------------------------------------------------------------
void Device::reload(const char* type, const char* name)
{
#if defined(LINUX) || defined(WINDOWS)
TempAllocator4096 temp;
DynamicString filename(temp);
filename += name;
filename += '.';
filename += type;
if (!m_bundle_compiler->compile(m_bundle_dir, m_source_dir, filename.c_str()))
{
Log::d("Compilation failed.");
return;
}
ResourceId old_res_id = m_resource_manager->resource_id(type, name);
const void* old_res = m_resource_manager->data(old_res_id);
m_resource_manager->unload(old_res_id, true);
ResourceId res_id = m_resource_manager->load(type, name);
m_resource_manager->flush();
const void* new_res = m_resource_manager->data(res_id);
uint32_t type_hash = string::murmur2_32(type, string::strlen(type), 0);
switch (type_hash)
{
case UNIT_TYPE:
{
Log::d("Reloading unit: %s", name);
/// Reload unit in all worlds
for (uint32_t i = 0; i < m_world_manager->worlds().size(); i++)
{
m_world_manager->worlds()[i]->reload_units((UnitResource*) old_res, (UnitResource*) new_res);
}
break;
}
case SOUND_TYPE:
{
Log::d("Reloading sound: %s", name);
for (uint32_t i = 0; i < m_world_manager->worlds().size(); i++)
{
m_world_manager->worlds()[i]->sound_world()->reload_sounds((SoundResource*) old_res, (SoundResource*) new_res);
}
break;
}
default:
{
CE_ASSERT(false, "Oops, unknown resource type: %s", type);
break;
}
}
#endif
}
static Device* g_device;
void set_device(Device* device)
{
g_device = device;
}
Device* device()
{
return g_device;
}
} // namespace crown
<commit_msg>Log on pause()/unpause()<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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.
OTHER DEALINGS IN THE SOFTWARE.
*/
#include <cstdlib>
#include "Config.h"
#include "Device.h"
#include "Accelerometer.h"
#include "Args.h"
#include "DiskFile.h"
#include "DiskFilesystem.h"
#include "JSONParser.h"
#include "Keyboard.h"
#include "Log.h"
#include "LuaEnvironment.h"
#include "Memory.h"
#include "Mouse.h"
#include "OS.h"
#include "OsWindow.h"
#include "Renderer.h"
#include "ResourceManager.h"
#include "StringSetting.h"
#include "StringUtils.h"
#include "TextReader.h"
#include "Touch.h"
#include "Types.h"
#include "Bundle.h"
#include "TempAllocator.h"
#include "ResourcePackage.h"
#include "ConsoleServer.h"
#include "World.h"
#include "LuaStack.h"
#include "WorldManager.h"
#include "NetworkFilesystem.h"
#include "LuaSystem.h"
#if defined(LINUX) || defined(WINDOWS)
#include "BundleCompiler.h"
#endif
#if defined(ANDROID)
#include "ApkFilesystem.h"
#endif
#define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024
namespace crown
{
//-----------------------------------------------------------------------------
Device::Device()
: m_allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)
, m_argc(0)
, m_argv(NULL)
, m_fileserver(0)
, m_console_port(10001)
, m_is_init(false)
, m_is_running(false)
, m_is_paused(false)
, m_frame_count(0)
, m_last_time(0)
, m_current_time(0)
, m_last_delta_time(0.0f)
, m_time_since_start(0.0)
, m_filesystem(NULL)
, m_lua_environment(NULL)
, m_renderer(NULL)
, m_bundle_compiler(NULL)
, m_console(NULL)
, m_resource_manager(NULL)
, m_resource_bundle(NULL)
, m_world_manager(NULL)
{
// Bundle dir is current dir by default.
string::strncpy(m_bundle_dir, os::get_cwd(), MAX_PATH_LENGTH);
string::strncpy(m_source_dir, "", MAX_PATH_LENGTH);
string::strncpy(m_boot_file, "lua/game", MAX_PATH_LENGTH);
}
//-----------------------------------------------------------------------------
Device::~Device()
{
}
//-----------------------------------------------------------------------------
void Device::init()
{
// Initialize
Log::i("Initializing Crown Engine %d.%d.%d...", CROWN_VERSION_MAJOR, CROWN_VERSION_MINOR, CROWN_VERSION_MICRO);
// RPC only in debug or development builds
#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
m_console = CE_NEW(m_allocator, ConsoleServer)(m_console_port);
m_console->init(false);
#endif
Log::d("Creating filesystem...");
// Default bundle filesystem
#if defined (LINUX) || defined(WINDOWS)
if (m_fileserver == 1)
{
m_filesystem = CE_NEW(m_allocator, NetworkFilesystem)(NetAddress(127, 0, 0, 1), 10001);
}
else
{
m_filesystem = CE_NEW(m_allocator, DiskFilesystem)(m_bundle_dir);
}
#elif defined(ANDROID)
if (m_fileserver == 1)
{
m_filesystem = CE_NEW(m_allocator, NetworkFilesystem)(NetAddress(192, 168, 0, 7), 10001);
}
else
{
m_filesystem = CE_NEW(m_allocator, ApkFilesystem)();
}
#endif
m_resource_bundle = Bundle::create(m_allocator, *m_filesystem);
// Create resource manager
Log::d("Creating resource manager...");
m_resource_manager = CE_NEW(m_allocator, ResourceManager)(*m_resource_bundle, 0);
Log::d("Resource seed: %d", m_resource_manager->seed());
// Create world manager
Log::d("Creating world manager...");
m_world_manager = CE_NEW(m_allocator, WorldManager)();
// Create window
Log::d("Creating main window...");
m_window = CE_NEW(m_allocator, OsWindow);
// Create input devices
m_keyboard = CE_NEW(m_allocator, Keyboard);
m_mouse = CE_NEW(m_allocator, Mouse);
m_touch = CE_NEW(m_allocator, Touch);
// Create renderer
Log::d("Creating renderer...");
m_renderer = CE_NEW(m_allocator, Renderer)(m_allocator);
m_renderer->init();
Log::d("Creating lua system...");
lua_system::init();
m_lua_environment = CE_NEW(m_allocator, LuaEnvironment)(lua_system::state());
Log::d("Creating physics...");
physics_system::init();
Log::d("Creating audio...");
audio_system::init();
Log::d("Crown Engine initialized.");
Log::d("Initializing Game...");
m_physics_config = m_resource_manager->load(PHYSICS_CONFIG_EXTENSION, "global");
m_resource_manager->flush();
m_is_init = true;
start();
// Execute lua boot file
m_lua_environment->load_and_execute(m_boot_file);
m_lua_environment->call_global("init", 0);
Log::d("Total allocated size: %ld", m_allocator.allocated_size());
}
//-----------------------------------------------------------------------------
void Device::shutdown()
{
CE_ASSERT(is_init(), "Engine is not initialized");
// Shutdowns the game
m_lua_environment->call_global("shutdown", 0);
m_resource_manager->unload(m_physics_config);
Log::d("Releasing audio...");
audio_system::shutdown();
Log::d("Releasing physics...");
physics_system::shutdown();
Log::d("Releasing lua system...");
lua_system::shutdown();
if (m_lua_environment)
{
CE_DELETE(m_allocator, m_lua_environment);
}
Log::d("Releasing input devices...");
CE_DELETE(m_allocator, m_touch);
CE_DELETE(m_allocator, m_mouse);
CE_DELETE(m_allocator, m_keyboard);
Log::d("Releasing renderer...");
if (m_renderer)
{
m_renderer->shutdown();
CE_DELETE(m_allocator, m_renderer);
}
Log::d("Releasing world manager...");
CE_DELETE(m_allocator, m_world_manager);
Log::d("Releasing resource manager...");
if (m_resource_manager)
{
CE_DELETE(m_allocator, m_resource_manager);
}
if (m_resource_bundle)
{
Bundle::destroy(m_allocator, m_resource_bundle);
}
Log::d("Releasing filesystem...");
if (m_filesystem)
{
CE_DELETE(m_allocator, m_filesystem);
}
#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
m_console->shutdown();
CE_DELETE(m_allocator, m_console);
m_console = NULL;
#endif
m_allocator.clear();
m_is_init = false;
}
//-----------------------------------------------------------------------------
bool Device::is_init() const
{
return m_is_init;
}
//-----------------------------------------------------------------------------
bool Device::is_paused() const
{
return m_is_paused;
}
//-----------------------------------------------------------------------------
Filesystem* Device::filesystem()
{
return m_filesystem;
}
//-----------------------------------------------------------------------------
ResourceManager* Device::resource_manager()
{
return m_resource_manager;
}
//-----------------------------------------------------------------------------
LuaEnvironment* Device::lua_environment()
{
return m_lua_environment;
}
//-----------------------------------------------------------------------------
OsWindow* Device::window()
{
return m_window;
}
//-----------------------------------------------------------------------------
Renderer* Device::renderer()
{
return m_renderer;
}
//-----------------------------------------------------------------------------
Keyboard* Device::keyboard()
{
return m_keyboard;
}
//-----------------------------------------------------------------------------
Mouse* Device::mouse()
{
return m_mouse;
}
//-----------------------------------------------------------------------------
Touch* Device::touch()
{
return m_touch;
}
//-----------------------------------------------------------------------------
Accelerometer* Device::accelerometer()
{
return NULL;
}
//-----------------------------------------------------------------------------
void Device::start()
{
CE_ASSERT(m_is_init, "Cannot start uninitialized engine.");
m_is_running = true;
m_last_time = os::milliseconds();
}
//-----------------------------------------------------------------------------
void Device::stop()
{
CE_ASSERT(m_is_init, "Cannot stop uninitialized engine.");
m_is_running = false;
}
//-----------------------------------------------------------------------------
void Device::pause()
{
m_is_paused = true;
Log::i("Engine paused.");
}
//-----------------------------------------------------------------------------
void Device::unpause()
{
m_is_paused = false;
Log::i("Engine unpaused.");
}
//-----------------------------------------------------------------------------
bool Device::is_running() const
{
return m_is_running;
}
//-----------------------------------------------------------------------------
uint64_t Device::frame_count() const
{
return m_frame_count;
}
//-----------------------------------------------------------------------------
float Device::last_delta_time() const
{
return m_last_delta_time;
}
//-----------------------------------------------------------------------------
double Device::time_since_start() const
{
return m_time_since_start;
}
//-----------------------------------------------------------------------------
void Device::frame()
{
m_current_time = os::microseconds();
m_last_delta_time = (m_current_time - m_last_time) / 1000000.0f;
m_last_time = m_current_time;
m_time_since_start += m_last_delta_time;
#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
m_console->update();
#endif
if (!m_is_paused)
{
m_resource_manager->poll_resource_loader();
m_lua_environment->call_global("frame", 1, ARGUMENT_FLOAT, last_delta_time());
m_renderer->frame();
}
lua_system::clear_temporaries();
m_frame_count++;
}
//-----------------------------------------------------------------------------
void Device::update_world(World* world, float dt)
{
world->update(dt);
}
//-----------------------------------------------------------------------------
void Device::render_world(World* world, Camera* camera)
{
world->render(camera);
}
//-----------------------------------------------------------------------------
WorldId Device::create_world()
{
return m_world_manager->create_world();
}
//-----------------------------------------------------------------------------
void Device::destroy_world(WorldId world)
{
m_world_manager->destroy_world(world);
}
//-----------------------------------------------------------------------------
ResourcePackage* Device::create_resource_package(const char* name)
{
CE_ASSERT_NOT_NULL(name);
ResourceId package_id = m_resource_manager->load("package", name);
m_resource_manager->flush();
PackageResource* package_res = (PackageResource*) m_resource_manager->data(package_id);
ResourcePackage* package = CE_NEW(default_allocator(), ResourcePackage)(*m_resource_manager, package_id, package_res);
return package;
}
//-----------------------------------------------------------------------------
void Device::destroy_resource_package(ResourcePackage* package)
{
CE_ASSERT_NOT_NULL(package);
m_resource_manager->unload(package->resource_id());
CE_DELETE(default_allocator(), package);
}
//-----------------------------------------------------------------------------
void Device::compile(const char* , const char* , const char* )
{
}
//-----------------------------------------------------------------------------
void Device::reload(const char* type, const char* name)
{
#if defined(LINUX) || defined(WINDOWS)
TempAllocator4096 temp;
DynamicString filename(temp);
filename += name;
filename += '.';
filename += type;
if (!m_bundle_compiler->compile(m_bundle_dir, m_source_dir, filename.c_str()))
{
Log::d("Compilation failed.");
return;
}
ResourceId old_res_id = m_resource_manager->resource_id(type, name);
const void* old_res = m_resource_manager->data(old_res_id);
m_resource_manager->unload(old_res_id, true);
ResourceId res_id = m_resource_manager->load(type, name);
m_resource_manager->flush();
const void* new_res = m_resource_manager->data(res_id);
uint32_t type_hash = string::murmur2_32(type, string::strlen(type), 0);
switch (type_hash)
{
case UNIT_TYPE:
{
Log::d("Reloading unit: %s", name);
/// Reload unit in all worlds
for (uint32_t i = 0; i < m_world_manager->worlds().size(); i++)
{
m_world_manager->worlds()[i]->reload_units((UnitResource*) old_res, (UnitResource*) new_res);
}
break;
}
case SOUND_TYPE:
{
Log::d("Reloading sound: %s", name);
for (uint32_t i = 0; i < m_world_manager->worlds().size(); i++)
{
m_world_manager->worlds()[i]->sound_world()->reload_sounds((SoundResource*) old_res, (SoundResource*) new_res);
}
break;
}
default:
{
CE_ASSERT(false, "Oops, unknown resource type: %s", type);
break;
}
}
#endif
}
static Device* g_device;
void set_device(Device* device)
{
g_device = device;
}
Device* device()
{
return g_device;
}
} // namespace crown
<|endoftext|> |
<commit_before>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "mmu.h"
#include "spinlock.h"
#include "condvar.h"
#include "queue.h"
#include "proc.hh"
#include "cpu.hh"
#include "vm.hh"
#include "sperf.hh"
#include "kmtrace.hh"
#include "futex.h"
#include <uk/mman.h>
//SYSCALL
int
sys_fork(int flags)
{
ANON_REGION(__func__, &perfgroup);
return fork(flags);
}
//SYSCALL NORET
int
sys_exit(void)
{
exit();
panic("exit() returned");
}
//SYSCALL
int
sys_wait(void)
{
ANON_REGION(__func__, &perfgroup);
return wait();
}
//SYSCALL
int
sys_kill(int pid)
{
return proc::kill(pid);
}
//SYSCALL
int
sys_getpid(void)
{
return myproc()->pid;
}
//SYSCALL
char*
sys_sbrk(int n)
{
uptr addr;
if(myproc()->vmap->sbrk(n, &addr) < 0)
return (char*)-1;
return (char*)addr;
}
//SYSCALL
int
sys_nsleep(u64 nsec)
{
struct spinlock lock;
struct condvar cv;
u64 nsecto;
initlock(&lock, "sleep_lock", 0);
initcondvar(&cv, "sleep_cv");
acquire(&lock);
auto cleanup = scoped_cleanup([&lock, &cv]() {
release(&lock);
destroycondvar(&cv);
destroylock(&lock);
});
nsecto = nsectime()+nsec;
while (nsecto > nsectime()) {
if (myproc()->killed)
return -1;
cv_sleepto(&cv, &lock, nsecto);
}
return 0;
}
// return how many clock tick interrupts have occurred
// since boot.
//SYSCALL
u64
sys_uptime(void)
{
return nsectime();
}
//SYSCALL
void *
sys_mmap(userptr<void> addr, size_t len, int prot, int flags, int fd,
off_t offset)
{
ANON_REGION(__func__, &perfgroup);
mt_ascope ascope("%s(%p,%lu,%#x,%#x,%d,%#lx)",
__func__, addr.unsafe_get(), len, prot, flags, fd, offset);
if (!(prot & (PROT_READ | PROT_WRITE))) {
cprintf("not implemented: !(prot & (PROT_READ | PROT_WRITE))\n");
return MAP_FAILED;
}
if (flags & MAP_SHARED) {
cprintf("not implemented: (flags & MAP_SHARED)\n");
return MAP_FAILED;
}
if (!(flags & MAP_ANONYMOUS)) {
cprintf("not implemented: !(flags & MAP_ANONYMOUS)\n");
return MAP_FAILED;
}
uptr start = PGROUNDDOWN(addr);
uptr end = PGROUNDUP(addr + len);
if ((flags & MAP_FIXED) && start != addr)
return MAP_FAILED;
#if MTRACE
if (addr != 0) {
for (uptr i = start / PGSIZE; i < end / PGSIZE; i++)
mtwriteavar("pte:%p.%#lx", myproc()->vmap, i);
}
#endif
vmnode *vmn = new vmnode((end - start) / PGSIZE);
if (vmn == 0)
return MAP_FAILED;
uptr r = myproc()->vmap->insert(vmn, start, 1);
if (r < 0) {
delete vmn;
return MAP_FAILED;
}
return (void*)r;
}
//SYSCALL
int
sys_munmap(userptr<void> addr, size_t len)
{
ANON_REGION(__func__, &perfgroup);
#if MTRACE
mt_ascope ascope("%s(%p,%#lx)", __func__, addr.unsafe_get(), len);
for (uptr i = addr / PGSIZE; i < PGROUNDUP(addr + len) / PGSIZE; i++)
mtwriteavar("pte:%p.%#lx", myproc()->vmap, i);
#endif
uptr align_addr = PGROUNDDOWN(addr);
uptr align_len = PGROUNDUP(addr + len) - align_addr;
if (myproc()->vmap->remove(align_addr, align_len) < 0)
return -1;
return 0;
}
//SYSCALL NORET
void
sys_halt(void)
{
halt();
panic("halt returned");
}
//SYSCALL
int
sys_setfs(u64 base)
{
proc *p = myproc();
p->user_fs_ = base;
switchvm(p);
return 0;
}
//SYSCALL
int
sys_setaffinity(int cpu)
{
return myproc()->set_cpu_pin(cpu);
}
//SYSCALL
long
sys_futex(const u64* addr, int op, u64 val, u64 timer)
{
futexkey_t key;
if (futexkey(addr, myproc()->vmap, &key) < 0)
return -1;
mt_ascope ascope("%s(%p,%d,%lu,%lu)", __func__, addr, op, val, timer);
switch(op) {
case FUTEX_WAIT:
return futexwait(key, val, timer);
case FUTEX_WAKE:
return futexwake(key, val);
default:
return -1;
}
}
//SYSCALL
long
sys_yield(void)
{
yield();
return 0;
}
<commit_msg>sys_cpuhz<commit_after>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "mmu.h"
#include "spinlock.h"
#include "condvar.h"
#include "queue.h"
#include "proc.hh"
#include "cpu.hh"
#include "vm.hh"
#include "sperf.hh"
#include "kmtrace.hh"
#include "futex.h"
#include <uk/mman.h>
//SYSCALL
int
sys_fork(int flags)
{
ANON_REGION(__func__, &perfgroup);
return fork(flags);
}
//SYSCALL NORET
int
sys_exit(void)
{
exit();
panic("exit() returned");
}
//SYSCALL
int
sys_wait(void)
{
ANON_REGION(__func__, &perfgroup);
return wait();
}
//SYSCALL
int
sys_kill(int pid)
{
return proc::kill(pid);
}
//SYSCALL
int
sys_getpid(void)
{
return myproc()->pid;
}
//SYSCALL
char*
sys_sbrk(int n)
{
uptr addr;
if(myproc()->vmap->sbrk(n, &addr) < 0)
return (char*)-1;
return (char*)addr;
}
//SYSCALL
int
sys_nsleep(u64 nsec)
{
struct spinlock lock;
struct condvar cv;
u64 nsecto;
initlock(&lock, "sleep_lock", 0);
initcondvar(&cv, "sleep_cv");
acquire(&lock);
auto cleanup = scoped_cleanup([&lock, &cv]() {
release(&lock);
destroycondvar(&cv);
destroylock(&lock);
});
nsecto = nsectime()+nsec;
while (nsecto > nsectime()) {
if (myproc()->killed)
return -1;
cv_sleepto(&cv, &lock, nsecto);
}
return 0;
}
// return how many clock tick interrupts have occurred
// since boot.
//SYSCALL
u64
sys_uptime(void)
{
return nsectime();
}
//SYSCALL
void *
sys_mmap(userptr<void> addr, size_t len, int prot, int flags, int fd,
off_t offset)
{
ANON_REGION(__func__, &perfgroup);
mt_ascope ascope("%s(%p,%lu,%#x,%#x,%d,%#lx)",
__func__, addr.unsafe_get(), len, prot, flags, fd, offset);
if (!(prot & (PROT_READ | PROT_WRITE))) {
cprintf("not implemented: !(prot & (PROT_READ | PROT_WRITE))\n");
return MAP_FAILED;
}
if (flags & MAP_SHARED) {
cprintf("not implemented: (flags & MAP_SHARED)\n");
return MAP_FAILED;
}
if (!(flags & MAP_ANONYMOUS)) {
cprintf("not implemented: !(flags & MAP_ANONYMOUS)\n");
return MAP_FAILED;
}
uptr start = PGROUNDDOWN(addr);
uptr end = PGROUNDUP(addr + len);
if ((flags & MAP_FIXED) && start != addr)
return MAP_FAILED;
#if MTRACE
if (addr != 0) {
for (uptr i = start / PGSIZE; i < end / PGSIZE; i++)
mtwriteavar("pte:%p.%#lx", myproc()->vmap, i);
}
#endif
vmnode *vmn = new vmnode((end - start) / PGSIZE);
if (vmn == 0)
return MAP_FAILED;
uptr r = myproc()->vmap->insert(vmn, start, 1);
if (r < 0) {
delete vmn;
return MAP_FAILED;
}
return (void*)r;
}
//SYSCALL
int
sys_munmap(userptr<void> addr, size_t len)
{
ANON_REGION(__func__, &perfgroup);
#if MTRACE
mt_ascope ascope("%s(%p,%#lx)", __func__, addr.unsafe_get(), len);
for (uptr i = addr / PGSIZE; i < PGROUNDUP(addr + len) / PGSIZE; i++)
mtwriteavar("pte:%p.%#lx", myproc()->vmap, i);
#endif
uptr align_addr = PGROUNDDOWN(addr);
uptr align_len = PGROUNDUP(addr + len) - align_addr;
if (myproc()->vmap->remove(align_addr, align_len) < 0)
return -1;
return 0;
}
//SYSCALL NORET
void
sys_halt(void)
{
halt();
panic("halt returned");
}
//SYSCALL
long
sys_cpuhz(void)
{
extern u64 cpuhz;
return cpuhz;
}
//SYSCALL
int
sys_setfs(u64 base)
{
proc *p = myproc();
p->user_fs_ = base;
switchvm(p);
return 0;
}
//SYSCALL
int
sys_setaffinity(int cpu)
{
return myproc()->set_cpu_pin(cpu);
}
//SYSCALL
long
sys_futex(const u64* addr, int op, u64 val, u64 timer)
{
futexkey_t key;
if (futexkey(addr, myproc()->vmap, &key) < 0)
return -1;
mt_ascope ascope("%s(%p,%d,%lu,%lu)", __func__, addr, op, val, timer);
switch(op) {
case FUTEX_WAIT:
return futexwait(key, val, timer);
case FUTEX_WAKE:
return futexwake(key, val);
default:
return -1;
}
}
//SYSCALL
long
sys_yield(void)
{
yield();
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "util/flet.h"
#include "util/scoped_map.h"
#include "kernel/environment.h"
#include "kernel/normalizer.h"
#include "kernel/builtin.h"
#include "kernel/kernel_exception.h"
#include "kernel/type_checker_trace.h"
#include "kernel/instantiate.h"
#include "kernel/free_vars.h"
#include "kernel/metavar.h"
#include "library/reduce.h"
#include "library/type_inferer.h"
namespace lean {
static name g_x_name("x");
class type_inferer::imp {
typedef scoped_map<expr, expr, expr_hash, expr_eqp> cache;
typedef buffer<unification_constraint> unification_constraints;
environment m_env;
context m_ctx;
metavar_env * m_menv;
unsigned m_menv_timestamp;
unification_constraints * m_uc;
normalizer m_normalizer;
cache m_cache;
volatile bool m_interrupted;
expr normalize(expr const & e, context const & ctx) {
return m_normalizer(e, ctx, m_menv);
}
expr check_type(expr const & e, expr const & s, context const & ctx) {
if (is_type(e))
return e;
if (e == Bool)
return Type();
expr u = normalize(e, ctx);
if (is_type(u))
return u;
if (u == Bool)
return Type();
if (has_metavar(u) && m_menv) {
trace tr = mk_type_expected_trace(ctx, s);
m_uc->push_back(mk_convertible_constraint(ctx, u, TypeU, tr));
return u;
}
throw type_expected_exception(m_env, ctx, s);
}
expr get_range(expr t, expr const & e, context const & ctx) {
unsigned num = num_args(e) - 1;
while (num > 0) {
--num;
if (is_pi(t)) {
t = abst_body(t);
} else {
t = m_normalizer(t, ctx);
if (is_pi(t)) {
t = abst_body(t);
} else if (has_metavar(t) && m_menv) {
// Create two fresh variables A and B,
// and assign r == (Pi(x : A), B x)
expr A = m_menv->mk_metavar(ctx);
expr B = m_menv->mk_metavar(ctx);
expr p = mk_pi(g_x_name, A, B(Var(0)));
trace tr = mk_function_expected_trace(ctx, e);
m_uc->push_back(mk_eq_constraint(ctx, t, p, tr));
t = abst_body(p);
} else {
throw function_expected_exception(m_env, ctx, e);
}
}
}
if (closed(t))
return t;
else
return instantiate(t, num_args(e)-1, &arg(e, 1));
}
void set_menv(metavar_env * menv) {
if (m_menv == menv) {
// Check whether m_menv has been updated since the last time the checker has been invoked
if (m_menv && m_menv->get_timestamp() > m_menv_timestamp) {
m_menv_timestamp = m_menv->get_timestamp();
m_cache.clear();
}
} else {
m_menv = menv;
m_cache.clear();
m_menv_timestamp = m_menv ? m_menv->get_timestamp() : 0;
}
}
expr infer_type(expr const & e, context const & ctx) {
// cheap cases, we do not cache results
switch (e.kind()) {
case expr_kind::MetaVar:
if (m_menv) {
if (m_menv->is_assigned(e))
return infer_type(m_menv->get_subst(e), ctx);
else
return m_menv->get_type(e);
} else {
throw kernel_exception(m_env, "unexpected metavariable occurrence");
}
case expr_kind::Constant: {
object const & obj = m_env.get_object(const_name(e));
if (obj.has_type())
return obj.get_type();
else
throw exception("type incorrect expression");
break;
}
case expr_kind::Var: {
context_entry const & ce = lookup(ctx, var_idx(e));
if (ce.get_domain())
return ce.get_domain();
// Remark: the case where ce.get_domain() is not
// available is not considered cheap.
break;
}
case expr_kind::Eq:
return mk_bool_type();
case expr_kind::Value:
return to_value(e).get_type();
case expr_kind::Type:
return mk_type(ty_level(e) + 1);
case expr_kind::App: case expr_kind::Lambda:
case expr_kind::Pi: case expr_kind::Let:
break; // expensive cases
}
check_interrupted(m_interrupted);
bool shared = false;
if (is_shared(e)) {
shared = true;
auto it = m_cache.find(e);
if (it != m_cache.end())
return it->second;
}
expr r;
switch (e.kind()) {
case expr_kind::Constant: case expr_kind::Eq:
case expr_kind::Value: case expr_kind::Type:
case expr_kind::MetaVar:
lean_unreachable();
case expr_kind::Var: {
auto p = lookup_ext(ctx, var_idx(e));
context_entry const & ce = p.first;
context const & ce_ctx = p.second;
lean_assert(!ce.get_domain());
r = lift_free_vars(infer_type(ce.get_body(), ce_ctx), ctx.size() - ce_ctx.size());
break;
}
case expr_kind::App: {
expr const & f = arg(e, 0);
expr f_t = infer_type(f, ctx);
r = get_range(f_t, e, ctx);
break;
}
case expr_kind::Lambda: {
cache::mk_scope sc(m_cache);
r = mk_pi(abst_name(e), abst_domain(e), infer_type(abst_body(e), extend(ctx, abst_name(e), abst_domain(e))));
break;
}
case expr_kind::Pi: {
expr t1 = check_type(infer_type(abst_domain(e), ctx), abst_domain(e), ctx);
expr t2;
{
cache::mk_scope sc(m_cache);
context new_ctx = extend(ctx, abst_name(e), abst_domain(e));
t2 = check_type(infer_type(abst_body(e), new_ctx), abst_body(e), new_ctx);
}
if (is_type(t1) && is_type(t2)) {
r = mk_type(max(ty_level(t1), ty_level(t2)));
} else {
lean_assert(m_uc);
trace tr = mk_max_type_trace(ctx, e);
r = m_menv->mk_metavar(ctx);
m_uc->push_back(mk_max_constraint(ctx, t1, t2, r, tr));
}
break;
}
case expr_kind::Let: {
cache::mk_scope sc(m_cache);
r = infer_type(let_body(e), extend(ctx, let_name(e), let_type(e), let_value(e)));
break;
}}
if (shared) {
m_cache.insert(e, r);
}
return r;
}
void set_ctx(context const & ctx) {
if (!is_eqp(m_ctx, ctx)) {
clear();
m_ctx = ctx;
}
}
public:
imp(environment const & env):
m_env(env),
m_normalizer(env) {
m_interrupted = false;
m_menv = nullptr;
m_menv_timestamp = 0;
m_uc = nullptr;
}
expr operator()(expr const & e, context const & ctx, metavar_env * menv, buffer<unification_constraint> & uc) {
set_ctx(ctx);
set_menv(menv);
flet<unification_constraints*> set(m_uc, &uc);
return infer_type(e, ctx);
}
void set_interrupt(bool flag) {
m_interrupted = flag;
m_normalizer.set_interrupt(flag);
}
void clear() {
m_cache.clear();
m_normalizer.clear();
m_ctx = context();
m_menv = nullptr;
m_menv_timestamp = 0;
}
};
type_inferer::type_inferer(environment const & env):m_ptr(new imp(env)) {}
type_inferer::~type_inferer() {}
expr type_inferer::operator()(expr const & e, context const & ctx, metavar_env * menv, buffer<unification_constraint> & uc) {
return m_ptr->operator()(e, ctx, menv, uc);
}
expr type_inferer::operator()(expr const & e, context const & ctx) {
buffer<unification_constraint> uc;
return operator()(e, ctx, nullptr, uc);
}
void type_inferer::clear() { m_ptr->clear(); }
void type_inferer::set_interrupt(bool flag) { m_ptr->set_interrupt(flag); }
}
<commit_msg>fix(type_inferer): bug when inferring the type of free variables<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "util/flet.h"
#include "util/scoped_map.h"
#include "kernel/environment.h"
#include "kernel/normalizer.h"
#include "kernel/builtin.h"
#include "kernel/kernel_exception.h"
#include "kernel/type_checker_trace.h"
#include "kernel/instantiate.h"
#include "kernel/free_vars.h"
#include "kernel/metavar.h"
#include "library/reduce.h"
#include "library/type_inferer.h"
namespace lean {
static name g_x_name("x");
class type_inferer::imp {
typedef scoped_map<expr, expr, expr_hash, expr_eqp> cache;
typedef buffer<unification_constraint> unification_constraints;
environment m_env;
context m_ctx;
metavar_env * m_menv;
unsigned m_menv_timestamp;
unification_constraints * m_uc;
normalizer m_normalizer;
cache m_cache;
volatile bool m_interrupted;
expr normalize(expr const & e, context const & ctx) {
return m_normalizer(e, ctx, m_menv);
}
expr check_type(expr const & e, expr const & s, context const & ctx) {
if (is_type(e))
return e;
if (e == Bool)
return Type();
expr u = normalize(e, ctx);
if (is_type(u))
return u;
if (u == Bool)
return Type();
if (has_metavar(u) && m_menv) {
trace tr = mk_type_expected_trace(ctx, s);
m_uc->push_back(mk_convertible_constraint(ctx, u, TypeU, tr));
return u;
}
throw type_expected_exception(m_env, ctx, s);
}
expr get_range(expr t, expr const & e, context const & ctx) {
unsigned num = num_args(e) - 1;
while (num > 0) {
--num;
if (is_pi(t)) {
t = abst_body(t);
} else {
t = m_normalizer(t, ctx);
if (is_pi(t)) {
t = abst_body(t);
} else if (has_metavar(t) && m_menv) {
// Create two fresh variables A and B,
// and assign r == (Pi(x : A), B x)
expr A = m_menv->mk_metavar(ctx);
expr B = m_menv->mk_metavar(ctx);
expr p = mk_pi(g_x_name, A, B(Var(0)));
trace tr = mk_function_expected_trace(ctx, e);
m_uc->push_back(mk_eq_constraint(ctx, t, p, tr));
t = abst_body(p);
} else {
throw function_expected_exception(m_env, ctx, e);
}
}
}
if (closed(t))
return t;
else
return instantiate(t, num_args(e)-1, &arg(e, 1));
}
void set_menv(metavar_env * menv) {
if (m_menv == menv) {
// Check whether m_menv has been updated since the last time the checker has been invoked
if (m_menv && m_menv->get_timestamp() > m_menv_timestamp) {
m_menv_timestamp = m_menv->get_timestamp();
m_cache.clear();
}
} else {
m_menv = menv;
m_cache.clear();
m_menv_timestamp = m_menv ? m_menv->get_timestamp() : 0;
}
}
expr infer_type(expr const & e, context const & ctx) {
// cheap cases, we do not cache results
switch (e.kind()) {
case expr_kind::MetaVar:
if (m_menv) {
if (m_menv->is_assigned(e))
return infer_type(m_menv->get_subst(e), ctx);
else
return m_menv->get_type(e);
} else {
throw kernel_exception(m_env, "unexpected metavariable occurrence");
}
case expr_kind::Constant: {
object const & obj = m_env.get_object(const_name(e));
if (obj.has_type())
return obj.get_type();
else
throw exception("type incorrect expression");
break;
}
case expr_kind::Var: {
auto p = lookup_ext(ctx, var_idx(e));
context_entry const & ce = p.first;
if (ce.get_domain()) {
context const & ce_ctx = p.second;
return lift_free_vars(ce.get_domain(), ctx.size() - ce_ctx.size());
}
// Remark: the case where ce.get_domain() is not
// available is not considered cheap.
break;
}
case expr_kind::Eq:
return mk_bool_type();
case expr_kind::Value:
return to_value(e).get_type();
case expr_kind::Type:
return mk_type(ty_level(e) + 1);
case expr_kind::App: case expr_kind::Lambda:
case expr_kind::Pi: case expr_kind::Let:
break; // expensive cases
}
check_interrupted(m_interrupted);
bool shared = false;
if (is_shared(e)) {
shared = true;
auto it = m_cache.find(e);
if (it != m_cache.end())
return it->second;
}
expr r;
switch (e.kind()) {
case expr_kind::Constant: case expr_kind::Eq:
case expr_kind::Value: case expr_kind::Type:
case expr_kind::MetaVar:
lean_unreachable();
case expr_kind::Var: {
auto p = lookup_ext(ctx, var_idx(e));
context_entry const & ce = p.first;
context const & ce_ctx = p.second;
lean_assert(!ce.get_domain());
r = lift_free_vars(infer_type(ce.get_body(), ce_ctx), ctx.size() - ce_ctx.size());
break;
}
case expr_kind::App: {
expr const & f = arg(e, 0);
expr f_t = infer_type(f, ctx);
r = get_range(f_t, e, ctx);
break;
}
case expr_kind::Lambda: {
cache::mk_scope sc(m_cache);
r = mk_pi(abst_name(e), abst_domain(e), infer_type(abst_body(e), extend(ctx, abst_name(e), abst_domain(e))));
break;
}
case expr_kind::Pi: {
expr t1 = check_type(infer_type(abst_domain(e), ctx), abst_domain(e), ctx);
expr t2;
{
cache::mk_scope sc(m_cache);
context new_ctx = extend(ctx, abst_name(e), abst_domain(e));
t2 = check_type(infer_type(abst_body(e), new_ctx), abst_body(e), new_ctx);
}
if (is_type(t1) && is_type(t2)) {
r = mk_type(max(ty_level(t1), ty_level(t2)));
} else {
lean_assert(m_uc);
trace tr = mk_max_type_trace(ctx, e);
r = m_menv->mk_metavar(ctx);
m_uc->push_back(mk_max_constraint(ctx, t1, t2, r, tr));
}
break;
}
case expr_kind::Let: {
cache::mk_scope sc(m_cache);
r = infer_type(let_body(e), extend(ctx, let_name(e), let_type(e), let_value(e)));
break;
}}
if (shared) {
m_cache.insert(e, r);
}
return r;
}
void set_ctx(context const & ctx) {
if (!is_eqp(m_ctx, ctx)) {
clear();
m_ctx = ctx;
}
}
public:
imp(environment const & env):
m_env(env),
m_normalizer(env) {
m_interrupted = false;
m_menv = nullptr;
m_menv_timestamp = 0;
m_uc = nullptr;
}
expr operator()(expr const & e, context const & ctx, metavar_env * menv, buffer<unification_constraint> & uc) {
set_ctx(ctx);
set_menv(menv);
flet<unification_constraints*> set(m_uc, &uc);
return infer_type(e, ctx);
}
void set_interrupt(bool flag) {
m_interrupted = flag;
m_normalizer.set_interrupt(flag);
}
void clear() {
m_cache.clear();
m_normalizer.clear();
m_ctx = context();
m_menv = nullptr;
m_menv_timestamp = 0;
}
};
type_inferer::type_inferer(environment const & env):m_ptr(new imp(env)) {}
type_inferer::~type_inferer() {}
expr type_inferer::operator()(expr const & e, context const & ctx, metavar_env * menv, buffer<unification_constraint> & uc) {
return m_ptr->operator()(e, ctx, menv, uc);
}
expr type_inferer::operator()(expr const & e, context const & ctx) {
buffer<unification_constraint> uc;
return operator()(e, ctx, nullptr, uc);
}
void type_inferer::clear() { m_ptr->clear(); }
void type_inferer::set_interrupt(bool flag) { m_ptr->set_interrupt(flag); }
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "styledbar.h"
#include <QPainter>
#include <QStyleOption>
using namespace Utils;
StyledBar::StyledBar(QWidget *parent)
: QWidget(parent)
{
setProperty("panelwidget", true);
setProperty("panelwidget_singlerow", true);
setProperty("lightColored", false);
}
void StyledBar::setSingleRow(bool singleRow)
{
setProperty("panelwidget_singlerow", singleRow);
}
bool StyledBar::isSingleRow() const
{
return property("panelwidget_singlerow").toBool();
}
void StyledBar::setLightColored(bool lightColored)
{
if (isLightColored() == lightColored)
return;
setProperty("lightColored", lightColored);
foreach (QWidget *childWidget, findChildren<QWidget *>())
childWidget->style()->polish(childWidget);
}
bool StyledBar::isLightColored() const
{
return property("lightColored").toBool();
}
void StyledBar::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
QStyleOption option;
option.rect = rect();
option.state = QStyle::State_Horizontal;
style()->drawControl(QStyle::CE_ToolBar, &option, &painter, this);
}
StyledSeparator::StyledSeparator(QWidget *parent)
: QWidget(parent)
{
setFixedWidth(10);
}
void StyledSeparator::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
QStyleOption option;
option.rect = rect();
option.state = QStyle::State_Horizontal;
option.palette = palette();
style()->drawPrimitive(QStyle::PE_IndicatorToolBarSeparator, &option, &painter, this);
}
<commit_msg>StyledBar: Explicitly set fixed height<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "styledbar.h"
#include <QPainter>
#include <QStyleOption>
using namespace Utils;
StyledBar::StyledBar(QWidget *parent)
: QWidget(parent)
{
setProperty("panelwidget", true);
setProperty("panelwidget_singlerow", true);
setProperty("lightColored", false);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
}
void StyledBar::setSingleRow(bool singleRow)
{
setProperty("panelwidget_singlerow", singleRow);
}
bool StyledBar::isSingleRow() const
{
return property("panelwidget_singlerow").toBool();
}
void StyledBar::setLightColored(bool lightColored)
{
if (isLightColored() == lightColored)
return;
setProperty("lightColored", lightColored);
foreach (QWidget *childWidget, findChildren<QWidget *>())
childWidget->style()->polish(childWidget);
}
bool StyledBar::isLightColored() const
{
return property("lightColored").toBool();
}
void StyledBar::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
QStyleOption option;
option.rect = rect();
option.state = QStyle::State_Horizontal;
style()->drawControl(QStyle::CE_ToolBar, &option, &painter, this);
}
StyledSeparator::StyledSeparator(QWidget *parent)
: QWidget(parent)
{
setFixedWidth(10);
}
void StyledSeparator::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
QStyleOption option;
option.rect = rect();
option.state = QStyle::State_Horizontal;
option.palette = palette();
style()->drawPrimitive(QStyle::PE_IndicatorToolBarSeparator, &option, &painter, this);
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 1999-2009 Soeren Sonnenburg
* Written (W) 1999-2008 Gunnar Raetsch
* Written (W) 2006-2007 Mikio L. Braun
* Written (W) 2008 Jochen Garcke
* Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include "lib/config.h"
#ifdef HAVE_LAPACK
#include "lib/lapack.h"
#include "lib/common.h"
#include "lib/io.h"
using namespace shogun;
#if defined(HAVE_MKL) || defined(HAVE_ACML)
#define DSYEV dsyev
#define DGESVD dgesvd
#define DPOSV dposv
#define DPOTRF dpotrf
#define DPOTRI dpotri
#define DGETRI dgetri
#define DGETRF dgetrf
#else
#define DSYEV dsyev_
#define DGESVD dgesvd_
#define DPOSV dposv_
#define DPOTRF dpotrf_
#define DPOTRI dpotri_
#define DGETRI dgetri_
#define DGETRF dgetrf_
#endif
#ifndef HAVE_ATLAS
int clapack_dpotrf(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo,
const int N, double *A, const int LDA)
{
char uplo = 'U';
int info = 0;
if (Order==CblasRowMajor)
{//A is symmetric, we switch Uplo to get result for CblasRowMajor
if (Uplo==CblasUpper)
uplo='L';
}
else if (Uplo==CblasLower)
{
uplo='L';
}
#ifdef HAVE_ACML
DPOTRF(uplo, N, A, LDA, &info);
#else
int n=N;
int lda=LDA;
DPOTRF(&uplo, &n, A, &lda, &info);
#endif
return info;
}
#undef DPOTRF
int clapack_dpotri(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo,
const int N, double *A, const int LDA)
{
char uplo = 'U';
int info = 0;
if (Order==CblasRowMajor)
{//A is symmetric, we switch Uplo to get result for CblasRowMajor
if (Uplo==CblasUpper)
uplo='L';
}
else if (Uplo==CblasLower)
{
uplo='L';
}
#ifdef HAVE_ACML
DPOTRI(uplo, N, A, LDA, &info);
#else
int n=N;
int lda=LDA;
DPOTRI(&uplo, &n, A, &lda, &info);
#endif
return info;
}
#undef DPOTRI
/* DPOSV computes the solution to a real system of linear equations
* A * X = B,
* where A is an N-by-N symmetric positive definite matrix and X and B
* are N-by-NRHS matrices
*/
int clapack_dposv(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo,
const int N, const int NRHS, double *A, const int lda,
double *B, const int ldb)
{
char uplo = 'U';
int info=0;
if (Order==CblasRowMajor)
{//A is symmetric, we switch Uplo to achieve CblasColMajor
if (Uplo==CblasUpper)
uplo='L';
}
else if (Uplo==CblasLower)
{
uplo='L';
}
#ifdef HAVE_ACML
DPOSV(uplo,N,NRHS,A,lda,B,ldb,&info);
#else
int n=N;
int nrhs=NRHS;
int LDA=lda;
int LDB=ldb;
DPOSV(&uplo, &n, &nrhs, A, &LDA, B, &LDB, &info);
#endif
return info;
}
#undef DPOSV
int clapack_dgetrf(const CBLAS_ORDER Order, const int M, const int N,
double *A, const int lda, int *ipiv)
{
// no rowmajor?
int info=0;
#ifdef HAVE_ACML
DGETRF(M,N,A,lda,ipiv,&info);
#else
int m=M;
int n=N;
int LDA=lda;
DGETRF(&m,&n,A,&LDA,ipiv,&info);
#endif
return info;
}
#undef DGETRF
int clapack_dgetri(const CBLAS_ORDER Order, const int N, double *A,
const int lda, int* ipiv)
{
// now rowmajor?
int info=0;
double* work = new double[1];
#ifdef HAVE_ACML
DGETRI(N,A,lda,ipiv,work,-1,&info);
int lwork = (int) work[0];
delete[] work;
work = new double[lwork];
DGETRI(N,A,lda,ipiv,work,lwork,&info);
#else
int n=N;
int LDA=lda;
DGETRI(&n,A,&LDA,ipiv,work,&(-1),&info);
int lwork = (int) work[0];
delete[] work;
work = new double[lwork];
DGETRI(&n,A,&LDA,ipiv,work,&lwork,&info);
#endif
return info;
}
#undef DGETRI
#endif //HAVE_ATLAS
/*
* Wrapper files for LAPACK if there isn't a clapack interface
*
*/
namespace shogun
{
/* DSYEV computes all eigenvalues and, optionally, eigenvectors of a
* real symmetric matrix A.
*/
void wrap_dsyev(char jobz, char uplo, int n, double *a, int lda, double *w, int *info)
{
#ifdef HAVE_ACML
DSYEV(jobz, uplo, n, a, lda, w, info);
#else
int lwork=-1;
double work1;
DSYEV(&jobz, &uplo, &n, a, &lda, w, &work1, &lwork, info);
ASSERT(*info==0);
ASSERT(work1>0);
lwork=(int) work1;
double* work=new double[lwork];
DSYEV(&jobz, &uplo, &n, a, &lda, w, work, &lwork, info);
delete[] work;
#endif
}
#undef DSYEV
void wrap_dgesvd(char jobu, char jobvt, int m, int n, double *a, int lda, double *sing,
double *u, int ldu, double *vt, int ldvt, int *info)
{
#ifdef HAVE_ACML
DGESVD(jobu, jobvt, m, n, a, lda, sing, u, ldu, vt, ldvt, info);
#else
int lwork=-1;
double work1;
DGESVD(&jobu, &jobvt, &m, &n, a, &lda, sing, u, &ldu, vt, &ldvt, &work1, &lwork, info);
ASSERT(*info==0);
ASSERT(work1>0);
lwork=(int) work1;
double* work=new double[lwork];
DGESVD(&jobu, &jobvt, &m, &n, a, &lda, sing, u, &ldu, vt, &ldvt, work, &lwork, info);
delete[] work;
#endif
}
}
#undef DGESVD
#endif //HAVE_LAPACK
<commit_msg>Another one crazy fix for dgetri wrapper<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 1999-2009 Soeren Sonnenburg
* Written (W) 1999-2008 Gunnar Raetsch
* Written (W) 2006-2007 Mikio L. Braun
* Written (W) 2008 Jochen Garcke
* Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include "lib/config.h"
#ifdef HAVE_LAPACK
#include "lib/lapack.h"
#include "lib/common.h"
#include "lib/io.h"
using namespace shogun;
#if defined(HAVE_MKL) || defined(HAVE_ACML)
#define DSYEV dsyev
#define DGESVD dgesvd
#define DPOSV dposv
#define DPOTRF dpotrf
#define DPOTRI dpotri
#define DGETRI dgetri
#define DGETRF dgetrf
#else
#define DSYEV dsyev_
#define DGESVD dgesvd_
#define DPOSV dposv_
#define DPOTRF dpotrf_
#define DPOTRI dpotri_
#define DGETRI dgetri_
#define DGETRF dgetrf_
#endif
#ifndef HAVE_ATLAS
int clapack_dpotrf(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo,
const int N, double *A, const int LDA)
{
char uplo = 'U';
int info = 0;
if (Order==CblasRowMajor)
{//A is symmetric, we switch Uplo to get result for CblasRowMajor
if (Uplo==CblasUpper)
uplo='L';
}
else if (Uplo==CblasLower)
{
uplo='L';
}
#ifdef HAVE_ACML
DPOTRF(uplo, N, A, LDA, &info);
#else
int n=N;
int lda=LDA;
DPOTRF(&uplo, &n, A, &lda, &info);
#endif
return info;
}
#undef DPOTRF
int clapack_dpotri(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo,
const int N, double *A, const int LDA)
{
char uplo = 'U';
int info = 0;
if (Order==CblasRowMajor)
{//A is symmetric, we switch Uplo to get result for CblasRowMajor
if (Uplo==CblasUpper)
uplo='L';
}
else if (Uplo==CblasLower)
{
uplo='L';
}
#ifdef HAVE_ACML
DPOTRI(uplo, N, A, LDA, &info);
#else
int n=N;
int lda=LDA;
DPOTRI(&uplo, &n, A, &lda, &info);
#endif
return info;
}
#undef DPOTRI
/* DPOSV computes the solution to a real system of linear equations
* A * X = B,
* where A is an N-by-N symmetric positive definite matrix and X and B
* are N-by-NRHS matrices
*/
int clapack_dposv(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo,
const int N, const int NRHS, double *A, const int lda,
double *B, const int ldb)
{
char uplo = 'U';
int info=0;
if (Order==CblasRowMajor)
{//A is symmetric, we switch Uplo to achieve CblasColMajor
if (Uplo==CblasUpper)
uplo='L';
}
else if (Uplo==CblasLower)
{
uplo='L';
}
#ifdef HAVE_ACML
DPOSV(uplo,N,NRHS,A,lda,B,ldb,&info);
#else
int n=N;
int nrhs=NRHS;
int LDA=lda;
int LDB=ldb;
DPOSV(&uplo, &n, &nrhs, A, &LDA, B, &LDB, &info);
#endif
return info;
}
#undef DPOSV
int clapack_dgetrf(const CBLAS_ORDER Order, const int M, const int N,
double *A, const int lda, int *ipiv)
{
// no rowmajor?
int info=0;
#ifdef HAVE_ACML
DGETRF(M,N,A,lda,ipiv,&info);
#else
int m=M;
int n=N;
int LDA=lda;
DGETRF(&m,&n,A,&LDA,ipiv,&info);
#endif
return info;
}
#undef DGETRF
int clapack_dgetri(const CBLAS_ORDER Order, const int N, double *A,
const int lda, int* ipiv)
{
// now rowmajor?
int info=0;
double* work = new double[1];
#ifdef HAVE_ACML
int lwork = -1;
DGETRI(N,A,lda,ipiv,work,lwork,&info);
lwork = (int) work[0];
delete[] work;
work = new double[lwork];
DGETRI(N,A,lda,ipiv,work,lwork,&info);
#else
int n=N;
int LDA=lda;
int lwork = -1;
DGETRI(&n,A,&LDA,ipiv,work,&lwork,&info);
lwork = (int) work[0];
delete[] work;
work = new double[lwork];
DGETRI(&n,A,&LDA,ipiv,work,&lwork,&info);
#endif
return info;
}
#undef DGETRI
#endif //HAVE_ATLAS
/*
* Wrapper files for LAPACK if there isn't a clapack interface
*
*/
namespace shogun
{
/* DSYEV computes all eigenvalues and, optionally, eigenvectors of a
* real symmetric matrix A.
*/
void wrap_dsyev(char jobz, char uplo, int n, double *a, int lda, double *w, int *info)
{
#ifdef HAVE_ACML
DSYEV(jobz, uplo, n, a, lda, w, info);
#else
int lwork=-1;
double work1;
DSYEV(&jobz, &uplo, &n, a, &lda, w, &work1, &lwork, info);
ASSERT(*info==0);
ASSERT(work1>0);
lwork=(int) work1;
double* work=new double[lwork];
DSYEV(&jobz, &uplo, &n, a, &lda, w, work, &lwork, info);
delete[] work;
#endif
}
#undef DSYEV
void wrap_dgesvd(char jobu, char jobvt, int m, int n, double *a, int lda, double *sing,
double *u, int ldu, double *vt, int ldvt, int *info)
{
#ifdef HAVE_ACML
DGESVD(jobu, jobvt, m, n, a, lda, sing, u, ldu, vt, ldvt, info);
#else
int lwork=-1;
double work1;
DGESVD(&jobu, &jobvt, &m, &n, a, &lda, sing, u, &ldu, vt, &ldvt, &work1, &lwork, info);
ASSERT(*info==0);
ASSERT(work1>0);
lwork=(int) work1;
double* work=new double[lwork];
DGESVD(&jobu, &jobvt, &m, &n, a, &lda, sing, u, &ldu, vt, &ldvt, work, &lwork, info);
delete[] work;
#endif
}
}
#undef DGESVD
#endif //HAVE_LAPACK
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "logjoin/LogJoinUpload.h"
#include "fnord-base/uri.h"
#include "fnord-base/util/binarymessagewriter.h"
#include "fnord-http/httprequest.h"
using namespace fnord;
namespace cm {
LogJoinUpload::LogJoinUpload(
RefPtr<mdb::MDB> db,
const String& feedserver_url,
http::HTTPConnectionPool* http) :
db_(db),
feedserver_url_(feedserver_url),
http_(http),
batch_size_(kDefaultBatchSize) {}
void LogJoinUpload::upload() {
while (scanQueue("__uploadq-sessions") > 0);
}
size_t LogJoinUpload::scanQueue(const String& queue_name) {
auto txn = db_->startTransaction();
auto cursor = txn->getCursor();
Buffer key;
Buffer value;
bool eof = false;
Vector<Buffer> batch;
for (int i = 0; i < batch_size_ && !eof; ++i) {
if (i == 0) {
key.append(queue_name);
eof = !cursor->getFirstOrGreater(&key, &value);
} else {
eof = !cursor->getNext(&key, &value);
}
if (!StringUtil::beginsWith(key.toString(), queue_name)) {
eof = true;
}
if (!eof) {
batch.emplace_back(value);
txn->del(key);
}
}
cursor->close();
try {
if (batch.size() > 0) {
uploadBatch(queue_name, batch);
}
} catch (...) {
txn->abort();
throw;
}
txn->commit();
return batch.size();
}
void LogJoinUpload::uploadBatch(
const String& queue_name,
const Vector<Buffer>& batch) {
URI uri(feedserver_url_ + "/tsdb/insert_batch?stream=joined_sessions.dawanda");
http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery());
req.addHeader("Host", uri.hostAndPort());
req.addHeader("Content-Type", "application/fnord-msg");
util::BinaryMessageWriter body;
for (const auto& b : batch) {
body.append(b.data(), b.size());
}
req.addBody(body.data(), body.size());
auto res = http_->executeRequest(req);
res.wait();
const auto& r = res.get();
if (r.statusCode() != 201) {
RAISEF(kRuntimeError, "received non-201 response: $0", r.body().toString());
}
}
} // namespace cm
<commit_msg>use mdb_cursor_del as mdb_del has some kind of bug<commit_after>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "logjoin/LogJoinUpload.h"
#include "fnord-base/uri.h"
#include "fnord-base/util/binarymessagewriter.h"
#include "fnord-http/httprequest.h"
using namespace fnord;
namespace cm {
LogJoinUpload::LogJoinUpload(
RefPtr<mdb::MDB> db,
const String& feedserver_url,
http::HTTPConnectionPool* http) :
db_(db),
feedserver_url_(feedserver_url),
http_(http),
batch_size_(kDefaultBatchSize) {}
void LogJoinUpload::upload() {
while (scanQueue("__uploadq-sessions") > 0);
}
size_t LogJoinUpload::scanQueue(const String& queue_name) {
auto txn = db_->startTransaction();
auto cursor = txn->getCursor();
Buffer key;
Buffer value;
Vector<Buffer> batch;
for (int i = 0; i < batch_size_; ++i) {
if (i == 0) {
key.append(queue_name);
if (!cursor->getFirstOrGreater(&key, &value)) {
break;
}
} else {
if (!cursor->getNext(&key, &value)) {
break;
}
}
if (!StringUtil::beginsWith(key.toString(), queue_name)) {
break;
}
batch.emplace_back(value);
cursor->del();
}
cursor->close();
try {
if (batch.size() > 0) {
uploadBatch(queue_name, batch);
}
} catch (...) {
txn->abort();
throw;
}
txn->commit();
return batch.size();
}
void LogJoinUpload::uploadBatch(
const String& queue_name,
const Vector<Buffer>& batch) {
URI uri(feedserver_url_ + "/tsdb/insert_batch?stream=joined_sessions.dawanda");
http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery());
req.addHeader("Host", uri.hostAndPort());
req.addHeader("Content-Type", "application/fnord-msg");
util::BinaryMessageWriter body;
for (const auto& b : batch) {
body.append(b.data(), b.size());
}
req.addBody(body.data(), body.size());
auto res = http_->executeRequest(req);
res.wait();
const auto& r = res.get();
if (r.statusCode() != 201) {
RAISEF(kRuntimeError, "received non-201 response: $0", r.body().toString());
}
}
} // namespace cm
<|endoftext|> |
<commit_before>/*
* objectList.cpp
*
* Created on: May 4, 2014
* Author: Srinivasan
*/
<commit_msg>removed unwanted file<commit_after><|endoftext|> |
<commit_before>#include "optionshierarchy.h"
#include "io.h"
#include <iostream>
using namespace std;
using namespace mlpack::io;
/* Ctors, Dtors, and R2D2 [actually, just copy-tors] */
/* Constructs an empty OptionsHierarchy node. */
OptionsHierarchy::OptionsHierarchy() : children() {
nodeData.node = "";
nodeData.desc = "";
nodeData.tname = "";
return;
}
/*
* Constructs an empty OptionsHierarchy node
*
* @param name The name of the node to be created.
*/
OptionsHierarchy::OptionsHierarchy(const char* name) : children() {
nodeData.node = string(name);
nodeData.desc = "";
nodeData.tname = "";
return;
}
/*
* Constructs an equivalent node to the given one.
*
* @param other The node to be copied
*/
OptionsHierarchy::OptionsHierarchy(const OptionsHierarchy& other) {
return;
}
/*
* Destroys the node.
*/
OptionsHierarchy::~OptionsHierarchy() {
return;
}
/*
* Will never fail, as given paths are relative to current node
* and will be generated if not found.
*
* @param pathname The full pathname of the given node, eg /foo/bar.
* @param tname A string unique to the type of the node.
*/
void OptionsHierarchy::AppendNode(string& pathname, string& tname) {
string tmp = string("");
OptionsData d;
d.node = pathname;
d.desc = tmp;
d.tname = tname;
AppendNode(pathname, tname, tmp, d);
}
/*
* Will never fail, as given paths are relative to current node
* and will be generated if not found.
*
* @param pathname The full pathname of the given node, eg /foo/bar.
* @param tname A string unique to the type of the node.
* @param description String description of the node.
*/
void OptionsHierarchy::AppendNode(string& pathname,
string& tname,
string& description) {
OptionsData d;
d.node = pathname;
d.desc = description;
d.tname = tname;
AppendNode(pathname, tname, description, d);
}
/*
* Will never fail, as given paths are relative to current node
* and will be generated if not found.
*
* @param pathname The full pathname of the given node, eg /foo/bar.
* @param tname A string unique to the type of the node.
* @param description String description of the node.
* @param data Specifies all fields of the new node.
*/
void OptionsHierarchy::AppendNode(string& pathname, string& tname,
string& description, OptionsData& data) {
string name = GetName(pathname);
string path = GetPath(pathname);
//Append the new name, if it isn't already there
if (children.count(name) == 0)
children[name] = OptionsHierarchy(name.c_str());
if (pathname.find('/') == pathname.npos || path.length() < 1) {
children[name].nodeData = data;
return;
}
//Recurse until path is done
children[name].AppendNode(path, tname, description, data);
}
/*
* Will return the node associated with a pathname
*
* @param pathname The full pathname of the node,
* eg foo/bar in foo/bar.
*
* @return Pointer to the node with that pathname,
* null if not found.
*/
OptionsHierarchy* OptionsHierarchy::FindNode(string& pathname) {
return FindNodeHelper(pathname, pathname);
}
OptionsHierarchy* OptionsHierarchy::FindNodeHelper(string& pathname,
string& target) {
string name = GetName(pathname);
string path = GetPath(pathname);
//If the node is there, recurse to it.
if (path.length() != 0 || name.length() != 0)
return children[name].FindNodeHelper(path, target);
if (target.compare(nodeData.node) == 0)
return this;
return NULL;
}
/*
* Returns the various data associated with a node. Passed by copy,
* since this is only for unit testing.
*
* @return The data associated with the node,
* eg it's name, description, and value.
*/
OptionsData OptionsHierarchy::GetNodeData() {
return nodeData;
}
/* Returns the path bar/fizz in the pathname foo/bar/fizz
*
* @param pathname The full pathname of the parameter,
* eg foo/bar in foo/bar.
*
* @return The identifiers of all nodes after the next node in the path,
* eg fizz/bar in foo/fizz/bar.
*/
string OptionsHierarchy::GetPath(string& pathname) {
//Want to make sure we return a valid string
if (pathname.find('/') == pathname.npos)
return string("");
//Get the rest of the node name Eg foo/bar in root/foo/bar
return pathname.substr(pathname.find('/')+1,pathname.length());
}
/* Returns the name foo in the pathname foo/bar/fizz
*
* @param pathname The full pathname of the parameter,
* eg foo/bar in foo/bar.
*
* @return The name of the next node in the path
* eg foo in foo/bar.
*/
string OptionsHierarchy::GetName(string& pathname) {
//Want to makesure we return a valid string
if (pathname.find('/') == pathname.npos)
return pathname;
//Get the topmost node name in this path Eg root in root/foo/bar
return pathname.substr(0, pathname.find('/'));
}
/*
* Obtains a vector containing relative pathnames of nodes subordinant to
* the one specified in the parameter.
*
* @param pathname The full pathname to the node in question.
*
* @return Vector containing relative pathnames of subordinant nodes.
*/
std::vector<std::string>
OptionsHierarchy::GetRelativePaths(std::string& pathname) {
std::vector<std::string> ret;
//Obtain the starting node.
OptionsHierarchy* node = FindNode(pathname);
if(node == NULL)
return ret;
//Start adding it's children etc.
return GetRelativePathsHelper(*node);
}
std::vector<std::string>
OptionsHierarchy::GetRelativePathsHelper(OptionsHierarchy& node) {
std::vector<std::string> ret;
std::vector<std::string> tmp;
tmp.push_back(node.nodeData.node);
ChildMap::iterator iter;
for(iter = node.children.begin(); iter != node.children.end(); iter++)
tmp = GetRelativePathsHelper((*iter).second);
while(tmp.size()) {
ret.push_back(tmp.back());
tmp.pop_back();
}
return ret;
}
/*
* Prints a node, followed by it's entries and submodules.
*/
void OptionsHierarchy::Print() {
//Print the node, append '/' if that node is not a leaf
PrintNode();
//Begin formatted output
cout << "Entries:" << endl;
PrintLeaves();
cout << "Submodules:" << endl;
PrintBranches();
}
/*
* Prints every node and it's value, if any.
*/
void OptionsHierarchy::PrintAll() {
PrintNode();
map<string, OptionsHierarchy>::iterator iter;
for (iter = children.begin(); iter != children.end(); iter++) {
iter->second.PrintAll();
}
}
/*
* Prints every node and it's description.
*/
void OptionsHierarchy::PrintAllHelp() {
// Special case for the top of the hierarchy.
if (nodeData.node == "Allowed Options")
cout << "Allowed Options:" << endl << endl;
else
PrintNodeHelp();
// Now print all the children.
map<string, OptionsHierarchy>::iterator iter;
// First print modules.
for (iter = children.begin(); iter != children.end(); iter++) {
if (iter->second.children.size() > 0)
iter->second.PrintAllHelp();
}
// Now print leaves.
// If this is the root node, we have to mention that these are default
// options.
if (nodeData.node == "Allowed Options")
cout << "Other options:" << endl << endl;
for (iter = children.begin(); iter != children.end(); iter++) {
if (iter->second.children.size() == 0)
iter->second.PrintAllHelp();
}
if (children.size() > 0) // If this was a module.
cout << endl; // Newline for separation from other modules.
}
/* Prints all children of this node which are parents */
void OptionsHierarchy::PrintBranches() {
map<string, OptionsHierarchy>::iterator iter;
//Iterate through all children
for (iter = children.begin(); iter != children.end(); iter++)
//Does this child have children?
if (iter->second.children.size()) {
iter->second.PrintNode();
}
}
/* Prints all children nodes that have no children themselves */
void OptionsHierarchy::PrintLeaves() {
map<string, OptionsHierarchy>::iterator iter;
for (iter = children.begin(); iter != children.end(); iter++) {
if (!iter->second.children.size()) {
//Print the node's name, data, and description.
iter->second.PrintNode();
} else {
iter->second.PrintLeaves();
}
}
}
/*
* Prints a node and its value.
*/
void OptionsHierarchy::PrintNode() {
IO::Info << " " << nodeData.node << " = " ;
if (nodeData.tname == TYPENAME(bool))
IO::Info << boolalpha << IO::GetParam<bool>(nodeData.node.c_str());
else if (nodeData.tname == TYPENAME(int))
IO::Info << IO::GetParam<int>(nodeData.node.c_str());
else if (nodeData.tname == TYPENAME(std::string)) {
std::string value = IO::GetParam<std::string>(nodeData.node.c_str());
if (value == "")
value = "\"\""; // So that the user isn't presented with an empty space.
IO::Info << value;
} else if (nodeData.tname == TYPENAME(float))
IO::Info << IO::GetParam<float>(nodeData.node.c_str());
IO::Info << endl;
}
/*
* Prints a node and its description. The format is similar to that help given
* by the ImageMagick suite of programs.
*/
void OptionsHierarchy::PrintNodeHelp() {
// We want to print differently if this is a module node (i.e. if it has any
// children).
if (children.size() > 0) {
if (nodeData.node == "default") // Special case for default module.
cout << "Default options:" << endl;
else // Other standard module title output.
cout << '\'' << nodeData.node << "' module: " << endl;
cout << " ";
if (nodeData.desc.length() > 0)
cout << HyphenateString(nodeData.desc, 2) << endl << endl;
else
cout << "Undocumented module." << endl << endl;
return; // Nothing else to do.
}
// Name of node gets printed first, with two spaces in front.
// If there is a parameter, we specify that below. We keep track of the
// length of what we've written.
cout << " --" << nodeData.node << " ";
int len = 5 + nodeData.node.length();
// Perhaps this should be moved somewhere more central, as it may need to be
// used more than just here.
string value = "[value]";
if (nodeData.tname == TYPENAME(bool))
value = "";
else if (nodeData.tname == TYPENAME(int))
value = "[int]";
else if (nodeData.tname == TYPENAME(float))
value = "[float]";
else if (nodeData.tname == TYPENAME(double))
value = "[double]";
else if (nodeData.tname == TYPENAME(std::string))
value = "[string]";
cout << value;
len += value.length();
// So, we only want to use a new line if we have used more than 30 characters
// already. Descriptions start at character 30.
if (len < 30) {
cout << std::string(30 - len, ' ');
if (nodeData.desc.length() > 0)
cout << HyphenateString(nodeData.desc, 30) << endl;
else
cout << "Undocumented option." << endl;
} else {
cout << endl << std::string(30, ' ');
if (nodeData.desc.length() > 0)
cout << HyphenateString(nodeData.desc, 30) << endl;
else
cout << "Undocumented option." << endl;
}
}
/**
* Hyphenate a string or split it onto multiple 80-character lines, with some
* amount of padding on each line. This is used for option output.
*
* @param str String to hyphenate (splits are on ' ').
* @param padding Amount of padding on the left for each new line.
*/
string OptionsHierarchy::HyphenateString(string str, int padding) {
size_t margin = 80 - padding;
if (str.length() < margin)
return str;
string out("");
unsigned int pos = 0;
// First try to look as far as possible.
while(pos < str.length() - 1) {
size_t splitpos;
// Check that we don't have a newline first.
splitpos = str.find('\n', pos);
if (splitpos == string::npos || splitpos > (pos + margin)) {
// We did not find a newline.
if (str.length() - pos < margin) {
splitpos = str.length(); // The rest fits on one line.
} else {
splitpos = str.rfind(' ', margin + pos); // Find nearest space.
if (splitpos <= pos || splitpos == string::npos) // Not found.
splitpos = pos + margin;
}
}
out += str.substr(pos, (splitpos - pos));
if (splitpos != str.length() - 1) {
out += '\n';
out += string(padding, ' ');
}
pos = splitpos;
if (str[pos] == ' ' || str[pos] == '\n')
pos++;
}
return out;
}
<commit_msg>Output doubles too<commit_after>#include "optionshierarchy.h"
#include "io.h"
#include <iostream>
using namespace std;
using namespace mlpack::io;
/* Ctors, Dtors, and R2D2 [actually, just copy-tors] */
/* Constructs an empty OptionsHierarchy node. */
OptionsHierarchy::OptionsHierarchy() : children() {
nodeData.node = "";
nodeData.desc = "";
nodeData.tname = "";
return;
}
/*
* Constructs an empty OptionsHierarchy node
*
* @param name The name of the node to be created.
*/
OptionsHierarchy::OptionsHierarchy(const char* name) : children() {
nodeData.node = string(name);
nodeData.desc = "";
nodeData.tname = "";
return;
}
/*
* Constructs an equivalent node to the given one.
*
* @param other The node to be copied
*/
OptionsHierarchy::OptionsHierarchy(const OptionsHierarchy& other) {
return;
}
/*
* Destroys the node.
*/
OptionsHierarchy::~OptionsHierarchy() {
return;
}
/*
* Will never fail, as given paths are relative to current node
* and will be generated if not found.
*
* @param pathname The full pathname of the given node, eg /foo/bar.
* @param tname A string unique to the type of the node.
*/
void OptionsHierarchy::AppendNode(string& pathname, string& tname) {
string tmp = string("");
OptionsData d;
d.node = pathname;
d.desc = tmp;
d.tname = tname;
AppendNode(pathname, tname, tmp, d);
}
/*
* Will never fail, as given paths are relative to current node
* and will be generated if not found.
*
* @param pathname The full pathname of the given node, eg /foo/bar.
* @param tname A string unique to the type of the node.
* @param description String description of the node.
*/
void OptionsHierarchy::AppendNode(string& pathname,
string& tname,
string& description) {
OptionsData d;
d.node = pathname;
d.desc = description;
d.tname = tname;
AppendNode(pathname, tname, description, d);
}
/*
* Will never fail, as given paths are relative to current node
* and will be generated if not found.
*
* @param pathname The full pathname of the given node, eg /foo/bar.
* @param tname A string unique to the type of the node.
* @param description String description of the node.
* @param data Specifies all fields of the new node.
*/
void OptionsHierarchy::AppendNode(string& pathname, string& tname,
string& description, OptionsData& data) {
string name = GetName(pathname);
string path = GetPath(pathname);
//Append the new name, if it isn't already there
if (children.count(name) == 0)
children[name] = OptionsHierarchy(name.c_str());
if (pathname.find('/') == pathname.npos || path.length() < 1) {
children[name].nodeData = data;
return;
}
//Recurse until path is done
children[name].AppendNode(path, tname, description, data);
}
/*
* Will return the node associated with a pathname
*
* @param pathname The full pathname of the node,
* eg foo/bar in foo/bar.
*
* @return Pointer to the node with that pathname,
* null if not found.
*/
OptionsHierarchy* OptionsHierarchy::FindNode(string& pathname) {
return FindNodeHelper(pathname, pathname);
}
OptionsHierarchy* OptionsHierarchy::FindNodeHelper(string& pathname,
string& target) {
string name = GetName(pathname);
string path = GetPath(pathname);
//If the node is there, recurse to it.
if (path.length() != 0 || name.length() != 0)
return children[name].FindNodeHelper(path, target);
if (target.compare(nodeData.node) == 0)
return this;
return NULL;
}
/*
* Returns the various data associated with a node. Passed by copy,
* since this is only for unit testing.
*
* @return The data associated with the node,
* eg it's name, description, and value.
*/
OptionsData OptionsHierarchy::GetNodeData() {
return nodeData;
}
/* Returns the path bar/fizz in the pathname foo/bar/fizz
*
* @param pathname The full pathname of the parameter,
* eg foo/bar in foo/bar.
*
* @return The identifiers of all nodes after the next node in the path,
* eg fizz/bar in foo/fizz/bar.
*/
string OptionsHierarchy::GetPath(string& pathname) {
//Want to make sure we return a valid string
if (pathname.find('/') == pathname.npos)
return string("");
//Get the rest of the node name Eg foo/bar in root/foo/bar
return pathname.substr(pathname.find('/')+1,pathname.length());
}
/* Returns the name foo in the pathname foo/bar/fizz
*
* @param pathname The full pathname of the parameter,
* eg foo/bar in foo/bar.
*
* @return The name of the next node in the path
* eg foo in foo/bar.
*/
string OptionsHierarchy::GetName(string& pathname) {
//Want to makesure we return a valid string
if (pathname.find('/') == pathname.npos)
return pathname;
//Get the topmost node name in this path Eg root in root/foo/bar
return pathname.substr(0, pathname.find('/'));
}
/*
* Obtains a vector containing relative pathnames of nodes subordinant to
* the one specified in the parameter.
*
* @param pathname The full pathname to the node in question.
*
* @return Vector containing relative pathnames of subordinant nodes.
*/
std::vector<std::string>
OptionsHierarchy::GetRelativePaths(std::string& pathname) {
std::vector<std::string> ret;
//Obtain the starting node.
OptionsHierarchy* node = FindNode(pathname);
if(node == NULL)
return ret;
//Start adding it's children etc.
return GetRelativePathsHelper(*node);
}
std::vector<std::string>
OptionsHierarchy::GetRelativePathsHelper(OptionsHierarchy& node) {
std::vector<std::string> ret;
std::vector<std::string> tmp;
tmp.push_back(node.nodeData.node);
ChildMap::iterator iter;
for(iter = node.children.begin(); iter != node.children.end(); iter++)
tmp = GetRelativePathsHelper((*iter).second);
while(tmp.size()) {
ret.push_back(tmp.back());
tmp.pop_back();
}
return ret;
}
/*
* Prints a node, followed by it's entries and submodules.
*/
void OptionsHierarchy::Print() {
//Print the node, append '/' if that node is not a leaf
PrintNode();
//Begin formatted output
cout << "Entries:" << endl;
PrintLeaves();
cout << "Submodules:" << endl;
PrintBranches();
}
/*
* Prints every node and it's value, if any.
*/
void OptionsHierarchy::PrintAll() {
PrintNode();
map<string, OptionsHierarchy>::iterator iter;
for (iter = children.begin(); iter != children.end(); iter++) {
iter->second.PrintAll();
}
}
/*
* Prints every node and it's description.
*/
void OptionsHierarchy::PrintAllHelp() {
// Special case for the top of the hierarchy.
if (nodeData.node == "Allowed Options")
cout << "Allowed Options:" << endl << endl;
else
PrintNodeHelp();
// Now print all the children.
map<string, OptionsHierarchy>::iterator iter;
// First print modules.
for (iter = children.begin(); iter != children.end(); iter++) {
if (iter->second.children.size() > 0)
iter->second.PrintAllHelp();
}
// Now print leaves.
// If this is the root node, we have to mention that these are default
// options.
if (nodeData.node == "Allowed Options")
cout << "Other options:" << endl << endl;
for (iter = children.begin(); iter != children.end(); iter++) {
if (iter->second.children.size() == 0)
iter->second.PrintAllHelp();
}
if (children.size() > 0) // If this was a module.
cout << endl; // Newline for separation from other modules.
}
/* Prints all children of this node which are parents */
void OptionsHierarchy::PrintBranches() {
map<string, OptionsHierarchy>::iterator iter;
// Iterate through all children
for (iter = children.begin(); iter != children.end(); iter++)
// Does this child have children?
if (iter->second.children.size()) {
iter->second.PrintNode();
}
}
/* Prints all children nodes that have no children themselves */
void OptionsHierarchy::PrintLeaves() {
map<string, OptionsHierarchy>::iterator iter;
for (iter = children.begin(); iter != children.end(); iter++) {
if (!iter->second.children.size()) {
// Print the node's name, data, and description.
iter->second.PrintNode();
} else {
iter->second.PrintLeaves();
}
}
}
/*
* Prints a node and its value.
*/
void OptionsHierarchy::PrintNode() {
IO::Info << " " << nodeData.node << " = " ;
if (nodeData.tname == TYPENAME(bool))
IO::Info << boolalpha << IO::GetParam<bool>(nodeData.node.c_str());
else if (nodeData.tname == TYPENAME(int))
IO::Info << IO::GetParam<int>(nodeData.node.c_str());
else if (nodeData.tname == TYPENAME(std::string)) {
std::string value = IO::GetParam<std::string>(nodeData.node.c_str());
if (value == "")
value = "\"\""; // So that the user isn't presented with an empty space.
IO::Info << value;
} else if (nodeData.tname == TYPENAME(float))
IO::Info << IO::GetParam<float>(nodeData.node.c_str());
else if (nodeData.tname == TYPENAME(double))
IO::Info << IO::GetParam<double>(nodeData.node.c_str());
IO::Info << endl;
}
/*
* Prints a node and its description. The format is similar to that help given
* by the ImageMagick suite of programs.
*/
void OptionsHierarchy::PrintNodeHelp() {
// We want to print differently if this is a module node (i.e. if it has any
// children).
if (children.size() > 0) {
if (nodeData.node == "default") // Special case for default module.
cout << "Default options:" << endl;
else // Other standard module title output.
cout << '\'' << nodeData.node << "' module: " << endl;
cout << " ";
if (nodeData.desc.length() > 0)
cout << HyphenateString(nodeData.desc, 2) << endl << endl;
else
cout << "Undocumented module." << endl << endl;
return; // Nothing else to do.
}
// Name of node gets printed first, with two spaces in front.
// If there is a parameter, we specify that below. We keep track of the
// length of what we've written.
cout << " --" << nodeData.node << " ";
int len = 5 + nodeData.node.length();
// Perhaps this should be moved somewhere more central, as it may need to be
// used more than just here.
string value = "[value]";
if (nodeData.tname == TYPENAME(bool))
value = "";
else if (nodeData.tname == TYPENAME(int))
value = "[int]";
else if (nodeData.tname == TYPENAME(float))
value = "[float]";
else if (nodeData.tname == TYPENAME(double))
value = "[double]";
else if (nodeData.tname == TYPENAME(std::string))
value = "[string]";
cout << value;
len += value.length();
// So, we only want to use a new line if we have used more than 30 characters
// already. Descriptions start at character 30.
if (len < 30) {
cout << std::string(30 - len, ' ');
if (nodeData.desc.length() > 0)
cout << HyphenateString(nodeData.desc, 30) << endl;
else
cout << "Undocumented option." << endl;
} else {
cout << endl << std::string(30, ' ');
if (nodeData.desc.length() > 0)
cout << HyphenateString(nodeData.desc, 30) << endl;
else
cout << "Undocumented option." << endl;
}
}
/**
* Hyphenate a string or split it onto multiple 80-character lines, with some
* amount of padding on each line. This is used for option output.
*
* @param str String to hyphenate (splits are on ' ').
* @param padding Amount of padding on the left for each new line.
*/
string OptionsHierarchy::HyphenateString(string str, int padding) {
size_t margin = 80 - padding;
if (str.length() < margin)
return str;
string out("");
unsigned int pos = 0;
// First try to look as far as possible.
while(pos < str.length() - 1) {
size_t splitpos;
// Check that we don't have a newline first.
splitpos = str.find('\n', pos);
if (splitpos == string::npos || splitpos > (pos + margin)) {
// We did not find a newline.
if (str.length() - pos < margin) {
splitpos = str.length(); // The rest fits on one line.
} else {
splitpos = str.rfind(' ', margin + pos); // Find nearest space.
if (splitpos <= pos || splitpos == string::npos) // Not found.
splitpos = pos + margin;
}
}
out += str.substr(pos, (splitpos - pos));
if (splitpos != str.length() - 1) {
out += '\n';
out += string(padding, ' ');
}
pos = splitpos;
if (str[pos] == ' ' || str[pos] == '\n')
pos++;
}
return out;
}
<|endoftext|> |
<commit_before>#include <algorithm> //std::sort
#include <iomanip> //std::setw
#include <iostream> //std::cout, std::cerr
#include <sstream> //std::stringstream
#include <string> //std::string
#include <vector> //std::vector
#include <dirent.h> //dirent, opendir, readdir
#include <errno.h> //errno
#include <grp.h> //getgrgid
#include <pwd.h> //getpwuid
#include <stdio.h> //perror
#include <string.h> //strlen
#include <sys/ioctl.h> //winsize, ioctl
#include <sys/stat.h> //st_mode, st_mtime, S_IFDIR, S_IRUSR, ...
#include <time.h> //time_t, tm
#include "parse.h" //File, FLAG_a, FLAG_l, FLAG_r
#include "execute.h"
void execute(std::vector<File>& regular_files,
std::vector<File>& directories,
int flags) {
std::sort(regular_files.begin(), regular_files.end(), by_name);
std::sort(directories.begin(), directories.end(), by_name);
if (!regular_files.empty()) {
print_files(regular_files, flags);
for (size_t i = 0; i < directories.size(); ++i)
print_directory(directories[i], flags, true);
}
else {
if (directories.empty()) {
File current; current.name = "."; current.path = ".";
print_directory(current, flags);
}
else if (directories.size() == 1)
print_directory(directories[0], flags);
else {
std::cout << directories[0].path << ": " << std::endl;
print_directory(directories[0], flags);
for (size_t i = 1; i < directories.size(); ++i)
print_directory(directories[i], flags, true);
}
}
}
void print_directory(const File& directory, int flags, bool extra) {
DIR *dir_ptr = opendir(directory.path.c_str());
if (dir_ptr == NULL) {
perror("opendir");
return;
}
if (extra)
std::cout << std::endl << directory.path << ": " << std::endl;
std::vector<File> files;
std::vector<File> directories;
dirent *entry;
while ((entry = readdir(dir_ptr))) {
if (entry->d_name[0] != '.' || (flags & FLAG_a)) {
File file;
std::string path = directory.path;
path += "/" + (std::string)entry->d_name;
file.name = entry->d_name;
file.path = path;
struct stat s;
if (stat(file.path.c_str(), &s) == 0) {
if (s.st_mode & S_IFDIR) {
file.name += '/';
file.color += BLUE;
if (flags & FLAG_R &&
file.name != "./" && file.name != "../") {
directories.push_back(file);
}
}
else if (s.st_mode & S_IXUSR) {
file.name += '*';
file.color += GREEN;
}
else file.color += BLACK;
files.push_back(file);
}
else
perror("stat");
}
}
if (errno) {
perror("readdir");
return;
}
if (closedir(dir_ptr) == -1) {
perror("closedir");
return;
}
std::sort(files.begin(), files.end(), by_name);
std::sort(directories.begin(), directories.end(), by_name);
print_files(files, flags);
for (size_t i = 0; i < directories.size(); ++i)
print_directory(directories[i], flags, true);
}
void print_files(const std::vector<File>& files, int flags) {
if (flags & FLAG_l) {
print_files_long(files); return;
}
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
int max_width = w.ws_col;
unsigned n_rows = 1;
std::vector<unsigned> column_width(files.size()+1);
while (n_rows < files.size()) {
int column = -1;
for (size_t i = 0; i < files.size(); ++i) {
if (i % n_rows == 0) ++column;
if (column_width[column] < files[i].name.size()+2)
column_width[column] = files[i].name.size()+2;
}
int total_width = 0;
for (size_t i = 0; column_width[i] != 0; ++i)
total_width += column_width[i];
if (total_width <= max_width) break;
for (size_t i = 0; column_width[i] != 0; ++i)
column_width[i] = 0;
++n_rows;
}
for (size_t i = 0; i < n_rows; ++i) {
for (size_t j = i; j < files.size(); j += n_rows) {
size_t column = j / n_rows;
std::cout << files[j].color;
struct stat s;
if (stat(files[i].path.c_str(), &s) == 0) {
if (s.st_mode & (S_IFDIR | S_IXUSR)) {
std::cout << files[j].name.substr(0,
files[j].name.size()-1) << BLACK
<< files[j].name[files[j].name.size()-1];
}
else {
std::cout << files[j].name << BLACK;
}
std::cout << std::setw(column_width[column] -
files[j].name.size()) << " ";
}
}
std::cout << std::endl;
}
}
void print_files_long(const std::vector<File>& files) {
blkcnt_t total_blocks = 0;
const char* months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
std::vector<std::string> permissions;
std::vector<nlink_t> links;
std::vector<const char*> users;
std::vector<const char*> groups;
std::vector<off_t> sizes;
size_t link_max = 0;
size_t user_max = 0;
size_t group_max = 0;
size_t size_max = 0;
std::vector<std::string> dates;
for (size_t i = 0; i < files.size(); ++i) {
struct stat s;
if (stat(files[i].path.c_str(), &s) == 0) {
total_blocks += s.st_blocks;
std::stringstream ss;
std::string permission;
permission += (s.st_mode & S_IFDIR ? 'd' : '-');
permission += (s.st_mode & S_IRUSR ? 'r' : '-');
permission += (s.st_mode & S_IWUSR ? 'w' : '-');
permission += (s.st_mode & S_IXUSR ? 'x' : '-');
permission += (s.st_mode & S_IRGRP ? 'r' : '-');
permission += (s.st_mode & S_IWGRP ? 'w' : '-');
permission += (s.st_mode & S_IXGRP ? 'x' : '-');
permission += (s.st_mode & S_IROTH ? 'r' : '-');
permission += (s.st_mode & S_IWOTH ? 'w' : '-');
permission += (s.st_mode & S_IXOTH ? 'x' : '-');
permissions.push_back(permission);
ss << s.st_nlink; std::string slink = ss.str(); ss.str("");
if (link_max < slink.size()) link_max = slink.size();
links.push_back(s.st_nlink);
const char* user = getpwuid(s.st_uid)->pw_name;
if (user_max < strlen(user)) user_max = strlen(user);
users.push_back(user);
const char* group = getgrgid(s.st_gid)->gr_name;
if (group_max < strlen(group)) group_max = strlen(group);
groups.push_back(group);
ss << s.st_size; std::string ssize = ss.str(); ss.str("");
if (size_max < ssize.size()) size_max = ssize.size();
sizes.push_back(s.st_size);
time_t mtime = s.st_mtime;
tm *ltm = localtime(&mtime);
std::string date;
date += months[ltm->tm_mon]; date += ' ';
if (ltm->tm_mday < 10) date += ' ';
ss << ltm->tm_mday << ' '; date += ss.str(); ss.str("");
if (ltm->tm_hour < 10) date += '0';
ss << ltm->tm_hour << ':'; date += ss.str(); ss.str("");
if (ltm->tm_min < 10) date += '0';
ss << ltm->tm_min; date += ss.str(); ss.str("");
dates.push_back(date);
}
else {
perror("stat");
return;
}
}
std::cout << "total " << total_blocks << std::endl;
for (size_t i = 0; i < files.size(); ++i) {
std::cout << permissions[i] << ' '
<< std::setw(link_max) << links[i] << ' '
<< std::setw(user_max) << users[i] << ' '
<< std::setw(group_max) << groups[i] << ' '
<< std::setw(size_max) << sizes[i] << ' '
<< dates[i] << ' ';
std::cout << files[i].color << files[i].name << BLACK << std::endl;
}
}
bool by_name(const File& left, const File& right) {
std::string upper_left, upper_right;
for (size_t i = 0; i < left.name.size(); ++i) {
if (left.name[i] == '.') continue;
upper_left += toupper(left.name[i]);
}
for (size_t i = 0; i < right.name.size(); ++i) {
if (right.name[i] == '.') continue;
upper_right += toupper(right.name[i]);
}
if (upper_left == upper_right) return left.name > right.name;
else return upper_left < upper_right;
}
<commit_msg>fixed sort<commit_after>#include <algorithm> //std::sort
#include <iomanip> //std::setw
#include <iostream> //std::cout, std::cerr
#include <sstream> //std::stringstream
#include <string> //std::string
#include <vector> //std::vector
#include <ctype.h> //isalnum
#include <dirent.h> //dirent, opendir, readdir
#include <errno.h> //errno
#include <grp.h> //getgrgid
#include <pwd.h> //getpwuid
#include <stdio.h> //perror
#include <string.h> //strlen
#include <sys/ioctl.h> //winsize, ioctl
#include <sys/stat.h> //st_mode, st_mtime, S_IFDIR, S_IRUSR, ...
#include <time.h> //time_t, tm
#include "parse.h" //File, FLAG_a, FLAG_l, FLAG_r
#include "execute.h"
void execute(std::vector<File>& regular_files,
std::vector<File>& directories,
int flags) {
std::sort(regular_files.begin(), regular_files.end(), by_name);
std::sort(directories.begin(), directories.end(), by_name);
if (!regular_files.empty()) {
print_files(regular_files, flags);
for (size_t i = 0; i < directories.size(); ++i)
print_directory(directories[i], flags, true);
}
else {
if (directories.empty()) {
File current; current.name = "."; current.path = ".";
bool extra = flags & FLAG_R;
print_directory(current, flags, extra);
}
else if (directories.size() == 1) {
bool extra = flags & FLAG_R;
print_directory(directories[0], flags, extra);
}
else {
for (size_t i = 0; i < directories.size(); ++i)
print_directory(directories[i], flags, true);
}
}
}
void print_directory(const File& directory, int flags, bool extra) {
DIR *dir_ptr = opendir(directory.path.c_str());
if (dir_ptr == NULL) {
perror("opendir");
return;
}
if (extra)
std::cout << std::endl << directory.path << ": " << std::endl;
std::vector<File> files;
std::vector<File> directories;
dirent *entry;
while ((entry = readdir(dir_ptr))) {
if (entry->d_name[0] != '.' || (flags & FLAG_a)) {
File file;
std::string path = directory.path;
path += "/" + (std::string)entry->d_name;
file.name = entry->d_name;
file.path = path;
struct stat s;
if (stat(file.path.c_str(), &s) == 0) {
if (s.st_mode & S_IFDIR) {
file.name += '/';
file.color += BLUE;
if (flags & FLAG_R &&
file.name != "./" && file.name != "../") {
directories.push_back(file);
}
}
else if (s.st_mode & S_IXUSR) {
file.name += '*';
file.color += GREEN;
}
else file.color += BLACK;
files.push_back(file);
}
else
perror("stat");
}
}
if (errno) {
perror("readdir");
return;
}
if (closedir(dir_ptr) == -1) {
perror("closedir");
return;
}
std::sort(files.begin(), files.end(), by_name);
std::sort(directories.begin(), directories.end(), by_name);
print_files(files, flags);
for (size_t i = 0; i < directories.size(); ++i)
print_directory(directories[i], flags, true);
}
void print_files(const std::vector<File>& files, int flags) {
if (flags & FLAG_l) {
print_files_long(files); return;
}
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
int max_width = w.ws_col;
unsigned n_rows = 1;
std::vector<unsigned> column_width(files.size()+1);
while (n_rows < files.size()) {
int column = -1;
for (size_t i = 0; i < files.size(); ++i) {
if (i % n_rows == 0) ++column;
if (column_width[column] < files[i].name.size()+2)
column_width[column] = files[i].name.size()+2;
}
int total_width = 0;
for (size_t i = 0; column_width[i] != 0; ++i)
total_width += column_width[i];
if (total_width <= max_width) break;
for (size_t i = 0; column_width[i] != 0; ++i)
column_width[i] = 0;
++n_rows;
}
for (size_t i = 0; i < n_rows; ++i) {
for (size_t j = i; j < files.size(); j += n_rows) {
size_t column = j / n_rows;
std::cout << files[j].color;
struct stat s;
if (stat(files[i].path.c_str(), &s) == 0) {
if (s.st_mode & (S_IFDIR | S_IXUSR)) {
std::cout << files[j].name.substr(0,
files[j].name.size()-1) << BLACK
<< files[j].name[files[j].name.size()-1];
}
else {
std::cout << files[j].name << BLACK;
}
std::cout << std::setw(column_width[column] -
files[j].name.size()) << " ";
}
}
std::cout << std::endl;
}
}
void print_files_long(const std::vector<File>& files) {
blkcnt_t total_blocks = 0;
const char* months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
std::vector<std::string> permissions;
std::vector<nlink_t> links;
std::vector<const char*> users;
std::vector<const char*> groups;
std::vector<off_t> sizes;
size_t link_max = 0;
size_t user_max = 0;
size_t group_max = 0;
size_t size_max = 0;
std::vector<std::string> dates;
for (size_t i = 0; i < files.size(); ++i) {
struct stat s;
if (stat(files[i].path.c_str(), &s) == 0) {
total_blocks += s.st_blocks;
std::stringstream ss;
std::string permission;
permission += (s.st_mode & S_IFDIR ? 'd' : '-');
permission += (s.st_mode & S_IRUSR ? 'r' : '-');
permission += (s.st_mode & S_IWUSR ? 'w' : '-');
permission += (s.st_mode & S_IXUSR ? 'x' : '-');
permission += (s.st_mode & S_IRGRP ? 'r' : '-');
permission += (s.st_mode & S_IWGRP ? 'w' : '-');
permission += (s.st_mode & S_IXGRP ? 'x' : '-');
permission += (s.st_mode & S_IROTH ? 'r' : '-');
permission += (s.st_mode & S_IWOTH ? 'w' : '-');
permission += (s.st_mode & S_IXOTH ? 'x' : '-');
permissions.push_back(permission);
ss << s.st_nlink; std::string slink = ss.str(); ss.str("");
if (link_max < slink.size()) link_max = slink.size();
links.push_back(s.st_nlink);
const char* user = getpwuid(s.st_uid)->pw_name;
if (user_max < strlen(user)) user_max = strlen(user);
users.push_back(user);
const char* group = getgrgid(s.st_gid)->gr_name;
if (group_max < strlen(group)) group_max = strlen(group);
groups.push_back(group);
ss << s.st_size; std::string ssize = ss.str(); ss.str("");
if (size_max < ssize.size()) size_max = ssize.size();
sizes.push_back(s.st_size);
time_t mtime = s.st_mtime;
tm *ltm = localtime(&mtime);
std::string date;
date += months[ltm->tm_mon]; date += ' ';
if (ltm->tm_mday < 10) date += ' ';
ss << ltm->tm_mday << ' '; date += ss.str(); ss.str("");
if (ltm->tm_hour < 10) date += '0';
ss << ltm->tm_hour << ':'; date += ss.str(); ss.str("");
if (ltm->tm_min < 10) date += '0';
ss << ltm->tm_min; date += ss.str(); ss.str("");
dates.push_back(date);
}
else {
perror("stat");
return;
}
}
std::cout << "total " << total_blocks << std::endl;
for (size_t i = 0; i < files.size(); ++i) {
std::cout << permissions[i] << ' '
<< std::setw(link_max) << links[i] << ' '
<< std::setw(user_max) << users[i] << ' '
<< std::setw(group_max) << groups[i] << ' '
<< std::setw(size_max) << sizes[i] << ' '
<< dates[i] << ' ';
std::cout << files[i].color << files[i].name << BLACK << std::endl;
}
}
bool by_name(const File& left, const File& right) {
std::string upper_left, upper_right;
for (size_t i = 0; i < left.name.size(); ++i) {
if (isalnum(left.name[i]))
upper_left += toupper(left.name[i]);
}
for (size_t i = 0; i < right.name.size(); ++i) {
if (isalnum(right.name[i]))
upper_right += toupper(right.name[i]);
}
if (upper_left == upper_right) return left.name > right.name;
else return upper_left < upper_right;
}
<|endoftext|> |
<commit_before>#ifndef AFFINE_INVARIANT_FEATURES_AFFINE_INVARIANT_FEATURE
#define AFFINE_INVARIANT_FEATURES_AFFINE_INVARIANT_FEATURE
#include <algorithm>
#include <vector>
#include <affine_invariant_features/affine_invariant_feature_base.hpp>
#include <affine_invariant_features/parallel_tasks.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/imgproc.hpp>
namespace affine_invariant_features {
//
// AffineInvariantFeature that samples features in various affine transformation space
//
class AffineInvariantFeature : public AffineInvariantFeatureBase {
private:
// the private constructor. users must use create() to instantiate an AffineInvariantFeature
AffineInvariantFeature(const cv::Ptr< cv::Feature2D > detector,
const cv::Ptr< cv::Feature2D > extractor)
: AffineInvariantFeatureBase(detector, extractor) {
// generate parameters for affine invariant sampling
phi_params_.push_back(0.);
tilt_params_.push_back(1.);
for (int i = 1; i < 6; ++i) {
const double tilt(std::pow(2., 0.5 * i));
for (double phi = 0.; phi < 180.; phi += 72. / tilt) {
phi_params_.push_back(phi);
tilt_params_.push_back(tilt);
}
}
ntasks_ = phi_params_.size();
}
public:
virtual ~AffineInvariantFeature() {}
//
// unique interfaces to instantiate an AffineInvariantFeature
//
static cv::Ptr< AffineInvariantFeature > create(const cv::Ptr< cv::Feature2D > feature) {
return new AffineInvariantFeature(feature, feature);
}
static cv::Ptr< AffineInvariantFeature > create(const cv::Ptr< cv::Feature2D > detector,
const cv::Ptr< cv::Feature2D > extractor) {
return new AffineInvariantFeature(detector, extractor);
}
//
// overloaded functions from AffineInvariantFeatureBase or its base class
//
virtual void compute(cv::InputArray image, std::vector< cv::KeyPoint > &keypoints,
cv::OutputArray descriptors) {
// extract the input
const cv::Mat image_mat(image.getMat());
// prepare outputs of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_, keypoints);
std::vector< cv::Mat > descriptors_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (int i = 0; i < ntasks_; ++i) {
tasks[i] = boost::bind(&AffineInvariantFeature::computeTask, this, boost::ref(image_mat),
boost::ref(keypoints_array[i]), boost::ref(descriptors_array[i]),
phi_params_[i], tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks);
// fill the final outputs
extendKeypoints(keypoints_array, keypoints);
extendDescriptors(descriptors_array, descriptors);
}
virtual void detect(cv::InputArray image, std::vector< cv::KeyPoint > &keypoints,
cv::InputArray mask = cv::noArray()) {
// extract inputs
const cv::Mat image_mat(image.getMat());
const cv::Mat mask_mat(mask.getMat());
// prepare an output of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (std::size_t i = 0; i < ntasks_; ++i) {
tasks[i] = boost::bind(&AffineInvariantFeature::detectTask, this, boost::ref(image_mat),
boost::ref(mask_mat), boost::ref(keypoints_array[i]), phi_params_[i],
tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks);
// fill the final output
extendKeypoints(keypoints_array, keypoints);
}
// detect and compute affine invariant keypoints and descriptors
virtual void detectAndCompute(cv::InputArray image, cv::InputArray mask,
std::vector< cv::KeyPoint > &keypoints, cv::OutputArray descriptors,
bool useProvidedKeypoints = false) {
// just compute descriptors if the keypoints is provided
if (useProvidedKeypoints) {
compute(image, keypoints, descriptors);
return;
}
// extract inputs
const cv::Mat image_mat(image.getMat());
const cv::Mat mask_mat(mask.getMat());
// prepare outputs of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_);
std::vector< cv::Mat > descriptors_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (std::size_t i = 0; i < ntasks_; ++i) {
tasks[i] =
boost::bind(&AffineInvariantFeature::detectAndComputeTask, this, boost::ref(image_mat),
boost::ref(mask_mat), boost::ref(keypoints_array[i]),
boost::ref(descriptors_array[i]), phi_params_[i], tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks);
// fill the final outputs
extendKeypoints(keypoints_array, keypoints);
extendDescriptors(descriptors_array, descriptors);
}
virtual cv::String getDefaultName() const { return "AffineInvariantFeature"; }
private:
void computeTask(const cv::Mat &src_image, std::vector< cv::KeyPoint > &keypoints,
cv::Mat &descriptors, const double phi, const double tilt) const {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// apply the affine transformation to keypoints
transformKeypoints(keypoints, affine);
// extract descriptors on the skewed image and keypoints
CV_Assert(extractor_);
extractor_->compute(image, keypoints, descriptors);
// invert keypoints
invertKeypoints(keypoints, affine);
}
void detectTask(const cv::Mat &src_image, const cv::Mat &src_mask,
std::vector< cv::KeyPoint > &keypoints, const double phi,
const double tilt) const {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// apply the affine transformation to the mask
cv::Mat mask(src_mask.empty() ? cv::Mat(src_image.size(), CV_8UC1, 255) : src_mask.clone());
warpMask(mask, affine, image.size());
// detect keypoints on the skewed image and mask
CV_Assert(detector_);
detector_->detect(image, keypoints, mask);
// invert keypoints
invertKeypoints(keypoints, affine);
}
void detectAndComputeTask(const cv::Mat &src_image, const cv::Mat &src_mask,
std::vector< cv::KeyPoint > &keypoints, cv::Mat &descriptors,
const double phi, const double tilt) {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// if keypoints are not provided, first apply the affine transformation to the mask
cv::Mat mask(src_mask.empty() ? cv::Mat(src_image.size(), CV_8UC1, 255) : src_mask.clone());
warpMask(mask, affine, image.size());
// detect keypoints on the skewed image and mask
// and extract descriptors on the image and keypoints
if (detector_ == extractor_) {
CV_Assert(detector_);
detector_->detectAndCompute(image, mask, keypoints, descriptors, false);
} else {
CV_Assert(detector_);
CV_Assert(extractor_);
detector_->detect(image, keypoints, mask);
extractor_->compute(image, keypoints, descriptors);
}
// invert the positions of the detected keypoints
invertKeypoints(keypoints, affine);
}
static void warpImage(cv::Mat &image, cv::Matx23f &affine, const double phi, const double tilt) {
// initiate output
affine = cv::Matx23f::eye();
if (phi != 0.) {
// rotate the source frame
affine = cv::getRotationMatrix2D(cv::Point2f(0., 0.), phi, 1.);
cv::Rect tmp_rect;
{
std::vector< cv::Point2f > corners(4);
corners[0] = cv::Point2f(0., 0.);
corners[1] = cv::Point2f(image.cols, 0.);
corners[2] = cv::Point2f(image.cols, image.rows);
corners[3] = cv::Point2f(0., image.rows);
std::vector< cv::Point2f > tmp_corners;
cv::transform(corners, tmp_corners, affine);
tmp_rect = cv::boundingRect(tmp_corners);
}
// cancel the offset of the rotated frame
affine(0, 2) = -tmp_rect.x;
affine(1, 2) = -tmp_rect.y;
// apply the final transformation to the image
cv::warpAffine(image, image, affine, tmp_rect.size(), cv::INTER_LINEAR, cv::BORDER_REPLICATE);
}
if (tilt != 1.) {
// shrink the image in width
cv::GaussianBlur(image, image, cv::Size(0, 0), 0.8 * std::sqrt(tilt * tilt - 1.), 0.01);
cv::resize(image, image, cv::Size(0, 0), 1. / tilt, 1., cv::INTER_NEAREST);
affine(0, 0) /= tilt;
affine(0, 1) /= tilt;
affine(0, 2) /= tilt;
}
}
static void warpMask(cv::Mat &mask, const cv::Matx23f &affine, const cv::Size size) {
if (affine == cv::Matx23f::eye()) {
return;
}
cv::warpAffine(mask, mask, affine, size, cv::INTER_NEAREST);
}
static void transformKeypoints(std::vector< cv::KeyPoint > &keypoints,
const cv::Matx23f &affine) {
if (affine == cv::Matx23f::eye()) {
return;
}
for (std::vector< cv::KeyPoint >::iterator keypoint = keypoints.begin();
keypoint != keypoints.end(); ++keypoint) {
// convert cv::Point2f to cv::Mat (1x1,2ch) without copying data.
// this is required because cv::transform does not accept cv::Point2f.
cv::Mat pt(cv::Mat(keypoint->pt, false).reshape(2));
cv::transform(pt, pt, affine);
}
}
static void invertKeypoints(std::vector< cv::KeyPoint > &keypoints, const cv::Matx23f &affine) {
if (affine == cv::Matx23f::eye()) {
return;
}
cv::Matx23f invert_affine;
cv::invertAffineTransform(affine, invert_affine);
transformKeypoints(keypoints, invert_affine);
}
static void extendKeypoints(const std::vector< std::vector< cv::KeyPoint > > &src,
std::vector< cv::KeyPoint > &dst) {
dst.clear();
for (std::size_t i = 0; i < src.size(); ++i) {
dst.insert(dst.end(), src[i].begin(), src[i].end());
}
}
void extendDescriptors(const std::vector< cv::Mat > &src, cv::OutputArray dst) const {
// create the output array
int nrows(0);
for (std::size_t i = 0; i < src.size(); ++i) {
nrows += src[i].rows;
}
dst.create(nrows, descriptorSize(), descriptorType());
// fill the output array
cv::Mat dst_mat(dst.getMat());
int rows(0);
for (std::size_t i = 0; i < src.size(); ++i) {
src[i].copyTo(dst_mat.rowRange(rows, rows + src[i].rows));
rows += src[i].rows;
}
}
private:
std::vector< double > phi_params_;
std::vector< double > tilt_params_;
std::size_t ntasks_;
};
}
#endif<commit_msg>private -> protected<commit_after>#ifndef AFFINE_INVARIANT_FEATURES_AFFINE_INVARIANT_FEATURE
#define AFFINE_INVARIANT_FEATURES_AFFINE_INVARIANT_FEATURE
#include <algorithm>
#include <vector>
#include <affine_invariant_features/affine_invariant_feature_base.hpp>
#include <affine_invariant_features/parallel_tasks.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/imgproc.hpp>
namespace affine_invariant_features {
//
// AffineInvariantFeature that samples features in various affine transformation space
//
class AffineInvariantFeature : public AffineInvariantFeatureBase {
protected:
// the private constructor. users must use create() to instantiate an AffineInvariantFeature
AffineInvariantFeature(const cv::Ptr< cv::Feature2D > detector,
const cv::Ptr< cv::Feature2D > extractor)
: AffineInvariantFeatureBase(detector, extractor) {
// generate parameters for affine invariant sampling
phi_params_.push_back(0.);
tilt_params_.push_back(1.);
for (int i = 1; i < 6; ++i) {
const double tilt(std::pow(2., 0.5 * i));
for (double phi = 0.; phi < 180.; phi += 72. / tilt) {
phi_params_.push_back(phi);
tilt_params_.push_back(tilt);
}
}
ntasks_ = phi_params_.size();
}
public:
virtual ~AffineInvariantFeature() {}
//
// unique interfaces to instantiate an AffineInvariantFeature
//
static cv::Ptr< AffineInvariantFeature > create(const cv::Ptr< cv::Feature2D > feature) {
return new AffineInvariantFeature(feature, feature);
}
static cv::Ptr< AffineInvariantFeature > create(const cv::Ptr< cv::Feature2D > detector,
const cv::Ptr< cv::Feature2D > extractor) {
return new AffineInvariantFeature(detector, extractor);
}
//
// overloaded functions from AffineInvariantFeatureBase or its base class
//
virtual void compute(cv::InputArray image, std::vector< cv::KeyPoint > &keypoints,
cv::OutputArray descriptors) {
// extract the input
const cv::Mat image_mat(image.getMat());
// prepare outputs of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_, keypoints);
std::vector< cv::Mat > descriptors_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (std::size_t i = 0; i < ntasks_; ++i) {
tasks[i] = boost::bind(&AffineInvariantFeature::computeTask, this, boost::ref(image_mat),
boost::ref(keypoints_array[i]), boost::ref(descriptors_array[i]),
phi_params_[i], tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks);
// fill the final outputs
extendKeypoints(keypoints_array, keypoints);
extendDescriptors(descriptors_array, descriptors);
}
virtual void detect(cv::InputArray image, std::vector< cv::KeyPoint > &keypoints,
cv::InputArray mask = cv::noArray()) {
// extract inputs
const cv::Mat image_mat(image.getMat());
const cv::Mat mask_mat(mask.getMat());
// prepare an output of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (std::size_t i = 0; i < ntasks_; ++i) {
tasks[i] = boost::bind(&AffineInvariantFeature::detectTask, this, boost::ref(image_mat),
boost::ref(mask_mat), boost::ref(keypoints_array[i]), phi_params_[i],
tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks);
// fill the final output
extendKeypoints(keypoints_array, keypoints);
}
virtual void detectAndCompute(cv::InputArray image, cv::InputArray mask,
std::vector< cv::KeyPoint > &keypoints, cv::OutputArray descriptors,
bool useProvidedKeypoints = false) {
// just compute descriptors if the keypoints is provided
if (useProvidedKeypoints) {
compute(image, keypoints, descriptors);
return;
}
// extract inputs
const cv::Mat image_mat(image.getMat());
const cv::Mat mask_mat(mask.getMat());
// prepare outputs of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_);
std::vector< cv::Mat > descriptors_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (std::size_t i = 0; i < ntasks_; ++i) {
tasks[i] =
boost::bind(&AffineInvariantFeature::detectAndComputeTask, this, boost::ref(image_mat),
boost::ref(mask_mat), boost::ref(keypoints_array[i]),
boost::ref(descriptors_array[i]), phi_params_[i], tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks);
// fill the final outputs
extendKeypoints(keypoints_array, keypoints);
extendDescriptors(descriptors_array, descriptors);
}
virtual cv::String getDefaultName() const { return "AffineInvariantFeature"; }
protected:
void computeTask(const cv::Mat &src_image, std::vector< cv::KeyPoint > &keypoints,
cv::Mat &descriptors, const double phi, const double tilt) const {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// apply the affine transformation to keypoints
transformKeypoints(keypoints, affine);
// extract descriptors on the skewed image and keypoints
CV_Assert(extractor_);
extractor_->compute(image, keypoints, descriptors);
// invert keypoints
invertKeypoints(keypoints, affine);
}
void detectTask(const cv::Mat &src_image, const cv::Mat &src_mask,
std::vector< cv::KeyPoint > &keypoints, const double phi,
const double tilt) const {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// apply the affine transformation to the mask
cv::Mat mask(src_mask.empty() ? cv::Mat(src_image.size(), CV_8UC1, 255) : src_mask.clone());
warpMask(mask, affine, image.size());
// detect keypoints on the skewed image and mask
CV_Assert(detector_);
detector_->detect(image, keypoints, mask);
// invert keypoints
invertKeypoints(keypoints, affine);
}
void detectAndComputeTask(const cv::Mat &src_image, const cv::Mat &src_mask,
std::vector< cv::KeyPoint > &keypoints, cv::Mat &descriptors,
const double phi, const double tilt) const {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// if keypoints are not provided, first apply the affine transformation to the mask
cv::Mat mask(src_mask.empty() ? cv::Mat(src_image.size(), CV_8UC1, 255) : src_mask.clone());
warpMask(mask, affine, image.size());
// detect keypoints on the skewed image and mask
// and extract descriptors on the image and keypoints
if (detector_ == extractor_) {
CV_Assert(detector_);
detector_->detectAndCompute(image, mask, keypoints, descriptors, false);
} else {
CV_Assert(detector_);
CV_Assert(extractor_);
detector_->detect(image, keypoints, mask);
extractor_->compute(image, keypoints, descriptors);
}
// invert the positions of the detected keypoints
invertKeypoints(keypoints, affine);
}
static void warpImage(cv::Mat &image, cv::Matx23f &affine, const double phi, const double tilt) {
// initiate output
affine = cv::Matx23f::eye();
if (phi != 0.) {
// rotate the source frame
affine = cv::getRotationMatrix2D(cv::Point2f(0., 0.), phi, 1.);
cv::Rect tmp_rect;
{
std::vector< cv::Point2f > corners(4);
corners[0] = cv::Point2f(0., 0.);
corners[1] = cv::Point2f(image.cols, 0.);
corners[2] = cv::Point2f(image.cols, image.rows);
corners[3] = cv::Point2f(0., image.rows);
std::vector< cv::Point2f > tmp_corners;
cv::transform(corners, tmp_corners, affine);
tmp_rect = cv::boundingRect(tmp_corners);
}
// cancel the offset of the rotated frame
affine(0, 2) = -tmp_rect.x;
affine(1, 2) = -tmp_rect.y;
// apply the final transformation to the image
cv::warpAffine(image, image, affine, tmp_rect.size(), cv::INTER_LINEAR, cv::BORDER_REPLICATE);
}
if (tilt != 1.) {
// shrink the image in width
cv::GaussianBlur(image, image, cv::Size(0, 0), 0.8 * std::sqrt(tilt * tilt - 1.), 0.01);
cv::resize(image, image, cv::Size(0, 0), 1. / tilt, 1., cv::INTER_NEAREST);
affine(0, 0) /= tilt;
affine(0, 1) /= tilt;
affine(0, 2) /= tilt;
}
}
static void warpMask(cv::Mat &mask, const cv::Matx23f &affine, const cv::Size size) {
if (affine == cv::Matx23f::eye()) {
return;
}
cv::warpAffine(mask, mask, affine, size, cv::INTER_NEAREST);
}
static void transformKeypoints(std::vector< cv::KeyPoint > &keypoints,
const cv::Matx23f &affine) {
if (affine == cv::Matx23f::eye()) {
return;
}
for (std::vector< cv::KeyPoint >::iterator keypoint = keypoints.begin();
keypoint != keypoints.end(); ++keypoint) {
// convert cv::Point2f to cv::Mat (1x1,2ch) without copying data.
// this is required because cv::transform does not accept cv::Point2f.
cv::Mat pt(cv::Mat(keypoint->pt, false).reshape(2));
cv::transform(pt, pt, affine);
}
}
static void invertKeypoints(std::vector< cv::KeyPoint > &keypoints, const cv::Matx23f &affine) {
if (affine == cv::Matx23f::eye()) {
return;
}
cv::Matx23f invert_affine;
cv::invertAffineTransform(affine, invert_affine);
transformKeypoints(keypoints, invert_affine);
}
static void extendKeypoints(const std::vector< std::vector< cv::KeyPoint > > &src,
std::vector< cv::KeyPoint > &dst) {
dst.clear();
for (std::size_t i = 0; i < src.size(); ++i) {
dst.insert(dst.end(), src[i].begin(), src[i].end());
}
}
void extendDescriptors(const std::vector< cv::Mat > &src, cv::OutputArray dst) const {
// create the output array
int nrows(0);
for (std::size_t i = 0; i < src.size(); ++i) {
nrows += src[i].rows;
}
dst.create(nrows, descriptorSize(), descriptorType());
// fill the output array
cv::Mat dst_mat(dst.getMat());
int rows(0);
for (std::size_t i = 0; i < src.size(); ++i) {
src[i].copyTo(dst_mat.rowRange(rows, rows + src[i].rows));
rows += src[i].rows;
}
}
protected:
std::vector< double > phi_params_;
std::vector< double > tilt_params_;
std::size_t ntasks_;
};
}
#endif<|endoftext|> |
<commit_before>#pragma once
#include "integrators/symplectic_runge_kutta_nystrom_integrator.hpp"
#include <algorithm>
#include <cmath>
#include <ctime>
#include <vector>
#include "glog/logging.h"
#include "quantities/quantities.hpp"
#ifdef ADVANCE_ΔQSTAGE
#error ADVANCE_ΔQSTAGE already defined
#else
#define ADVANCE_ΔQSTAGE(step) \
do { \
Time const step_evaluated = (step); \
for (int k = 0; k < dimension; ++k) { \
Position const Δq = (*Δqstage_previous)[k] + \
step_evaluated * p_stage[k]; \
q_stage[k] = q_last[k].value + Δq; \
(*Δqstage_current)[k] = Δq; \
} \
} while (false)
#endif
#ifdef ADVANCE_ΔVSTAGE
#error ADVANCE_ΔVSTAGE already defined
#else
#define ADVANCE_ΔVSTAGE(step, q_clock) \
do { \
Time const step_evaluated = (step); \
compute_acceleration((q_clock), q_stage, &f); \
for (int k = 0; k < dimension; ++k) { \
Velocity const Δp = (*Δpstage_previous)[k] + step_evaluated * f[k]; \
p_stage[k] = p_last[k].value + Δp; \
(*Δpstage_current)[k] = Δp; \
} \
} while (false)
#endif
namespace principia {
namespace integrators {
SRKNIntegrator::SRKNIntegrator(std::vector<double> const& a,
std::vector<double> const& b)
: a_(std::move(a)),
b_(std::move(b)) {
if (b.front() == 0.0) {
vanishing_coefficients_ = kFirstBVanishes;
first_same_as_last_ = std::make_unique<FirstSameAsLast>();
first_same_as_last_->first = a.front();
first_same_as_last_->last = a.back();
a_ = std::vector<double>(a.begin() + 1, a.end());
b_ = std::vector<double>(b.begin() + 1, b.end());
a_.back() += first_same_as_last_->first;
stages_ = b_.size();
CHECK_EQ(stages_, a_.size());
} else if (a.back() == 0.0) {
vanishing_coefficients_ = kLastAVanishes;
first_same_as_last_ = std::make_unique<FirstSameAsLast>();
first_same_as_last_->first = b.front();
first_same_as_last_->last = b.back();
a_ = std::vector<double>(a.begin(), a.end() - 1);
b_ = std::vector<double>(b.begin(), b.end() - 1);
b_.front() += first_same_as_last_->last;
stages_ = b_.size();
CHECK_EQ(stages_, a_.size());
} else {
vanishing_coefficients_ = kNone;
first_same_as_last_.reset();
a_ = a;
b_ = b;
stages_ = b_.size();
CHECK_EQ(stages_, a_.size());
}
// Runge-Kutta time weights.
c_.resize(stages_);
if (vanishing_coefficients_ == kFirstBVanishes) {
c_[0] = first_same_as_last_->first;
} else {
c_[0] = 0.0;
}
for (int j = 1; j < stages_; ++j) {
c_[j] = c_[j - 1] + a_[j - 1];
}
}
template<typename Position, typename Velocity,
typename RightHandSideComputation>
void SRKNIntegrator::SolveTrivialKineticEnergyIncrement(
RightHandSideComputation compute_acceleration,
Parameters<Position, Velocity> const& parameters,
not_null<Solution<Position, Velocity>*> const solution) const {
switch (vanishing_coefficients_) {
case kNone:
SolveTrivialKineticEnergyIncrementOptimized<kNone>(compute_acceleration,
parameters,
solution);
break;
case kFirstBVanishes:
SolveTrivialKineticEnergyIncrementOptimized<kFirstBVanishes>(
compute_acceleration,
parameters,
solution);
break;
case kLastAVanishes:
SolveTrivialKineticEnergyIncrementOptimized<kLastAVanishes>(
compute_acceleration,
parameters,
solution);
break;
default:
LOG(FATAL) << "Invalid vanishing coefficients";
}
}
template<SRKNIntegrator::VanishingCoefficients vanishing_coefficients,
typename Position, typename Velocity,
typename RightHandSideComputation>
void SRKNIntegrator::SolveTrivialKineticEnergyIncrementOptimized(
RightHandSideComputation compute_acceleration,
SRKNIntegrator::Parameters<Position, Velocity> const& parameters,
not_null<Solution<Position, Velocity>*> const solution) const {
int const dimension = parameters.initial.positions.size();
std::vector<Position> Δqstage0(dimension);
std::vector<Position> Δqstage1(dimension);
std::vector<Velocity> Δpstage0(dimension);
std::vector<Velocity> Δpstage1(dimension);
std::vector<Position>* Δqstage_current = &Δqstage1;
std::vector<Position>* Δqstage_previous = &Δqstage0;
std::vector<Velocity>* Δpstage_current = &Δpstage1;
std::vector<Velocity>* Δpstage_previous = &Δpstage0;
// Dimension the result.
int const capacity = parameters.sampling_period == 0 ?
1 :
static_cast<int>(
ceil((((parameters.tmax - parameters.initial.time.value) /
parameters.Δt) + 1) /
parameters.sampling_period)) + 1;
solution->clear();
solution->reserve(capacity);
std::vector<DoublePrecision<Position>> q_last(parameters.initial.positions);
std::vector<DoublePrecision<Velocity>> p_last(parameters.initial.momenta);
int sampling_phase = 0;
std::vector<Position> q_stage(dimension);
std::vector<Velocity> p_stage(dimension);
std::vector<Quotient<Velocity, Time>> f(dimension); // Current forces.
std::vector<Quotient<Position, Time>> v(dimension); // Current velocities.
// The following quantity is generally equal to |Δt|, but during the last
// iteration, if |tmax_is_exact|, it may differ significantly from |Δt|.
Time h = parameters.Δt; // Constant for now.
// During one iteration of the outer loop below we process the time interval
// [|tn|, |tn| + |h|[. |tn| is computed using compensated summation to make
// sure that we don't have drifts.
DoublePrecision<Time> tn = parameters.initial.time;
// Whether position and momentum are synchronized between steps, relevant for
// first-same-as-last (FSAL) integrators. Time is always synchronous with
// position.
bool q_and_p_are_synchronized = true;
bool should_synchronize = false;
// Integration. For details see Wolfram Reference,
// http://reference.wolfram.com/mathematica/tutorial/NDSolveSPRK.html#74387056
bool at_end = !parameters.tmax_is_exact && parameters.tmax < tn.value + h;
while (!at_end) {
// Check if this is the last interval and if so process it appropriately.
if (parameters.tmax_is_exact) {
// If |tn| is getting close to |tmax|, use |tmax| as the upper bound of
// the interval and update |h| accordingly. The bound chosen here for
// |tmax| ensures that we don't end up with a ridiculously small last
// interval: we'd rather make the last interval a bit bigger. More
// precisely, the last interval generally has a length between 0.5 Δt and
// 1.5 Δt, unless it is also the first interval.
// NOTE(phl): This may lead to convergence as bad as (1.5 Δt)^5 rather
// than Δt^5.
if (parameters.tmax <= tn.value + 3 * h / 2) {
at_end = true;
h = (parameters.tmax - tn.value) - tn.error;
}
} else if (parameters.tmax < tn.value + 2 * h) {
// If the next interval would overshoot, make this the last interval but
// stick to the same step.
at_end = true;
}
// Here |h| is the length of the current time interval and |tn| is its
// start.
// Increment SPRK step from "'SymplecticPartitionedRungeKutta' Method
// for NDSolve", algorithm 3.
for (int k = 0; k < dimension; ++k) {
(*Δqstage_current)[k] = Position();
(*Δpstage_current)[k] = Velocity();
q_stage[k] = q_last[k].value;
}
if (vanishing_coefficients != kNone) {
should_synchronize = at_end ||
(parameters.sampling_period != 0 &&
sampling_phase % parameters.sampling_period == 0);
}
if (vanishing_coefficients == kFirstBVanishes &&
q_and_p_are_synchronized) {
// Desynchronize.
std::swap(Δqstage_current, Δqstage_previous);
for (int k = 0; k < dimension; ++k) {
p_stage[k] = p_last[k].value;
}
ADVANCE_ΔQSTAGE(first_same_as_last_->first * h);
q_and_p_are_synchronized = false;
}
for (int i = 0; i < stages_; ++i) {
std::swap(Δqstage_current, Δqstage_previous);
std::swap(Δpstage_current, Δpstage_previous);
// Beware, the p/q order matters here, the two computations depend on one
// another.
// By using |tn.error| below we get a time value which is possibly a wee
// bit more precise.
if (vanishing_coefficients == kLastAVanishes &&
q_and_p_are_synchronized && i == 0) {
ADVANCE_ΔVSTAGE(first_same_as_last_->first * h,
tn.value);
q_and_p_are_synchronized = false;
} else {
ADVANCE_ΔVSTAGE(b_[i] * h, tn.value + (tn.error + c_[i] * h));
}
if (vanishing_coefficients == kFirstBVanishes &&
should_synchronize && i == stages_ - 1) {
ADVANCE_ΔQSTAGE(first_same_as_last_->last * h);
q_and_p_are_synchronized = true;
} else {
ADVANCE_ΔQSTAGE(a_[i] * h);
}
}
if (vanishing_coefficients == kLastAVanishes && should_synchronize) {
std::swap(Δpstage_current, Δpstage_previous);
// TODO(egg): the second parameter below is really just tn.value + h.
ADVANCE_ΔVSTAGE(first_same_as_last_->last * h,
tn.value + h);
q_and_p_are_synchronized = true;
}
// Compensated summation from "'SymplecticPartitionedRungeKutta' Method
// for NDSolve", algorithm 2.
for (int k = 0; k < dimension; ++k) {
q_last[k].Increment((*Δqstage_current)[k]);
p_last[k].Increment((*Δpstage_current)[k]);
q_stage[k] = q_last[k].value;
p_stage[k] = p_last[k].value;
}
tn.Increment(h);
if (parameters.sampling_period != 0) {
if (sampling_phase % parameters.sampling_period == 0) {
solution->emplace_back();
SystemState<Position, Velocity>* state = &solution->back();
state->time = tn;
state->positions.reserve(dimension);
state->momenta.reserve(dimension);
for (int k = 0; k < dimension; ++k) {
state->positions.emplace_back(q_last[k]);
state->momenta.emplace_back(p_last[k]);
}
}
++sampling_phase;
}
}
if (parameters.sampling_period == 0) {
solution->emplace_back();
SystemState<Position, Velocity>* state = &solution->back();
state->time = tn;
state->positions.reserve(dimension);
state->momenta.reserve(dimension);
for (int k = 0; k < dimension; ++k) {
state->positions.emplace_back(q_last[k]);
state->momenta.emplace_back(p_last[k]);
}
}
}
} // namespace integrators
} // namespace principia
#undef ADVANCE_ΔQSTAGE
#undef ADVANCE_ΔVSTAGE
<commit_msg>wording<commit_after>#pragma once
#include "integrators/symplectic_runge_kutta_nystrom_integrator.hpp"
#include <algorithm>
#include <cmath>
#include <ctime>
#include <vector>
#include "glog/logging.h"
#include "quantities/quantities.hpp"
#ifdef ADVANCE_ΔQSTAGE
#error ADVANCE_ΔQSTAGE already defined
#else
#define ADVANCE_ΔQSTAGE(step) \
do { \
Time const step_evaluated = (step); \
for (int k = 0; k < dimension; ++k) { \
Position const Δq = (*Δqstage_previous)[k] + \
step_evaluated * v_stage[k]; \
q_stage[k] = q_last[k].value + Δq; \
(*Δqstage_current)[k] = Δq; \
} \
} while (false)
#endif
#ifdef ADVANCE_ΔVSTAGE
#error ADVANCE_ΔVSTAGE already defined
#else
#define ADVANCE_ΔVSTAGE(step, q_clock) \
do { \
Time const step_evaluated = (step); \
compute_acceleration((q_clock), q_stage, &a); \
for (int k = 0; k < dimension; ++k) { \
Velocity const Δv = (*Δvstage_previous)[k] + step_evaluated * a[k]; \
v_stage[k] = v_last[k].value + Δv; \
(*Δvstage_current)[k] = Δv; \
} \
} while (false)
#endif
namespace principia {
namespace integrators {
SRKNIntegrator::SRKNIntegrator(std::vector<double> const& a,
std::vector<double> const& b)
: a_(std::move(a)),
b_(std::move(b)) {
if (b.front() == 0.0) {
vanishing_coefficients_ = kFirstBVanishes;
first_same_as_last_ = std::make_unique<FirstSameAsLast>();
first_same_as_last_->first = a.front();
first_same_as_last_->last = a.back();
a_ = std::vector<double>(a.begin() + 1, a.end());
b_ = std::vector<double>(b.begin() + 1, b.end());
a_.back() += first_same_as_last_->first;
stages_ = b_.size();
CHECK_EQ(stages_, a_.size());
} else if (a.back() == 0.0) {
vanishing_coefficients_ = kLastAVanishes;
first_same_as_last_ = std::make_unique<FirstSameAsLast>();
first_same_as_last_->first = b.front();
first_same_as_last_->last = b.back();
a_ = std::vector<double>(a.begin(), a.end() - 1);
b_ = std::vector<double>(b.begin(), b.end() - 1);
b_.front() += first_same_as_last_->last;
stages_ = b_.size();
CHECK_EQ(stages_, a_.size());
} else {
vanishing_coefficients_ = kNone;
first_same_as_last_.reset();
a_ = a;
b_ = b;
stages_ = b_.size();
CHECK_EQ(stages_, a_.size());
}
// Runge-Kutta time weights.
c_.resize(stages_);
if (vanishing_coefficients_ == kFirstBVanishes) {
c_[0] = first_same_as_last_->first;
} else {
c_[0] = 0.0;
}
for (int j = 1; j < stages_; ++j) {
c_[j] = c_[j - 1] + a_[j - 1];
}
}
template<typename Position, typename Velocity,
typename RightHandSideComputation>
void SRKNIntegrator::SolveTrivialKineticEnergyIncrement(
RightHandSideComputation compute_acceleration,
Parameters<Position, Velocity> const& parameters,
not_null<Solution<Position, Velocity>*> const solution) const {
switch (vanishing_coefficients_) {
case kNone:
SolveTrivialKineticEnergyIncrementOptimized<kNone>(compute_acceleration,
parameters,
solution);
break;
case kFirstBVanishes:
SolveTrivialKineticEnergyIncrementOptimized<kFirstBVanishes>(
compute_acceleration,
parameters,
solution);
break;
case kLastAVanishes:
SolveTrivialKineticEnergyIncrementOptimized<kLastAVanishes>(
compute_acceleration,
parameters,
solution);
break;
default:
LOG(FATAL) << "Invalid vanishing coefficients";
}
}
template<SRKNIntegrator::VanishingCoefficients vanishing_coefficients,
typename Position, typename Velocity,
typename RightHandSideComputation>
void SRKNIntegrator::SolveTrivialKineticEnergyIncrementOptimized(
RightHandSideComputation compute_acceleration,
SRKNIntegrator::Parameters<Position, Velocity> const& parameters,
not_null<Solution<Position, Velocity>*> const solution) const {
int const dimension = parameters.initial.positions.size();
std::vector<Position> Δqstage0(dimension);
std::vector<Position> Δqstage1(dimension);
std::vector<Velocity> Δpstage0(dimension);
std::vector<Velocity> Δpstage1(dimension);
std::vector<Position>* Δqstage_current = &Δqstage1;
std::vector<Position>* Δqstage_previous = &Δqstage0;
std::vector<Velocity>* Δvstage_current = &Δpstage1;
std::vector<Velocity>* Δvstage_previous = &Δpstage0;
// Dimension the result.
int const capacity = parameters.sampling_period == 0 ?
1 :
static_cast<int>(
ceil((((parameters.tmax - parameters.initial.time.value) /
parameters.Δt) + 1) /
parameters.sampling_period)) + 1;
solution->clear();
solution->reserve(capacity);
std::vector<DoublePrecision<Position>> q_last(parameters.initial.positions);
std::vector<DoublePrecision<Velocity>> v_last(parameters.initial.momenta);
int sampling_phase = 0;
std::vector<Position> q_stage(dimension);
std::vector<Velocity> v_stage(dimension);
std::vector<Quotient<Velocity, Time>> a(dimension); // Current forces.
std::vector<Quotient<Position, Time>> v(dimension); // Current velocities.
// The following quantity is generally equal to |Δt|, but during the last
// iteration, if |tmax_is_exact|, it may differ significantly from |Δt|.
Time h = parameters.Δt; // Constant for now.
// During one iteration of the outer loop below we process the time interval
// [|tn|, |tn| + |h|[. |tn| is computed using compensated summation to make
// sure that we don't have drifts.
DoublePrecision<Time> tn = parameters.initial.time;
// Whether position and velocity are synchronized between steps, relevant for
// first-same-as-last (FSAL) integrators. Time is always synchronous with
// position.
bool q_and_v_are_synchronized = true;
bool should_synchronize = false;
// Integration. For details see Wolfram Reference,
// http://reference.wolfram.com/mathematica/tutorial/NDSolveSPRK.html#74387056
bool at_end = !parameters.tmax_is_exact && parameters.tmax < tn.value + h;
while (!at_end) {
// Check if this is the last interval and if so process it appropriately.
if (parameters.tmax_is_exact) {
// If |tn| is getting close to |tmax|, use |tmax| as the upper bound of
// the interval and update |h| accordingly. The bound chosen here for
// |tmax| ensures that we don't end up with a ridiculously small last
// interval: we'd rather make the last interval a bit bigger. More
// precisely, the last interval generally has a length between 0.5 Δt and
// 1.5 Δt, unless it is also the first interval.
// NOTE(phl): This may lead to convergence as bad as (1.5 Δt)^5 rather
// than Δt^5.
if (parameters.tmax <= tn.value + 3 * h / 2) {
at_end = true;
h = (parameters.tmax - tn.value) - tn.error;
}
} else if (parameters.tmax < tn.value + 2 * h) {
// If the next interval would overshoot, make this the last interval but
// stick to the same step.
at_end = true;
}
// Here |h| is the length of the current time interval and |tn| is its
// start.
// Increment SPRK step from "'SymplecticPartitionedRungeKutta' Method
// for NDSolve", algorithm 3.
for (int k = 0; k < dimension; ++k) {
(*Δqstage_current)[k] = Position();
(*Δvstage_current)[k] = Velocity();
q_stage[k] = q_last[k].value;
}
if (vanishing_coefficients != kNone) {
should_synchronize = at_end ||
(parameters.sampling_period != 0 &&
sampling_phase % parameters.sampling_period == 0);
}
if (vanishing_coefficients == kFirstBVanishes &&
q_and_v_are_synchronized) {
// Desynchronize.
std::swap(Δqstage_current, Δqstage_previous);
for (int k = 0; k < dimension; ++k) {
v_stage[k] = v_last[k].value;
}
ADVANCE_ΔQSTAGE(first_same_as_last_->first * h);
q_and_v_are_synchronized = false;
}
for (int i = 0; i < stages_; ++i) {
std::swap(Δqstage_current, Δqstage_previous);
std::swap(Δvstage_current, Δvstage_previous);
// Beware, the p/q order matters here, the two computations depend on one
// another.
// By using |tn.error| below we get a time value which is possibly a wee
// bit more precise.
if (vanishing_coefficients == kLastAVanishes &&
q_and_v_are_synchronized && i == 0) {
ADVANCE_ΔVSTAGE(first_same_as_last_->first * h,
tn.value);
q_and_v_are_synchronized = false;
} else {
ADVANCE_ΔVSTAGE(b_[i] * h, tn.value + (tn.error + c_[i] * h));
}
if (vanishing_coefficients == kFirstBVanishes &&
should_synchronize && i == stages_ - 1) {
ADVANCE_ΔQSTAGE(first_same_as_last_->last * h);
q_and_v_are_synchronized = true;
} else {
ADVANCE_ΔQSTAGE(a_[i] * h);
}
}
if (vanishing_coefficients == kLastAVanishes && should_synchronize) {
std::swap(Δvstage_current, Δvstage_previous);
// TODO(egg): the second parameter below is really just tn.value + h.
ADVANCE_ΔVSTAGE(first_same_as_last_->last * h,
tn.value + h);
q_and_v_are_synchronized = true;
}
// Compensated summation from "'SymplecticPartitionedRungeKutta' Method
// for NDSolve", algorithm 2.
for (int k = 0; k < dimension; ++k) {
q_last[k].Increment((*Δqstage_current)[k]);
v_last[k].Increment((*Δvstage_current)[k]);
q_stage[k] = q_last[k].value;
v_stage[k] = v_last[k].value;
}
tn.Increment(h);
if (parameters.sampling_period != 0) {
if (sampling_phase % parameters.sampling_period == 0) {
solution->emplace_back();
SystemState<Position, Velocity>* state = &solution->back();
state->time = tn;
state->positions.reserve(dimension);
state->momenta.reserve(dimension);
for (int k = 0; k < dimension; ++k) {
state->positions.emplace_back(q_last[k]);
state->momenta.emplace_back(v_last[k]);
}
}
++sampling_phase;
}
}
if (parameters.sampling_period == 0) {
solution->emplace_back();
SystemState<Position, Velocity>* state = &solution->back();
state->time = tn;
state->positions.reserve(dimension);
state->momenta.reserve(dimension);
for (int k = 0; k < dimension; ++k) {
state->positions.emplace_back(q_last[k]);
state->momenta.emplace_back(v_last[k]);
}
}
}
} // namespace integrators
} // namespace principia
#undef ADVANCE_ΔQSTAGE
#undef ADVANCE_ΔVSTAGE
<|endoftext|> |
<commit_before>#include "generated_flexnlp_test.o.h"
#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "configure.h"
int main(int, char **)
{
std::vector<double> duration_vector;
double start, end;
const int hsize = HIDDEN_SIZE;
const int isize = INPUT_SIZE;
const int osize = hsize;
const int nbatch = BATCH_SIZE;
const int nlayers = NUM_LAYERS;
const int ntimestep = SEQ_LENGTH;
// test LSTM Layer,
int8_t* x_in = (int8_t*) malloc(ntimestep*nbatch*isize*sizeof(int8_t));
int8_t* w_in = (int8_t*) malloc(nlayers*4*osize*(isize+hsize)*sizeof(int8_t));
int8_t* output = (int8_t*) malloc(ntimestep*nbatch*hsize*sizeof(int8_t));
int8_t* h_out = (int8_t*) malloc(nlayers*nbatch*hsize*sizeof(int8_t));
for(int i=0; i<ntimestep*nbatch*isize; i++)
if (i%3 == 0)
x_in[i] = (int8_t) 2;
else if (i%3 == 1)
x_in[i] = (int8_t) -3;
else
x_in[i] = (int8_t) 100;
for(int i=0; i<nlayers*4*osize*(isize+hsize); i++)
if (i%3 == 0)
w_in[i] = (int8_t) 2;
else if (i%3 == 1)
w_in[i] = (int8_t) -3;
else
w_in[i] = (int8_t) 100;
for(int i=0; i<nlayers*nbatch*hsize; i++)
h_out[i] = (int8_t) 3;
for(int i=0; i<ntimestep*nbatch*hsize; i++)
output[i] = (int8_t) 0;
Halide::Buffer<int8_t> b_input(x_in, ntimestep, nbatch, isize);
Halide::Buffer<int8_t> b_W(w_in, NUM_LAYERS, 4, osize, isize + hsize);
Halide::Buffer<int8_t> b_output(output, ntimestep, nbatch, hsize);
Halide::Buffer<int8_t> b_h_out(h_out, nlayers, nbatch, hsize);
std::cout << "Buffers Initialized" << std::endl;
for (int i = 0; i < NB_TESTS; i++)
{
for(int i=0; i<nlayers*nbatch*hsize; i++)
h_out[i] = (int8_t) 3;
for(int i=0; i<ntimestep*nbatch*hsize; i++)
output[i] = (int8_t) 0;
start = rtclock();
flexnlp_lstm(
b_input.raw_buffer(),
b_W.raw_buffer(),
b_output.raw_buffer(),
b_h_out.raw_buffer()
);
end = rtclock();
duration_vector.push_back((end - start) * 1000);
}
print_time("performance_CPU.csv", "FlexLSTM",
{"Tiramisu"},
{median(duration_vector)});
for(int i = 0; i<100; i++){
std::cout << " , " << (int) output[i];
}
std::cout << "Finished" << std::endl;
return 0;
}
<commit_msg>Comment final result display<commit_after>#include "generated_flexnlp_test.o.h"
#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "configure.h"
int main(int, char **)
{
std::vector<double> duration_vector;
double start, end;
const int hsize = HIDDEN_SIZE;
const int isize = INPUT_SIZE;
const int osize = hsize;
const int nbatch = BATCH_SIZE;
const int nlayers = NUM_LAYERS;
const int ntimestep = SEQ_LENGTH;
// test LSTM Layer,
int8_t* x_in = (int8_t*) malloc(ntimestep*nbatch*isize*sizeof(int8_t));
int8_t* w_in = (int8_t*) malloc(nlayers*4*osize*(isize+hsize)*sizeof(int8_t));
int8_t* output = (int8_t*) malloc(ntimestep*nbatch*hsize*sizeof(int8_t));
int8_t* h_out = (int8_t*) malloc(nlayers*nbatch*hsize*sizeof(int8_t));
for(int i=0; i<ntimestep*nbatch*isize; i++)
if (i%3 == 0)
x_in[i] = (int8_t) 2;
else if (i%3 == 1)
x_in[i] = (int8_t) -3;
else
x_in[i] = (int8_t) 100;
for(int i=0; i<nlayers*4*osize*(isize+hsize); i++)
if (i%3 == 0)
w_in[i] = (int8_t) 2;
else if (i%3 == 1)
w_in[i] = (int8_t) -3;
else
w_in[i] = (int8_t) 100;
for(int i=0; i<nlayers*nbatch*hsize; i++)
h_out[i] = (int8_t) 3;
for(int i=0; i<ntimestep*nbatch*hsize; i++)
output[i] = (int8_t) 0;
Halide::Buffer<int8_t> b_input(x_in, ntimestep, nbatch, isize);
Halide::Buffer<int8_t> b_W(w_in, NUM_LAYERS, 4, osize, isize + hsize);
Halide::Buffer<int8_t> b_output(output, ntimestep, nbatch, hsize);
Halide::Buffer<int8_t> b_h_out(h_out, nlayers, nbatch, hsize);
std::cout << "Buffers Initialized" << std::endl;
for (int i = 0; i < NB_TESTS; i++)
{
for(int i=0; i<nlayers*nbatch*hsize; i++)
h_out[i] = (int8_t) 3;
for(int i=0; i<ntimestep*nbatch*hsize; i++)
output[i] = (int8_t) 0;
start = rtclock();
flexnlp_lstm(
b_input.raw_buffer(),
b_W.raw_buffer(),
b_output.raw_buffer(),
b_h_out.raw_buffer()
);
end = rtclock();
duration_vector.push_back((end - start) * 1000);
}
print_time("performance_CPU.csv", "FlexLSTM",
{"Tiramisu"},
{median(duration_vector)});
/* Uncomment to show some resulting values
for(int i = 0; i<100; i++){
std::cout << " , " << (int) output[i];
}
*/
std::cout << "Finished" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "intnw_instruments_network_chooser.h"
#include "intnw_instruments_net_stats_wrapper.h"
#include "libcmm_net_restriction.h"
#include "debug.h"
#include <assert.h>
#include "libpowertutor.h"
#include <functional>
#include <sstream>
#include <string>
using std::max; using std::ostringstream;
using std::string;
#include <instruments_private.h>
#include <resource_weights.h>
static const char *strategy_names[NUM_STRATEGIES] = {
"wifi", "3G", "redundant"
};
struct strategy_args {
IntNWInstrumentsNetworkChooser *chooser;
InstrumentsWrappedNetStats **net_stats;
};
double
network_transfer_time(instruments_context_t ctx, void *strategy_arg, void *chooser_arg)
{
struct strategy_args *args = (struct strategy_args *)strategy_arg;
int bytelen = (int) chooser_arg;
assert(args->net_stats);
return args->chooser->calculateTransferTime(ctx, *args->net_stats,
bytelen);
}
double
network_transfer_energy_cost(instruments_context_t ctx, void *strategy_arg, void *chooser_arg)
{
struct strategy_args *args = (struct strategy_args *)strategy_arg;
int bytelen = (int) chooser_arg;
assert(args->net_stats);
return args->chooser->calculateTransferEnergy(ctx, *args->net_stats,
bytelen);
}
double
network_transfer_data_cost(instruments_context_t ctx, void *strategy_arg, void *chooser_arg)
{
struct strategy_args *args = (struct strategy_args *)strategy_arg;
int bytelen = (int) chooser_arg;
assert(args->net_stats);
return args->chooser->calculateTransferMobileData(*args->net_stats, bytelen);
}
double
IntNWInstrumentsNetworkChooser::getBandwidthUp(instruments_context_t ctx,
InstrumentsWrappedNetStats *net_stats)
{
double bw = net_stats->get_bandwidth_up(ctx);
return max(1.0, bw); // TODO: revisit. This is a hack to avoid bogus calculations.
}
double
IntNWInstrumentsNetworkChooser::getRttSeconds(instruments_context_t ctx,
InstrumentsWrappedNetStats *net_stats)
{
double rtt_seconds = net_stats->get_rtt(ctx);
return max(0.0, rtt_seconds); // TODO: revisit. This is a hack to avoid bogus calculations.
}
double
IntNWInstrumentsNetworkChooser::calculateTransferTime(instruments_context_t ctx,
InstrumentsWrappedNetStats *net_stats,
int bytelen)
{
assert(net_stats);
double bw = getBandwidthUp(ctx, net_stats);
double rtt_seconds = getRttSeconds(ctx, net_stats);
return (bytelen / bw) + rtt_seconds;
}
double
IntNWInstrumentsNetworkChooser::calculateTransferEnergy(instruments_context_t ctx,
InstrumentsWrappedNetStats *net_stats,
int bytelen)
{
assert(net_stats);
NetworkType type;
if (net_stats == wifi_stats) {
type = TYPE_WIFI;
} else if (net_stats == cellular_stats) {
type = TYPE_MOBILE;
} else assert(0);
double bw = getBandwidthUp(ctx, net_stats);
double rtt_seconds = getRttSeconds(ctx, net_stats);
return estimate_energy_cost(type, bytelen, bw, rtt_seconds * 1000.0);
}
double
IntNWInstrumentsNetworkChooser::calculateTransferMobileData(InstrumentsWrappedNetStats *net_stats,
int bytelen)
{
if (net_stats == wifi_stats) {
return 0;
} else if (net_stats == cellular_stats) {
return bytelen;
} else assert(0);
}
IntNWInstrumentsNetworkChooser::IntNWInstrumentsNetworkChooser()
: wifi_present(false), needs_reevaluation(true), chosen_strategy_type(-1)
{
dbgprintf("creating InstrumentsNetworkChooser %p\n", this);
wifi_stats = new InstrumentsWrappedNetStats("wifi");
cellular_stats = new InstrumentsWrappedNetStats("cellular");
for (int i = 0; i < NUM_STRATEGIES - 1; ++i) {
strategy_args[i] = new struct strategy_args;
strategy_args[i]->chooser = this;
}
strategy_args[NETWORK_CHOICE_WIFI]->net_stats = &wifi_stats;
strategy_args[NETWORK_CHOICE_CELLULAR]->net_stats = &cellular_stats;
for (int i = NETWORK_CHOICE_WIFI; i <= NETWORK_CHOICE_CELLULAR; ++i) {
strategies[i] =
make_strategy(network_transfer_time,
network_transfer_energy_cost,
network_transfer_data_cost,
(void *)strategy_args[i], (void *) 0);
}
strategies[NETWORK_CHOICE_BOTH] = make_redundant_strategy(strategies, 2);
EvalMethod method = EMPIRICAL_ERROR_ALL_SAMPLES_INTNW;
//EvalMethod method = EMPIRICAL_ERROR_BINNED_INTNW;
//EvalMethod method = EMPIRICAL_ERROR_BINNED;
evaluator = register_strategy_set_with_method(strategies, NUM_STRATEGIES, method);
if (shouldLoadErrors()) {
restore_evaluator(evaluator, getLoadErrorsFilename().c_str());
}
}
IntNWInstrumentsNetworkChooser::~IntNWInstrumentsNetworkChooser()
{
dbgprintf("destroying InstrumentsNetworkChooser %p\n", this);
delete wifi_stats;
delete cellular_stats;
free_strategy_evaluator(evaluator);
for (int i = 0; i < NUM_STRATEGIES; ++i) {
free_strategy(strategies[i]);
}
for (int i = NETWORK_CHOICE_WIFI; i <= NETWORK_CHOICE_CELLULAR; ++i) {
delete strategy_args[i];
}
}
bool
IntNWInstrumentsNetworkChooser::
choose_networks(u_long send_label, size_t num_bytes,
struct net_interface& local_iface,
struct net_interface& remote_iface)
{
// XXX: don't really want to require this, but it's
// XXX: true for the redundancy experiments.
// TODO: make sure that CSockMapping calls the
// TODO: right version of choose_networks.
if (num_bytes == 0) {
// TODO: can we apply the brute force method
// TODO: without knowing the size of the data?
return label_matcher.choose_networks(send_label, num_bytes,
local_iface, remote_iface);
}
assert(has_match);
if (!wifi_present) {
local_iface = cellular_local;
remote_iface = cellular_remote;
return true;
}
if (needs_reevaluation) {
chosen_strategy_type = chooseNetwork(num_bytes);
needs_reevaluation = false;
}
dbgprintf("chooseNetwork: %s\n", strategy_names[chosen_strategy_type]);
if (chosen_strategy_type == NETWORK_CHOICE_WIFI ||
chosen_strategy_type == NETWORK_CHOICE_BOTH) {
local_iface = wifi_local;
remote_iface = wifi_remote;
} else {
assert(chosen_strategy_type == NETWORK_CHOICE_CELLULAR);
local_iface = cellular_local;
remote_iface = cellular_remote;
}
return true;
}
void
IntNWInstrumentsNetworkChooser::consider(struct net_interface local_iface,
struct net_interface remote_iface)
{
// pass it to a delegate matcher in case choose_networks
// gets called without knowing how many bytes will be sent
label_matcher.consider(local_iface, remote_iface);
has_match = true;
if (matches_type(NET_TYPE_WIFI, local_iface, remote_iface)) {
wifi_present = true;
wifi_local = local_iface;
wifi_remote = remote_iface;
} else if (matches_type(NET_TYPE_THREEG, local_iface, remote_iface)) {
cellular_local = local_iface;
cellular_remote = remote_iface;
} else assert(false);
}
void
IntNWInstrumentsNetworkChooser::reset()
{
NetworkChooserImpl::reset();
wifi_present = false;
needs_reevaluation = true;
chosen_strategy_type = -1;
label_matcher.reset();
}
int
IntNWInstrumentsNetworkChooser::chooseNetwork(int bytelen)
{
instruments_strategy_t chosen = choose_strategy(evaluator, (void *)bytelen);
return getStrategyIndex(chosen);
}
int IntNWInstrumentsNetworkChooser::getStrategyIndex(instruments_strategy_t strategy)
{
for (int i = 0; i < NUM_STRATEGIES; ++i) {
if (strategy == strategies[i]) {
return i;
}
}
assert(0);
}
void
IntNWInstrumentsNetworkChooser::setFixedResourceWeights(double energyWeight,
double dataWeight)
{
set_fixed_resource_weights(energyWeight, dataWeight);
}
static int energy_spent_mJ = 0;
static int data_spent_bytes = 0;
void
IntNWInstrumentsNetworkChooser::setAdaptiveResourceBudgets(double goalTime,
int energyBudgetMilliJoules,
int dataBudgetBytes)
{
struct timeval goaltime_tv;
goaltime_tv.tv_sec = static_cast<time_t>(goalTime);
goaltime_tv.tv_usec = (goalTime - goaltime_tv.tv_sec) * 1000000;
energy_spent_mJ = 0;
data_spent_bytes = 0;
set_resource_budgets(goaltime_tv, energyBudgetMilliJoules, dataBudgetBytes);
}
void IntNWInstrumentsNetworkChooser::updateResourceWeights()
{
int new_energy_spent_mJ = energy_consumed_since_reset();
int new_data_spent_bytes = mobile_bytes_consumed_since_reset();
report_spent_energy(new_energy_spent_mJ - energy_spent_mJ);
report_spent_data(new_data_spent_bytes - data_spent_bytes);
update_weights_now();
energy_spent_mJ = new_energy_spent_mJ;
data_spent_bytes = new_data_spent_bytes;
}
double IntNWInstrumentsNetworkChooser::getEnergyWeight()
{
return get_energy_cost_weight();
}
double IntNWInstrumentsNetworkChooser::getDataWeight()
{
return get_data_cost_weight();
}
void
IntNWInstrumentsNetworkChooser::reportNetStats(int network_type,
double new_bw,
double new_bw_estimate,
double new_latency_seconds,
double new_latency_estimate)
{
InstrumentsWrappedNetStats *stats = NULL;
switch (network_type) {
case NET_TYPE_WIFI:
stats = wifi_stats;
break;
case NET_TYPE_THREEG:
stats = cellular_stats;
break;
default:
assert(false);
break;
}
ostringstream oss;
oss << "Adding new stats to " << net_type_name(network_type)
<< " network estimator: ";
if (new_bw > 0.0) {
oss << "bandwidth: obs " << new_bw << " est " << new_bw_estimate;
}
if (new_latency_seconds > 0.0) {
oss << " latency: obs " << new_latency_seconds << " est " << new_latency_estimate;
}
oss << "\n";
dbgprintf("%s", oss.str().c_str());
// XXX: hackish. Should separate bw and RTT updates.
stats->update(new_bw, new_bw_estimate,
new_latency_seconds, new_latency_estimate);
needs_reevaluation = true;
}
void
IntNWInstrumentsNetworkChooser::setRedundancyStrategy()
{
dbgprintf("setting IntNWInstrumentsNetworkChooser::RedundancyStrategy\n");
assert(redundancyStrategy == NULL);
redundancyStrategy =
new IntNWInstrumentsNetworkChooser::RedundancyStrategy(this);
}
IntNWInstrumentsNetworkChooser::RedundancyStrategy::
RedundancyStrategy(IntNWInstrumentsNetworkChooser *chooser_)
: chooser(chooser_)
{
}
bool
IntNWInstrumentsNetworkChooser::RedundancyStrategy::
shouldTransmitRedundantly(PendingSenderIROB *psirob)
{
assert(chooser->has_match);
assert(chooser->chosen_strategy_type != -1);
dbgprintf("shouldTransmitRedundantly: Chosen network strategy: %s\n",
strategy_names[chooser->chosen_strategy_type]);
return (chooser->chosen_strategy_type == NETWORK_CHOICE_BOTH);
}
std::string IntNWInstrumentsNetworkChooser::load_errors_filename;
std::string IntNWInstrumentsNetworkChooser::save_errors_filename;
bool
IntNWInstrumentsNetworkChooser::shouldLoadErrors()
{
return !load_errors_filename.empty();
}
bool
IntNWInstrumentsNetworkChooser::shouldSaveErrors()
{
return !save_errors_filename.empty();
}
std::string
IntNWInstrumentsNetworkChooser::getLoadErrorsFilename()
{
return load_errors_filename;
}
std::string
IntNWInstrumentsNetworkChooser::getSaveErrorsFilename()
{
return save_errors_filename;
}
void
IntNWInstrumentsNetworkChooser::setLoadErrorsFilename(const std::string& filename)
{
load_errors_filename = filename;
}
void
IntNWInstrumentsNetworkChooser::setSaveErrorsFilename(const std::string& filename)
{
save_errors_filename = filename;
}
void
IntNWInstrumentsNetworkChooser::saveToFile()
{
if (shouldSaveErrors()) {
string filename = getSaveErrorsFilename();
dbgprintf("Saving IntNWInstrumentsNetworkChooser %p to %s\n",
this, filename.c_str());
save_evaluator(evaluator, filename.c_str());
}
}
<commit_msg>Switched to confidence bounds method. TODO: make it an option in /etc/cmm_config.<commit_after>#include "intnw_instruments_network_chooser.h"
#include "intnw_instruments_net_stats_wrapper.h"
#include "libcmm_net_restriction.h"
#include "debug.h"
#include <assert.h>
#include "libpowertutor.h"
#include <functional>
#include <sstream>
#include <string>
using std::max; using std::ostringstream;
using std::string;
#include <instruments_private.h>
#include <resource_weights.h>
static const char *strategy_names[NUM_STRATEGIES] = {
"wifi", "3G", "redundant"
};
struct strategy_args {
IntNWInstrumentsNetworkChooser *chooser;
InstrumentsWrappedNetStats **net_stats;
};
double
network_transfer_time(instruments_context_t ctx, void *strategy_arg, void *chooser_arg)
{
struct strategy_args *args = (struct strategy_args *)strategy_arg;
int bytelen = (int) chooser_arg;
assert(args->net_stats);
return args->chooser->calculateTransferTime(ctx, *args->net_stats,
bytelen);
}
double
network_transfer_energy_cost(instruments_context_t ctx, void *strategy_arg, void *chooser_arg)
{
struct strategy_args *args = (struct strategy_args *)strategy_arg;
int bytelen = (int) chooser_arg;
assert(args->net_stats);
return args->chooser->calculateTransferEnergy(ctx, *args->net_stats,
bytelen);
}
double
network_transfer_data_cost(instruments_context_t ctx, void *strategy_arg, void *chooser_arg)
{
struct strategy_args *args = (struct strategy_args *)strategy_arg;
int bytelen = (int) chooser_arg;
assert(args->net_stats);
return args->chooser->calculateTransferMobileData(*args->net_stats, bytelen);
}
double
IntNWInstrumentsNetworkChooser::getBandwidthUp(instruments_context_t ctx,
InstrumentsWrappedNetStats *net_stats)
{
double bw = net_stats->get_bandwidth_up(ctx);
return max(1.0, bw); // TODO: revisit. This is a hack to avoid bogus calculations.
}
double
IntNWInstrumentsNetworkChooser::getRttSeconds(instruments_context_t ctx,
InstrumentsWrappedNetStats *net_stats)
{
double rtt_seconds = net_stats->get_rtt(ctx);
return max(0.0, rtt_seconds); // TODO: revisit. This is a hack to avoid bogus calculations.
}
double
IntNWInstrumentsNetworkChooser::calculateTransferTime(instruments_context_t ctx,
InstrumentsWrappedNetStats *net_stats,
int bytelen)
{
assert(net_stats);
double bw = getBandwidthUp(ctx, net_stats);
double rtt_seconds = getRttSeconds(ctx, net_stats);
return (bytelen / bw) + rtt_seconds;
}
double
IntNWInstrumentsNetworkChooser::calculateTransferEnergy(instruments_context_t ctx,
InstrumentsWrappedNetStats *net_stats,
int bytelen)
{
assert(net_stats);
NetworkType type;
if (net_stats == wifi_stats) {
type = TYPE_WIFI;
} else if (net_stats == cellular_stats) {
type = TYPE_MOBILE;
} else assert(0);
double bw = getBandwidthUp(ctx, net_stats);
double rtt_seconds = getRttSeconds(ctx, net_stats);
return estimate_energy_cost(type, bytelen, bw, rtt_seconds * 1000.0);
}
double
IntNWInstrumentsNetworkChooser::calculateTransferMobileData(InstrumentsWrappedNetStats *net_stats,
int bytelen)
{
if (net_stats == wifi_stats) {
return 0;
} else if (net_stats == cellular_stats) {
return bytelen;
} else assert(0);
}
IntNWInstrumentsNetworkChooser::IntNWInstrumentsNetworkChooser()
: wifi_present(false), needs_reevaluation(true), chosen_strategy_type(-1)
{
dbgprintf("creating InstrumentsNetworkChooser %p\n", this);
wifi_stats = new InstrumentsWrappedNetStats("wifi");
cellular_stats = new InstrumentsWrappedNetStats("cellular");
for (int i = 0; i < NUM_STRATEGIES - 1; ++i) {
strategy_args[i] = new struct strategy_args;
strategy_args[i]->chooser = this;
}
strategy_args[NETWORK_CHOICE_WIFI]->net_stats = &wifi_stats;
strategy_args[NETWORK_CHOICE_CELLULAR]->net_stats = &cellular_stats;
for (int i = NETWORK_CHOICE_WIFI; i <= NETWORK_CHOICE_CELLULAR; ++i) {
strategies[i] =
make_strategy(network_transfer_time,
network_transfer_energy_cost,
network_transfer_data_cost,
(void *)strategy_args[i], (void *) 0);
}
strategies[NETWORK_CHOICE_BOTH] = make_redundant_strategy(strategies, 2);
EvalMethod method = CONFIDENCE_BOUNDS;
//EvalMethod method = EMPIRICAL_ERROR_ALL_SAMPLES_INTNW;
//EvalMethod method = EMPIRICAL_ERROR_BINNED_INTNW;
//EvalMethod method = EMPIRICAL_ERROR_BINNED;
evaluator = register_strategy_set_with_method(strategies, NUM_STRATEGIES, method);
if (shouldLoadErrors()) {
restore_evaluator(evaluator, getLoadErrorsFilename().c_str());
}
}
IntNWInstrumentsNetworkChooser::~IntNWInstrumentsNetworkChooser()
{
dbgprintf("destroying InstrumentsNetworkChooser %p\n", this);
delete wifi_stats;
delete cellular_stats;
free_strategy_evaluator(evaluator);
for (int i = 0; i < NUM_STRATEGIES; ++i) {
free_strategy(strategies[i]);
}
for (int i = NETWORK_CHOICE_WIFI; i <= NETWORK_CHOICE_CELLULAR; ++i) {
delete strategy_args[i];
}
}
bool
IntNWInstrumentsNetworkChooser::
choose_networks(u_long send_label, size_t num_bytes,
struct net_interface& local_iface,
struct net_interface& remote_iface)
{
// XXX: don't really want to require this, but it's
// XXX: true for the redundancy experiments.
// TODO: make sure that CSockMapping calls the
// TODO: right version of choose_networks.
if (num_bytes == 0) {
// TODO: can we apply the brute force method
// TODO: without knowing the size of the data?
return label_matcher.choose_networks(send_label, num_bytes,
local_iface, remote_iface);
}
assert(has_match);
if (!wifi_present) {
local_iface = cellular_local;
remote_iface = cellular_remote;
return true;
}
if (needs_reevaluation) {
chosen_strategy_type = chooseNetwork(num_bytes);
needs_reevaluation = false;
}
dbgprintf("chooseNetwork: %s\n", strategy_names[chosen_strategy_type]);
if (chosen_strategy_type == NETWORK_CHOICE_WIFI ||
chosen_strategy_type == NETWORK_CHOICE_BOTH) {
local_iface = wifi_local;
remote_iface = wifi_remote;
} else {
assert(chosen_strategy_type == NETWORK_CHOICE_CELLULAR);
local_iface = cellular_local;
remote_iface = cellular_remote;
}
return true;
}
void
IntNWInstrumentsNetworkChooser::consider(struct net_interface local_iface,
struct net_interface remote_iface)
{
// pass it to a delegate matcher in case choose_networks
// gets called without knowing how many bytes will be sent
label_matcher.consider(local_iface, remote_iface);
has_match = true;
if (matches_type(NET_TYPE_WIFI, local_iface, remote_iface)) {
wifi_present = true;
wifi_local = local_iface;
wifi_remote = remote_iface;
} else if (matches_type(NET_TYPE_THREEG, local_iface, remote_iface)) {
cellular_local = local_iface;
cellular_remote = remote_iface;
} else assert(false);
}
void
IntNWInstrumentsNetworkChooser::reset()
{
NetworkChooserImpl::reset();
wifi_present = false;
needs_reevaluation = true;
chosen_strategy_type = -1;
label_matcher.reset();
}
int
IntNWInstrumentsNetworkChooser::chooseNetwork(int bytelen)
{
instruments_strategy_t chosen = choose_strategy(evaluator, (void *)bytelen);
return getStrategyIndex(chosen);
}
int IntNWInstrumentsNetworkChooser::getStrategyIndex(instruments_strategy_t strategy)
{
for (int i = 0; i < NUM_STRATEGIES; ++i) {
if (strategy == strategies[i]) {
return i;
}
}
assert(0);
}
void
IntNWInstrumentsNetworkChooser::setFixedResourceWeights(double energyWeight,
double dataWeight)
{
set_fixed_resource_weights(energyWeight, dataWeight);
}
static int energy_spent_mJ = 0;
static int data_spent_bytes = 0;
void
IntNWInstrumentsNetworkChooser::setAdaptiveResourceBudgets(double goalTime,
int energyBudgetMilliJoules,
int dataBudgetBytes)
{
struct timeval goaltime_tv;
goaltime_tv.tv_sec = static_cast<time_t>(goalTime);
goaltime_tv.tv_usec = (goalTime - goaltime_tv.tv_sec) * 1000000;
energy_spent_mJ = 0;
data_spent_bytes = 0;
set_resource_budgets(goaltime_tv, energyBudgetMilliJoules, dataBudgetBytes);
}
void IntNWInstrumentsNetworkChooser::updateResourceWeights()
{
int new_energy_spent_mJ = energy_consumed_since_reset();
int new_data_spent_bytes = mobile_bytes_consumed_since_reset();
report_spent_energy(new_energy_spent_mJ - energy_spent_mJ);
report_spent_data(new_data_spent_bytes - data_spent_bytes);
update_weights_now();
energy_spent_mJ = new_energy_spent_mJ;
data_spent_bytes = new_data_spent_bytes;
}
double IntNWInstrumentsNetworkChooser::getEnergyWeight()
{
return get_energy_cost_weight();
}
double IntNWInstrumentsNetworkChooser::getDataWeight()
{
return get_data_cost_weight();
}
void
IntNWInstrumentsNetworkChooser::reportNetStats(int network_type,
double new_bw,
double new_bw_estimate,
double new_latency_seconds,
double new_latency_estimate)
{
InstrumentsWrappedNetStats *stats = NULL;
switch (network_type) {
case NET_TYPE_WIFI:
stats = wifi_stats;
break;
case NET_TYPE_THREEG:
stats = cellular_stats;
break;
default:
assert(false);
break;
}
ostringstream oss;
oss << "Adding new stats to " << net_type_name(network_type)
<< " network estimator: ";
if (new_bw > 0.0) {
oss << "bandwidth: obs " << new_bw << " est " << new_bw_estimate;
}
if (new_latency_seconds > 0.0) {
oss << " latency: obs " << new_latency_seconds << " est " << new_latency_estimate;
}
oss << "\n";
dbgprintf("%s", oss.str().c_str());
// XXX: hackish. Should separate bw and RTT updates.
stats->update(new_bw, new_bw_estimate,
new_latency_seconds, new_latency_estimate);
needs_reevaluation = true;
}
void
IntNWInstrumentsNetworkChooser::setRedundancyStrategy()
{
dbgprintf("setting IntNWInstrumentsNetworkChooser::RedundancyStrategy\n");
assert(redundancyStrategy == NULL);
redundancyStrategy =
new IntNWInstrumentsNetworkChooser::RedundancyStrategy(this);
}
IntNWInstrumentsNetworkChooser::RedundancyStrategy::
RedundancyStrategy(IntNWInstrumentsNetworkChooser *chooser_)
: chooser(chooser_)
{
}
bool
IntNWInstrumentsNetworkChooser::RedundancyStrategy::
shouldTransmitRedundantly(PendingSenderIROB *psirob)
{
assert(chooser->has_match);
assert(chooser->chosen_strategy_type != -1);
dbgprintf("shouldTransmitRedundantly: Chosen network strategy: %s\n",
strategy_names[chooser->chosen_strategy_type]);
return (chooser->chosen_strategy_type == NETWORK_CHOICE_BOTH);
}
std::string IntNWInstrumentsNetworkChooser::load_errors_filename;
std::string IntNWInstrumentsNetworkChooser::save_errors_filename;
bool
IntNWInstrumentsNetworkChooser::shouldLoadErrors()
{
return !load_errors_filename.empty();
}
bool
IntNWInstrumentsNetworkChooser::shouldSaveErrors()
{
return !save_errors_filename.empty();
}
std::string
IntNWInstrumentsNetworkChooser::getLoadErrorsFilename()
{
return load_errors_filename;
}
std::string
IntNWInstrumentsNetworkChooser::getSaveErrorsFilename()
{
return save_errors_filename;
}
void
IntNWInstrumentsNetworkChooser::setLoadErrorsFilename(const std::string& filename)
{
load_errors_filename = filename;
}
void
IntNWInstrumentsNetworkChooser::setSaveErrorsFilename(const std::string& filename)
{
save_errors_filename = filename;
}
void
IntNWInstrumentsNetworkChooser::saveToFile()
{
if (shouldSaveErrors()) {
string filename = getSaveErrorsFilename();
dbgprintf("Saving IntNWInstrumentsNetworkChooser %p to %s\n",
this, filename.c_str());
save_evaluator(evaluator, filename.c_str());
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Intel(r) Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http ://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __VMF_TYPES_H__
#define __VMF_TYPES_H__
/*!
* \file types.hpp
* \brief Header file contains declarations of VMF numeric types
*/
#include <cstdint>
#include <cmath>
#include <memory>
#include <cstring>
#include <utility>
#include <vector>
namespace vmf
{
/*!
* \brief Compares double values
*/
static bool DOUBLE_EQ(double a, double b)
{
return std::abs(a - b) < std::numeric_limits<double>::epsilon();
}
/*!
* \brief Character type. Equivalent of char type in C/C++
*/
typedef char vmf_char;
/*!
* \brief 64-bit integer type.
*/
typedef int64_t vmf_integer;
/*!
* \brief Double precesion floating point type.
*/
typedef double vmf_real;
/*!
* \brief String type.
*/
typedef std::string vmf_string;
/*!
* \brief floating point vector2D type.
*/
struct vmf_vec2d
{
vmf_vec2d() : x(0), y(0) {}
vmf_vec2d(vmf_real _x, vmf_real _y) : x(_x), y(_y) {}
bool operator == (const vmf_vec2d& value) const
{
return DOUBLE_EQ(x, value.x) && DOUBLE_EQ(y, value.y);
}
vmf_real x;
vmf_real y;
};
/*!
* \brief floating point vector3D type.
*/
struct vmf_vec3d : vmf_vec2d
{
vmf_vec3d() : vmf_vec2d(), z(0){}
vmf_vec3d(vmf_real _x, vmf_real _y, vmf_real _z) : vmf_vec2d(_x, _y), z(_z) {}
bool operator == (const vmf_vec3d& value) const
{
return vmf_vec2d::operator==(value) && DOUBLE_EQ(z, value.z);
}
vmf_real z;
};
/*!
* \brief floating point vector4D type.
*/
struct vmf_vec4d : vmf_vec3d
{
vmf_vec4d() : vmf_vec3d(), w(0){}
vmf_vec4d(vmf_real _x, vmf_real _y, vmf_real _z, vmf_real _w) : vmf_vec3d(_x, _y, _z), w(_w) {}
bool operator == (const vmf_vec4d& value) const
{
return vmf_vec3d::operator==(value) && DOUBLE_EQ(w, value.w);
}
vmf_real w;
};
/*!
* \brief binary buffer with arbitrary content
*/
struct vmf_rawbuffer : public std::vector<char>
{
public:
vmf_rawbuffer() : std::vector<char>()
{ }
explicit vmf_rawbuffer(const vmf_rawbuffer& other) : std::vector<char>(other)
{ }
vmf_rawbuffer(vmf_rawbuffer&& other)
{
*this = std::move(other);
}
vmf_rawbuffer& operator=(const vmf_rawbuffer& other)
{
return static_cast<vmf_rawbuffer&>(
std::vector<char>::operator=(
static_cast< const std::vector<char> & >(other)));
}
vmf_rawbuffer(const char* str, const size_t len)
{
*this = (str != nullptr) ? vmf_rawbuffer(str, str + len) : vmf_rawbuffer(len);
}
private:
// These constructors are private
// because a Variant value can be converted to both size_t and vmf_rawbuffer
vmf_rawbuffer(const size_t len) : std::vector<char>(len)
{ }
vmf_rawbuffer(const char* strBegin,
const char* strEnd) : std::vector<char>(strBegin, strEnd)
{ }
};
} /* vmf */
#endif /* __VMF_TYPES_H__ */
<commit_msg>std::swap() instead of std::move()<commit_after>/*
* Copyright 2015 Intel(r) Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http ://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __VMF_TYPES_H__
#define __VMF_TYPES_H__
/*!
* \file types.hpp
* \brief Header file contains declarations of VMF numeric types
*/
#include <cstdint>
#include <cmath>
#include <memory>
#include <cstring>
#include <utility>
#include <vector>
namespace vmf
{
/*!
* \brief Compares double values
*/
static bool DOUBLE_EQ(double a, double b)
{
return std::abs(a - b) < std::numeric_limits<double>::epsilon();
}
/*!
* \brief Character type. Equivalent of char type in C/C++
*/
typedef char vmf_char;
/*!
* \brief 64-bit integer type.
*/
typedef int64_t vmf_integer;
/*!
* \brief Double precesion floating point type.
*/
typedef double vmf_real;
/*!
* \brief String type.
*/
typedef std::string vmf_string;
/*!
* \brief floating point vector2D type.
*/
struct vmf_vec2d
{
vmf_vec2d() : x(0), y(0) {}
vmf_vec2d(vmf_real _x, vmf_real _y) : x(_x), y(_y) {}
bool operator == (const vmf_vec2d& value) const
{
return DOUBLE_EQ(x, value.x) && DOUBLE_EQ(y, value.y);
}
vmf_real x;
vmf_real y;
};
/*!
* \brief floating point vector3D type.
*/
struct vmf_vec3d : vmf_vec2d
{
vmf_vec3d() : vmf_vec2d(), z(0){}
vmf_vec3d(vmf_real _x, vmf_real _y, vmf_real _z) : vmf_vec2d(_x, _y), z(_z) {}
bool operator == (const vmf_vec3d& value) const
{
return vmf_vec2d::operator==(value) && DOUBLE_EQ(z, value.z);
}
vmf_real z;
};
/*!
* \brief floating point vector4D type.
*/
struct vmf_vec4d : vmf_vec3d
{
vmf_vec4d() : vmf_vec3d(), w(0){}
vmf_vec4d(vmf_real _x, vmf_real _y, vmf_real _z, vmf_real _w) : vmf_vec3d(_x, _y, _z), w(_w) {}
bool operator == (const vmf_vec4d& value) const
{
return vmf_vec3d::operator==(value) && DOUBLE_EQ(w, value.w);
}
vmf_real w;
};
/*!
* \brief binary buffer with arbitrary content
*/
struct vmf_rawbuffer : public std::vector<char>
{
public:
vmf_rawbuffer() : std::vector<char>()
{ }
explicit vmf_rawbuffer(const vmf_rawbuffer& other) : std::vector<char>(other)
{ }
vmf_rawbuffer(vmf_rawbuffer&& other)
{
std::swap(*this, other);
}
vmf_rawbuffer& operator=(const vmf_rawbuffer& other)
{
return static_cast<vmf_rawbuffer&>(
std::vector<char>::operator=(
static_cast< const std::vector<char> & >(other)));
}
vmf_rawbuffer(const char* str, const size_t len)
{
*this = (str != nullptr) ? vmf_rawbuffer(str, str + len) : vmf_rawbuffer(len);
}
private:
// These constructors are private
// because a Variant value can be converted to both size_t and vmf_rawbuffer
vmf_rawbuffer(const size_t len) : std::vector<char>(len)
{ }
vmf_rawbuffer(const char* strBegin,
const char* strEnd) : std::vector<char>(strBegin, strEnd)
{ }
};
} /* vmf */
#endif /* __VMF_TYPES_H__ */
<|endoftext|> |
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/fnet/transport.h>
#include <vespa/fnet/transport_thread.h>
#include <vespa/fnet/iserveradapter.h>
#include <vespa/fnet/ipacketstreamer.h>
#include <vespa/fnet/connector.h>
#include <vespa/fnet/connection.h>
#include <vespa/fastos/thread.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <thread>
#include <chrono>
#include <set>
using namespace std::literals;
struct DummyAdapter : FNET_IServerAdapter {
bool InitChannel(FNET_Channel *, uint32_t) override { return false; }
};
struct DummyStreamer : FNET_IPacketStreamer {
bool GetPacketInfo(FNET_DataBuffer *, uint32_t *, uint32_t *, uint32_t *, bool *) override { return false; }
FNET_Packet *Decode(FNET_DataBuffer *, uint32_t, uint32_t, FNET_Context) override { return nullptr; }
void Encode(FNET_Packet *, uint32_t, FNET_DataBuffer *) override {}
};
struct Fixture {
DummyStreamer streamer;
DummyAdapter adapter;
FastOS_ThreadPool thread_pool;
FNET_Transport client;
FNET_Transport server;
Fixture() : streamer(), adapter(), thread_pool(128_Ki), client(8), server(8)
{
ASSERT_TRUE(client.Start(&thread_pool));
ASSERT_TRUE(server.Start(&thread_pool));
}
void wait_for_components(size_t client_cnt, size_t server_cnt) {
bool ok = false;
for (size_t i = 0; !ok && (i < 10000); ++i) {
std::this_thread::sleep_for(3ms);
ok = ((client.GetNumIOComponents() == client_cnt) &&
(server.GetNumIOComponents() == server_cnt));
}
EXPECT_EQUAL(client.GetNumIOComponents(), client_cnt);
EXPECT_EQUAL(server.GetNumIOComponents(), server_cnt);
}
~Fixture() {
server.ShutDown(true);
client.ShutDown(true);
thread_pool.Close();
}
};
void check_threads(FNET_Transport &transport, size_t num_threads, const vespalib::string &tag) {
std::set<FNET_TransportThread *> threads;
while (threads.size() < num_threads) {
threads.insert(transport.select_thread(nullptr, 0));
}
for (auto thread: threads) {
uint32_t cnt = thread->GetNumIOComponents();
fprintf(stderr, "-- %s thread: %u io components\n", tag.c_str(), cnt);
EXPECT_GREATER(cnt, 1u);
}
}
TEST_F("require that connections are spread among transport threads", Fixture)
{
FNET_Connector *listener = f1.server.Listen("tcp/0", &f1.streamer, &f1.adapter);
ASSERT_TRUE(listener);
uint32_t port = listener->GetPortNumber();
vespalib::string spec = vespalib::make_string("tcp/localhost:%u", port);
std::vector<FNET_Connection *> connections;
for (size_t i = 0; i < 256; ++i) {
std::this_thread::sleep_for(1ms);
connections.push_back(f1.client.Connect(spec.c_str(), &f1.streamer));
ASSERT_TRUE(connections.back());
}
f1.wait_for_components(256, 257);
check_threads(f1.client, 8, "client");
check_threads(f1.server, 8, "server");
listener->SubRef();
for (FNET_Connection *conn: connections) {
conn->SubRef();
}
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>Slow down when getting too far ahead of server.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/fnet/transport.h>
#include <vespa/fnet/transport_thread.h>
#include <vespa/fnet/iserveradapter.h>
#include <vespa/fnet/ipacketstreamer.h>
#include <vespa/fnet/connector.h>
#include <vespa/fnet/connection.h>
#include <vespa/fastos/thread.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <thread>
#include <chrono>
#include <set>
using namespace std::literals;
struct DummyAdapter : FNET_IServerAdapter {
bool InitChannel(FNET_Channel *, uint32_t) override { return false; }
};
struct DummyStreamer : FNET_IPacketStreamer {
bool GetPacketInfo(FNET_DataBuffer *, uint32_t *, uint32_t *, uint32_t *, bool *) override { return false; }
FNET_Packet *Decode(FNET_DataBuffer *, uint32_t, uint32_t, FNET_Context) override { return nullptr; }
void Encode(FNET_Packet *, uint32_t, FNET_DataBuffer *) override {}
};
struct Fixture {
DummyStreamer streamer;
DummyAdapter adapter;
FastOS_ThreadPool thread_pool;
FNET_Transport client;
FNET_Transport server;
Fixture() : streamer(), adapter(), thread_pool(128_Ki), client(8), server(8)
{
ASSERT_TRUE(client.Start(&thread_pool));
ASSERT_TRUE(server.Start(&thread_pool));
}
void wait_for_components(size_t client_cnt, size_t server_cnt) {
bool ok = false;
for (size_t i = 0; !ok && (i < 10000); ++i) {
std::this_thread::sleep_for(3ms);
ok = ((client.GetNumIOComponents() == client_cnt) &&
(server.GetNumIOComponents() == server_cnt));
}
EXPECT_EQUAL(client.GetNumIOComponents(), client_cnt);
EXPECT_EQUAL(server.GetNumIOComponents(), server_cnt);
}
~Fixture() {
server.ShutDown(true);
client.ShutDown(true);
thread_pool.Close();
}
};
void check_threads(FNET_Transport &transport, size_t num_threads, const vespalib::string &tag) {
std::set<FNET_TransportThread *> threads;
while (threads.size() < num_threads) {
threads.insert(transport.select_thread(nullptr, 0));
}
for (auto thread: threads) {
uint32_t cnt = thread->GetNumIOComponents();
fprintf(stderr, "-- %s thread: %u io components\n", tag.c_str(), cnt);
EXPECT_GREATER(cnt, 1u);
}
}
TEST_F("require that connections are spread among transport threads", Fixture)
{
FNET_Connector *listener = f1.server.Listen("tcp/0", &f1.streamer, &f1.adapter);
ASSERT_TRUE(listener);
uint32_t port = listener->GetPortNumber();
vespalib::string spec = vespalib::make_string("tcp/localhost:%u", port);
std::vector<FNET_Connection *> connections;
for (size_t i = 0; i < 256; ++i) {
std::this_thread::sleep_for(1ms);
if (i > f1.server.GetNumIOComponents() + 16) {
/*
* tcp listen backlog is limited (cf. SOMAXCONN).
* Slow down when getting too far ahead of server.
*/
std::this_thread::sleep_for(10ms);
}
connections.push_back(f1.client.Connect(spec.c_str(), &f1.streamer));
ASSERT_TRUE(connections.back());
}
f1.wait_for_components(256, 257);
check_threads(f1.client, 8, "client");
check_threads(f1.server, 8, "server");
listener->SubRef();
for (FNET_Connection *conn: connections) {
conn->SubRef();
}
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2018 Cisco and/or its affiliates.
* 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 <vom/route.hpp>
#include <vom/route_api_types.hpp>
namespace VOM {
void
to_vpp(const route::path& p, vapi_payload_ip_add_del_route& payload)
{
payload.is_drop = 0;
payload.is_unreach = 0;
payload.is_prohibit = 0;
payload.is_local = 0;
payload.is_classify = 0;
payload.is_multipath = 0;
payload.is_resolve_host = 0;
payload.is_resolve_attached = 0;
if (route::path::flags_t::DVR & p.flags()) {
payload.is_dvr = 1;
}
if (route::path::special_t::STANDARD == p.type()) {
uint8_t path_v6;
to_bytes(p.nh(), &path_v6, payload.next_hop_address);
if (p.rd()) {
payload.next_hop_table_id = p.rd()->table_id();
}
if (p.itf()) {
payload.next_hop_sw_if_index = p.itf()->handle().value();
}
} else if (route::path::special_t::DROP == p.type()) {
payload.is_drop = 1;
} else if (route::path::special_t::UNREACH == p.type()) {
payload.is_unreach = 1;
} else if (route::path::special_t::PROHIBIT == p.type()) {
payload.is_prohibit = 1;
} else if (route::path::special_t::LOCAL == p.type()) {
payload.is_local = 1;
}
payload.next_hop_weight = p.weight();
payload.next_hop_preference = p.preference();
payload.next_hop_via_label = 0;
payload.classify_table_index = 0;
}
void
to_vpp(const route::path& p, vapi_payload_ip_mroute_add_del& payload)
{
payload.next_hop_afi = p.nh_proto();
if (route::path::special_t::STANDARD == p.type()) {
uint8_t path_v6;
to_bytes(p.nh(), &path_v6, payload.nh_address);
if (p.itf()) {
payload.next_hop_sw_if_index = p.itf()->handle().value();
}
payload.next_hop_afi = p.nh_proto();
} else if (route::path::special_t::LOCAL == p.type()) {
payload.is_local = 1;
}
}
route::path
from_vpp(const vapi_type_fib_path& p, const nh_proto_t& nhp)
{
if (p.is_local) {
return route::path(route::path::special_t::LOCAL);
} else if (p.is_drop) {
return route::path(route::path::special_t::DROP);
} else if (p.is_unreach) {
return route::path(route::path::special_t::UNREACH);
} else if (p.is_prohibit) {
return route::path(route::path::special_t::PROHIBIT);
} else {
boost::asio::ip::address address =
from_bytes(nh_proto_t::IPV6 == nhp, p.next_hop);
std::shared_ptr<interface> itf = interface::find(p.sw_if_index);
if (itf) {
if (p.is_dvr) {
return route::path(*itf, nhp, route::path::flags_t::DVR, p.weight,
p.preference);
} else {
return route::path(address, *itf, p.weight, p.preference);
}
} else {
std::shared_ptr<route_domain> rd = route_domain::find(p.table_id);
if (rd) {
return route::path(*rd, address, p.weight, p.preference);
}
}
}
VOM_LOG(log_level_t::ERROR) << "cannot decode: ";
return route::path(route::path::special_t::DROP);
}
};
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "mozilla")
* End:
*/
<commit_msg>VOM: recurive route update fix<commit_after>/*
* Copyright (c) 2018 Cisco and/or its affiliates.
* 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 <vom/route.hpp>
#include <vom/route_api_types.hpp>
namespace VOM {
void
to_vpp(const route::path& p, vapi_payload_ip_add_del_route& payload)
{
payload.is_drop = 0;
payload.is_unreach = 0;
payload.is_prohibit = 0;
payload.is_local = 0;
payload.is_classify = 0;
payload.is_resolve_host = 0;
payload.is_resolve_attached = 0;
if (route::path::flags_t::DVR & p.flags()) {
payload.is_dvr = 1;
}
if (route::path::special_t::STANDARD == p.type()) {
uint8_t path_v6;
to_bytes(p.nh(), &path_v6, payload.next_hop_address);
payload.next_hop_sw_if_index = 0xffffffff;
if (p.rd()) {
payload.next_hop_table_id = p.rd()->table_id();
}
if (p.itf()) {
payload.next_hop_sw_if_index = p.itf()->handle().value();
}
} else if (route::path::special_t::DROP == p.type()) {
payload.is_drop = 1;
} else if (route::path::special_t::UNREACH == p.type()) {
payload.is_unreach = 1;
} else if (route::path::special_t::PROHIBIT == p.type()) {
payload.is_prohibit = 1;
} else if (route::path::special_t::LOCAL == p.type()) {
payload.is_local = 1;
}
payload.next_hop_weight = p.weight();
payload.next_hop_preference = p.preference();
payload.next_hop_via_label = 0x100000;
payload.classify_table_index = 0;
}
void
to_vpp(const route::path& p, vapi_payload_ip_mroute_add_del& payload)
{
payload.next_hop_afi = p.nh_proto();
if (route::path::special_t::STANDARD == p.type()) {
uint8_t path_v6;
to_bytes(p.nh(), &path_v6, payload.nh_address);
if (p.itf()) {
payload.next_hop_sw_if_index = p.itf()->handle().value();
}
payload.next_hop_afi = p.nh_proto();
} else if (route::path::special_t::LOCAL == p.type()) {
payload.is_local = 1;
}
}
route::path
from_vpp(const vapi_type_fib_path& p, const nh_proto_t& nhp)
{
if (p.is_local) {
return route::path(route::path::special_t::LOCAL);
} else if (p.is_drop) {
return route::path(route::path::special_t::DROP);
} else if (p.is_unreach) {
return route::path(route::path::special_t::UNREACH);
} else if (p.is_prohibit) {
return route::path(route::path::special_t::PROHIBIT);
} else {
boost::asio::ip::address address =
from_bytes(nh_proto_t::IPV6 == nhp, p.next_hop);
std::shared_ptr<interface> itf = interface::find(p.sw_if_index);
if (itf) {
if (p.is_dvr) {
return route::path(*itf, nhp, route::path::flags_t::DVR, p.weight,
p.preference);
} else {
return route::path(address, *itf, p.weight, p.preference);
}
} else {
std::shared_ptr<route_domain> rd = route_domain::find(p.table_id);
if (rd) {
return route::path(*rd, address, p.weight, p.preference);
}
}
}
VOM_LOG(log_level_t::ERROR) << "cannot decode: ";
return route::path(route::path::special_t::DROP);
}
};
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "mozilla")
* End:
*/
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIFalTextComponent.cpp
created: Sun Jun 19 2005
author: Paul D Turner <[email protected]>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/falagard/TextComponent.h"
#include "CEGUI/falagard/XMLEnumHelper.h"
#include "CEGUI/FontManager.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/PropertyHelper.h"
#include "CEGUI/Font.h"
#include "CEGUI/LeftAlignedRenderedString.h"
#include "CEGUI/RightAlignedRenderedString.h"
#include "CEGUI/CentredRenderedString.h"
#include "CEGUI/JustifiedRenderedString.h"
#include "CEGUI/RenderedStringWordWrapper.h"
#include <iostream>
#if defined (CEGUI_USE_FRIBIDI)
#include "CEGUI/FribidiVisualMapping.h"
#elif defined (CEGUI_USE_MINIBIDI)
#include "CEGUI/MinibidiVisualMapping.h"
#else
#include "CEGUI/BidiVisualMapping.h"
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
TextComponent::TextComponent() :
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping),
#else
#error "BIDI Configuration is inconsistant, check your config!"
#endif
d_bidiDataValid(false),
d_formattedRenderedString(CEGUI_NEW_AO LeftAlignedRenderedString(d_renderedString)),
d_lastHorzFormatting(HTF_LEFT_ALIGNED),
d_vertFormatting(VTF_TOP_ALIGNED),
d_horzFormatting(HTF_LEFT_ALIGNED)
{}
TextComponent::~TextComponent()
{
CEGUI_DELETE_AO d_bidiVisualMapping;
}
TextComponent::TextComponent(const TextComponent& obj) :
FalagardComponentBase(obj),
d_textLogical(obj.d_textLogical),
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping),
#endif
d_bidiDataValid(false),
d_renderedString(obj.d_renderedString),
d_formattedRenderedString(obj.d_formattedRenderedString),
d_lastHorzFormatting(obj.d_lastHorzFormatting),
d_font(obj.d_font),
d_vertFormatting(obj.d_vertFormatting),
d_horzFormatting(obj.d_horzFormatting),
d_textPropertyName(obj.d_textPropertyName),
d_fontPropertyName(obj.d_fontPropertyName)
{
}
TextComponent& TextComponent::operator=(const TextComponent& other)
{
if (this == &other)
return *this;
FalagardComponentBase::operator=(other);
d_textLogical = other.d_textLogical;
// note we do not assign the BidiVisualMapping object, we just mark our
// existing one as invalid so it's data gets regenerated next time it's
// needed.
d_bidiDataValid = false;
d_renderedString = other.d_renderedString;
d_formattedRenderedString = other.d_formattedRenderedString;
d_lastHorzFormatting = other.d_lastHorzFormatting;
d_font = other.d_font;
d_vertFormatting = other.d_vertFormatting;
d_horzFormatting = other.d_horzFormatting;
d_textPropertyName = other.d_textPropertyName;
d_fontPropertyName = other.d_fontPropertyName;
return *this;
}
const String& TextComponent::getText() const
{
return d_textLogical;
}
void TextComponent::setText(const String& text)
{
d_textLogical = text;
d_bidiDataValid = false;
}
const String& TextComponent::getFont() const
{
return d_font;
}
void TextComponent::setFont(const String& font)
{
d_font = font;
}
VerticalTextFormatting TextComponent::getVerticalFormatting(const Window& wnd) const
{
return d_vertFormatting.get(wnd);
}
void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt)
{
d_vertFormatting.set(fmt);
}
HorizontalTextFormatting TextComponent::getHorizontalFormatting(const Window& wnd) const
{
return d_horzFormatting.get(wnd);
}
void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt)
{
d_horzFormatting.set(fmt);
}
void TextComponent::setHorizontalFormattingPropertySource(
const String& property_name)
{
d_horzFormatting.setPropertySource(property_name);
}
void TextComponent::setVerticalFormattingPropertySource(
const String& property_name)
{
d_vertFormatting.setPropertySource(property_name);
}
void TextComponent::setupStringFormatter(const Window& window,
const RenderedString& rendered_string) const
{
const HorizontalTextFormatting horzFormatting = d_horzFormatting.get(window);
// no formatting change
if (horzFormatting == d_lastHorzFormatting)
{
d_formattedRenderedString->setRenderedString(rendered_string);
return;
}
d_lastHorzFormatting = horzFormatting;
switch(horzFormatting)
{
case HTF_LEFT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO LeftAlignedRenderedString(rendered_string);
break;
case HTF_CENTRE_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO CentredRenderedString(rendered_string);
break;
case HTF_RIGHT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RightAlignedRenderedString(rendered_string);
break;
case HTF_JUSTIFIED:
d_formattedRenderedString =
CEGUI_NEW_AO JustifiedRenderedString(rendered_string);
break;
case HTF_WORDWRAP_LEFT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<LeftAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_CENTRE_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<CentredRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_RIGHT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<RightAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_JUSTIFIED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<JustifiedRenderedString>(rendered_string);
break;
}
}
void TextComponent::render_impl(Window& srcWindow, Rectf& destRect, const CEGUI::ColourRect* modColours, const Rectf* clipper, bool /*clipToDisplay*/) const
{
const Font* font = getFontObject(srcWindow);
// exit if we have no font to use.
if (!font)
return;
const RenderedString* rs = &d_renderedString;
// do we fetch text from a property
if (!d_textPropertyName.empty())
{
// fetch text & do bi-directional reordering as needed
String vis;
#ifdef CEGUI_BIDI_SUPPORT
BidiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l);
#else
vis = srcWindow.getProperty(d_textPropertyName);
#endif
// parse string using parser from Window.
d_renderedString =
srcWindow.getRenderedStringParser().parse(vis, font, 0);
}
// do we use a static text string from the looknfeel
else if (!getTextVisual().empty())
// parse string using parser from Window.
d_renderedString = srcWindow.getRenderedStringParser().
parse(getTextVisual(), font, 0);
// do we have to override the font?
else if (font != srcWindow.getFont())
d_renderedString = srcWindow.getRenderedStringParser().
parse(srcWindow.getTextVisual(), font, 0);
// use ready-made RenderedString from the Window itself
else
rs = &srcWindow.getRenderedString();
setupStringFormatter(srcWindow, *rs);
d_formattedRenderedString->format(&srcWindow, destRect.getSize());
// Get total formatted height.
const float textHeight = d_formattedRenderedString->getVerticalExtent(&srcWindow);
// handle dest area adjustments for vertical formatting.
const VerticalTextFormatting vertFormatting = d_vertFormatting.get(srcWindow);
switch(vertFormatting)
{
case VTF_CENTRE_ALIGNED:
destRect.d_min.d_y += (destRect.getHeight() - textHeight) * 0.5f;
break;
case VTF_BOTTOM_ALIGNED:
destRect.d_min.d_y = destRect.d_max.d_y - textHeight;
break;
default:
// default is VTF_TOP_ALIGNED, for which we take no action.
break;
}
// calculate final colours to be used
ColourRect finalColours;
initColoursRect(srcWindow, modColours, finalColours);
// add geometry for text to the target window.
d_formattedRenderedString->draw(&srcWindow, srcWindow.getGeometryBuffer(),
destRect.getPosition(),
&finalColours, clipper);
}
const Font* TextComponent::getFontObject(const Window& window) const
{
CEGUI_TRY
{
return d_fontPropertyName.empty() ?
(d_font.empty() ? window.getFont() : &FontManager::getSingleton().get(d_font))
: &FontManager::getSingleton().get(window.getProperty(d_fontPropertyName));
}
CEGUI_CATCH (UnknownObjectException&)
{
return 0;
}
}
void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const
{
// opening tag
xml_stream.openTag("TextComponent");
// write out area
d_area.writeXMLToStream(xml_stream);
// write text element
if (!d_font.empty() && !getText().empty())
{
xml_stream.openTag("Text");
if (!d_font.empty())
xml_stream.attribute("font", d_font);
if (!getText().empty())
xml_stream.attribute("string", getText());
xml_stream.closeTag();
}
// write text property element
if (!d_textPropertyName.empty())
{
xml_stream.openTag("TextProperty")
.attribute("name", d_textPropertyName)
.closeTag();
}
// write font property element
if (!d_fontPropertyName.empty())
{
xml_stream.openTag("FontProperty")
.attribute("name", d_fontPropertyName)
.closeTag();
}
// get base class to write colours
writeColoursXML(xml_stream);
d_vertFormatting.writeXMLToStream(xml_stream);
d_horzFormatting.writeXMLToStream(xml_stream);
// closing tag
xml_stream.closeTag();
}
bool TextComponent::isTextFetchedFromProperty() const
{
return !d_textPropertyName.empty();
}
const String& TextComponent::getTextPropertySource() const
{
return d_textPropertyName;
}
void TextComponent::setTextPropertySource(const String& property)
{
d_textPropertyName = property;
}
bool TextComponent::isFontFetchedFromProperty() const
{
return !d_fontPropertyName.empty();
}
const String& TextComponent::getFontPropertySource() const
{
return d_fontPropertyName;
}
void TextComponent::setFontPropertySource(const String& property)
{
d_fontPropertyName = property;
}
const String& TextComponent::getTextVisual() const
{
// no bidi support
if (!d_bidiVisualMapping)
return d_textLogical;
if (!d_bidiDataValid)
{
d_bidiVisualMapping->updateVisual(d_textLogical);
d_bidiDataValid = true;
}
return d_bidiVisualMapping->getTextVisual();
}
float TextComponent::getHorizontalTextExtent(const Window& window) const
{
return d_formattedRenderedString->getHorizontalExtent(&window);
}
float TextComponent::getVerticalTextExtent(const Window& window) const
{
return d_formattedRenderedString->getVerticalExtent(&window);
}
bool TextComponent::handleFontRenderSizeChange(Window& window,
const Font* font) const
{
const bool res =
FalagardComponentBase::handleFontRenderSizeChange(window, font);
if (font == getFontObject(window))
{
window.invalidate();
return true;
}
return res;
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveText(const Window& wnd) const
{
if (!d_textPropertyName.empty())
return wnd.getProperty(d_textPropertyName);
else if (d_textLogical.empty())
return wnd.getText();
else
return d_textLogical;
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveVisualText(const Window& wnd) const
{
#ifndef CEGUI_BIDI_SUPPORT
return getEffectiveText(wnd);
#else
if (!d_textPropertyName.empty())
{
String visual;
BidiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
wnd.getProperty(d_textPropertyName), visual, l2v, v2l);
return visual;
}
// do we use a static text string from the looknfeel
else if (d_text.empty())
return wnd.getTextVisual();
else
getTextVisual();
#endif
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveFont(const Window& wnd) const
{
if (!d_fontPropertyName.empty())
return wnd.getProperty(d_fontPropertyName);
else if (d_font.empty())
{
if (const Font* font = wnd.getFont())
return font->getName();
else
return String();
}
else
return d_font;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>Fixed a build error in falagard/TextComponent when BIDI support is enabled<commit_after>/***********************************************************************
filename: CEGUIFalTextComponent.cpp
created: Sun Jun 19 2005
author: Paul D Turner <[email protected]>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/falagard/TextComponent.h"
#include "CEGUI/falagard/XMLEnumHelper.h"
#include "CEGUI/FontManager.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/PropertyHelper.h"
#include "CEGUI/Font.h"
#include "CEGUI/LeftAlignedRenderedString.h"
#include "CEGUI/RightAlignedRenderedString.h"
#include "CEGUI/CentredRenderedString.h"
#include "CEGUI/JustifiedRenderedString.h"
#include "CEGUI/RenderedStringWordWrapper.h"
#include <iostream>
#if defined (CEGUI_USE_FRIBIDI)
#include "CEGUI/FribidiVisualMapping.h"
#elif defined (CEGUI_USE_MINIBIDI)
#include "CEGUI/MinibidiVisualMapping.h"
#else
#include "CEGUI/BidiVisualMapping.h"
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
TextComponent::TextComponent() :
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping),
#else
#error "BIDI Configuration is inconsistant, check your config!"
#endif
d_bidiDataValid(false),
d_formattedRenderedString(CEGUI_NEW_AO LeftAlignedRenderedString(d_renderedString)),
d_lastHorzFormatting(HTF_LEFT_ALIGNED),
d_vertFormatting(VTF_TOP_ALIGNED),
d_horzFormatting(HTF_LEFT_ALIGNED)
{}
TextComponent::~TextComponent()
{
CEGUI_DELETE_AO d_bidiVisualMapping;
}
TextComponent::TextComponent(const TextComponent& obj) :
FalagardComponentBase(obj),
d_textLogical(obj.d_textLogical),
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping),
#endif
d_bidiDataValid(false),
d_renderedString(obj.d_renderedString),
d_formattedRenderedString(obj.d_formattedRenderedString),
d_lastHorzFormatting(obj.d_lastHorzFormatting),
d_font(obj.d_font),
d_vertFormatting(obj.d_vertFormatting),
d_horzFormatting(obj.d_horzFormatting),
d_textPropertyName(obj.d_textPropertyName),
d_fontPropertyName(obj.d_fontPropertyName)
{
}
TextComponent& TextComponent::operator=(const TextComponent& other)
{
if (this == &other)
return *this;
FalagardComponentBase::operator=(other);
d_textLogical = other.d_textLogical;
// note we do not assign the BidiVisualMapping object, we just mark our
// existing one as invalid so it's data gets regenerated next time it's
// needed.
d_bidiDataValid = false;
d_renderedString = other.d_renderedString;
d_formattedRenderedString = other.d_formattedRenderedString;
d_lastHorzFormatting = other.d_lastHorzFormatting;
d_font = other.d_font;
d_vertFormatting = other.d_vertFormatting;
d_horzFormatting = other.d_horzFormatting;
d_textPropertyName = other.d_textPropertyName;
d_fontPropertyName = other.d_fontPropertyName;
return *this;
}
const String& TextComponent::getText() const
{
return d_textLogical;
}
void TextComponent::setText(const String& text)
{
d_textLogical = text;
d_bidiDataValid = false;
}
const String& TextComponent::getFont() const
{
return d_font;
}
void TextComponent::setFont(const String& font)
{
d_font = font;
}
VerticalTextFormatting TextComponent::getVerticalFormatting(const Window& wnd) const
{
return d_vertFormatting.get(wnd);
}
void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt)
{
d_vertFormatting.set(fmt);
}
HorizontalTextFormatting TextComponent::getHorizontalFormatting(const Window& wnd) const
{
return d_horzFormatting.get(wnd);
}
void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt)
{
d_horzFormatting.set(fmt);
}
void TextComponent::setHorizontalFormattingPropertySource(
const String& property_name)
{
d_horzFormatting.setPropertySource(property_name);
}
void TextComponent::setVerticalFormattingPropertySource(
const String& property_name)
{
d_vertFormatting.setPropertySource(property_name);
}
void TextComponent::setupStringFormatter(const Window& window,
const RenderedString& rendered_string) const
{
const HorizontalTextFormatting horzFormatting = d_horzFormatting.get(window);
// no formatting change
if (horzFormatting == d_lastHorzFormatting)
{
d_formattedRenderedString->setRenderedString(rendered_string);
return;
}
d_lastHorzFormatting = horzFormatting;
switch(horzFormatting)
{
case HTF_LEFT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO LeftAlignedRenderedString(rendered_string);
break;
case HTF_CENTRE_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO CentredRenderedString(rendered_string);
break;
case HTF_RIGHT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RightAlignedRenderedString(rendered_string);
break;
case HTF_JUSTIFIED:
d_formattedRenderedString =
CEGUI_NEW_AO JustifiedRenderedString(rendered_string);
break;
case HTF_WORDWRAP_LEFT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<LeftAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_CENTRE_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<CentredRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_RIGHT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<RightAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_JUSTIFIED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<JustifiedRenderedString>(rendered_string);
break;
}
}
void TextComponent::render_impl(Window& srcWindow, Rectf& destRect, const CEGUI::ColourRect* modColours, const Rectf* clipper, bool /*clipToDisplay*/) const
{
const Font* font = getFontObject(srcWindow);
// exit if we have no font to use.
if (!font)
return;
const RenderedString* rs = &d_renderedString;
// do we fetch text from a property
if (!d_textPropertyName.empty())
{
// fetch text & do bi-directional reordering as needed
String vis;
#ifdef CEGUI_BIDI_SUPPORT
BidiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l);
#else
vis = srcWindow.getProperty(d_textPropertyName);
#endif
// parse string using parser from Window.
d_renderedString =
srcWindow.getRenderedStringParser().parse(vis, font, 0);
}
// do we use a static text string from the looknfeel
else if (!getTextVisual().empty())
// parse string using parser from Window.
d_renderedString = srcWindow.getRenderedStringParser().
parse(getTextVisual(), font, 0);
// do we have to override the font?
else if (font != srcWindow.getFont())
d_renderedString = srcWindow.getRenderedStringParser().
parse(srcWindow.getTextVisual(), font, 0);
// use ready-made RenderedString from the Window itself
else
rs = &srcWindow.getRenderedString();
setupStringFormatter(srcWindow, *rs);
d_formattedRenderedString->format(&srcWindow, destRect.getSize());
// Get total formatted height.
const float textHeight = d_formattedRenderedString->getVerticalExtent(&srcWindow);
// handle dest area adjustments for vertical formatting.
const VerticalTextFormatting vertFormatting = d_vertFormatting.get(srcWindow);
switch(vertFormatting)
{
case VTF_CENTRE_ALIGNED:
destRect.d_min.d_y += (destRect.getHeight() - textHeight) * 0.5f;
break;
case VTF_BOTTOM_ALIGNED:
destRect.d_min.d_y = destRect.d_max.d_y - textHeight;
break;
default:
// default is VTF_TOP_ALIGNED, for which we take no action.
break;
}
// calculate final colours to be used
ColourRect finalColours;
initColoursRect(srcWindow, modColours, finalColours);
// add geometry for text to the target window.
d_formattedRenderedString->draw(&srcWindow, srcWindow.getGeometryBuffer(),
destRect.getPosition(),
&finalColours, clipper);
}
const Font* TextComponent::getFontObject(const Window& window) const
{
CEGUI_TRY
{
return d_fontPropertyName.empty() ?
(d_font.empty() ? window.getFont() : &FontManager::getSingleton().get(d_font))
: &FontManager::getSingleton().get(window.getProperty(d_fontPropertyName));
}
CEGUI_CATCH (UnknownObjectException&)
{
return 0;
}
}
void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const
{
// opening tag
xml_stream.openTag("TextComponent");
// write out area
d_area.writeXMLToStream(xml_stream);
// write text element
if (!d_font.empty() && !getText().empty())
{
xml_stream.openTag("Text");
if (!d_font.empty())
xml_stream.attribute("font", d_font);
if (!getText().empty())
xml_stream.attribute("string", getText());
xml_stream.closeTag();
}
// write text property element
if (!d_textPropertyName.empty())
{
xml_stream.openTag("TextProperty")
.attribute("name", d_textPropertyName)
.closeTag();
}
// write font property element
if (!d_fontPropertyName.empty())
{
xml_stream.openTag("FontProperty")
.attribute("name", d_fontPropertyName)
.closeTag();
}
// get base class to write colours
writeColoursXML(xml_stream);
d_vertFormatting.writeXMLToStream(xml_stream);
d_horzFormatting.writeXMLToStream(xml_stream);
// closing tag
xml_stream.closeTag();
}
bool TextComponent::isTextFetchedFromProperty() const
{
return !d_textPropertyName.empty();
}
const String& TextComponent::getTextPropertySource() const
{
return d_textPropertyName;
}
void TextComponent::setTextPropertySource(const String& property)
{
d_textPropertyName = property;
}
bool TextComponent::isFontFetchedFromProperty() const
{
return !d_fontPropertyName.empty();
}
const String& TextComponent::getFontPropertySource() const
{
return d_fontPropertyName;
}
void TextComponent::setFontPropertySource(const String& property)
{
d_fontPropertyName = property;
}
const String& TextComponent::getTextVisual() const
{
// no bidi support
if (!d_bidiVisualMapping)
return d_textLogical;
if (!d_bidiDataValid)
{
d_bidiVisualMapping->updateVisual(d_textLogical);
d_bidiDataValid = true;
}
return d_bidiVisualMapping->getTextVisual();
}
float TextComponent::getHorizontalTextExtent(const Window& window) const
{
return d_formattedRenderedString->getHorizontalExtent(&window);
}
float TextComponent::getVerticalTextExtent(const Window& window) const
{
return d_formattedRenderedString->getVerticalExtent(&window);
}
bool TextComponent::handleFontRenderSizeChange(Window& window,
const Font* font) const
{
const bool res =
FalagardComponentBase::handleFontRenderSizeChange(window, font);
if (font == getFontObject(window))
{
window.invalidate();
return true;
}
return res;
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveText(const Window& wnd) const
{
if (!d_textPropertyName.empty())
return wnd.getProperty(d_textPropertyName);
else if (d_textLogical.empty())
return wnd.getText();
else
return d_textLogical;
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveVisualText(const Window& wnd) const
{
#ifndef CEGUI_BIDI_SUPPORT
return getEffectiveText(wnd);
#else
if (!d_textPropertyName.empty())
{
String visual;
BidiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
wnd.getProperty(d_textPropertyName), visual, l2v, v2l);
return visual;
}
// do we use a static text string from the looknfeel
else if (d_textLogical.empty())
return wnd.getTextVisual();
else
getTextVisual();
#endif
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveFont(const Window& wnd) const
{
if (!d_fontPropertyName.empty())
return wnd.getProperty(d_fontPropertyName);
else if (d_font.empty())
{
if (const Font* font = wnd.getFont())
return font->getName();
else
return String();
}
else
return d_font;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
#define OSVR_DEV_VERBOSE_DISABLE
// Internal Includes
#include <osvr/PluginHost/RegistrationContext.h>
#include <osvr/PluginHost/SearchPath.h>
#include "PluginSpecificRegistrationContextImpl.h"
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
#include <libfunctionality/LoadPlugin.h>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/algorithm/string/predicate.hpp>
// Standard includes
#include <algorithm>
#include <iterator>
namespace osvr {
namespace pluginhost {
RegistrationContext::RegistrationContext() {}
RegistrationContext::~RegistrationContext() {
// Reset the plugins in reverse order.
for (auto &ptr : m_regMap | boost::adaptors::map_values |
boost::adaptors::reversed) {
ptr.reset();
}
}
static inline bool tryLoadingPlugin(libfunc::PluginHandle & plugin, std::string const& name, OSVR_PluginRegContext ctx, bool shouldRethrow = false) {
OSVR_DEV_VERBOSE("Trying to load a plugin with the name " << name);
try {
plugin = libfunc::loadPluginByName(
name, ctx);
return true;
} catch (std::runtime_error const&e) {
OSVR_DEV_VERBOSE("Failed: " << e.what());
if (shouldRethrow) {
throw;
}
return false;
}
catch (...) {
throw;
}
}
void RegistrationContext::loadPlugin(std::string const &pluginName) {
const std::string pluginPathName = pluginhost::findPlugin(pluginName);
if (pluginPathName.empty()) {
throw std::runtime_error("Could not find plugin named " +
pluginName);
}
const std::string pluginPathNameNoExt = (boost::filesystem::path(pluginPathName).parent_path() / boost::filesystem::path(pluginPathName).stem()).generic_string();
PluginRegPtr pluginReg(
PluginSpecificRegistrationContext::create(pluginName));
pluginReg->setParent(*this);
libfunc::PluginHandle plugin;
auto ctx = pluginReg->extractOpaquePointer();
bool success = tryLoadingPlugin(plugin, pluginPathName, ctx) || tryLoadingPlugin(plugin, pluginPathNameNoExt, ctx, true);
if (!success) {
throw std::runtime_error("Unusual error occurred trying to load plugin named " +
pluginName);
}
pluginReg->takePluginHandle(plugin);
adoptPluginRegistrationContext(pluginReg);
}
void RegistrationContext::loadPlugins() {
// Build a list of all the plugins we can find
auto pluginPaths = pluginhost::getPluginSearchPath();
for (const auto &pluginPath : pluginPaths) {
OSVR_DEV_VERBOSE("Searching for plugins in " << pluginPath << "...");
}
auto pluginPathNames = pluginhost::getAllFilesWithExt(pluginPaths, OSVR_PLUGIN_EXTENSION);
// Load all of the non-.manualload plugins
for (const auto &plugin : pluginPathNames) {
OSVR_DEV_VERBOSE("Examining plugin '" << plugin << "'...");
const std::string pluginBaseName = boost::filesystem::path(plugin).filename().stem().generic_string();
if (boost::iends_with(pluginBaseName, OSVR_PLUGIN_IGNORE_SUFFIX)) {
OSVR_DEV_VERBOSE("Ignoring manual-load plugin: " << pluginBaseName);
continue;
}
try {
loadPlugin(pluginBaseName);
OSVR_DEV_VERBOSE("Successfully loaded plugin: " << pluginBaseName);
} catch (const std::exception &e) {
OSVR_DEV_VERBOSE("Failed to load plugin " << pluginBaseName << ": " << e.what());
} catch (...) {
OSVR_DEV_VERBOSE("Failed to load plugin " << pluginBaseName << ": Unknown error.");
}
}
}
void RegistrationContext::adoptPluginRegistrationContext(PluginRegPtr ctx) {
/// This set parent might be a duplicate, but won't be if the plugin reg
/// ctx is not created by loadPlugin above.
ctx->setParent(*this);
m_regMap.insert(std::make_pair(ctx->getName(), ctx));
OSVR_DEV_VERBOSE("RegistrationContext:\t"
"Adopted registration context for "
<< ctx->getName());
}
void RegistrationContext::triggerHardwareDetect() {
for (auto &pluginPtr : m_regMap | boost::adaptors::map_values) {
pluginPtr->triggerHardwareDetectCallbacks();
}
}
void
RegistrationContext::instantiateDriver(const std::string &pluginName,
const std::string &driverName,
const std::string ¶ms) const {
auto pluginIt = m_regMap.find(pluginName);
if (pluginIt == end(m_regMap)) {
throw std::runtime_error("Could not find plugin named " +
pluginName);
}
pluginIt->second->instantiateDriver(driverName, params);
}
util::AnyMap &RegistrationContext::data() { return m_data; }
util::AnyMap const &RegistrationContext::data() const { return m_data; }
} // namespace pluginhost
} // namespace osvr
<commit_msg>Remove extra verbosity<commit_after>/** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
#define OSVR_DEV_VERBOSE_DISABLE
// Internal Includes
#include <osvr/PluginHost/RegistrationContext.h>
#include <osvr/PluginHost/SearchPath.h>
#include "PluginSpecificRegistrationContextImpl.h"
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
#include <libfunctionality/LoadPlugin.h>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/algorithm/string/predicate.hpp>
// Standard includes
#include <algorithm>
#include <iterator>
namespace osvr {
namespace pluginhost {
RegistrationContext::RegistrationContext() {}
RegistrationContext::~RegistrationContext() {
// Reset the plugins in reverse order.
for (auto &ptr : m_regMap | boost::adaptors::map_values |
boost::adaptors::reversed) {
ptr.reset();
}
}
static inline bool tryLoadingPlugin(libfunc::PluginHandle & plugin, std::string const& name, OSVR_PluginRegContext ctx, bool shouldRethrow = false) {
OSVR_DEV_VERBOSE("Trying to load a plugin with the name " << name);
try {
plugin = libfunc::loadPluginByName(
name, ctx);
return true;
} catch (std::runtime_error const&e) {
OSVR_DEV_VERBOSE("Failed: " << e.what());
if (shouldRethrow) {
throw;
}
return false;
}
catch (...) {
throw;
}
}
void RegistrationContext::loadPlugin(std::string const &pluginName) {
const std::string pluginPathName = pluginhost::findPlugin(pluginName);
if (pluginPathName.empty()) {
throw std::runtime_error("Could not find plugin named " +
pluginName);
}
const std::string pluginPathNameNoExt = (boost::filesystem::path(pluginPathName).parent_path() / boost::filesystem::path(pluginPathName).stem()).generic_string();
PluginRegPtr pluginReg(
PluginSpecificRegistrationContext::create(pluginName));
pluginReg->setParent(*this);
libfunc::PluginHandle plugin;
auto ctx = pluginReg->extractOpaquePointer();
bool success = tryLoadingPlugin(plugin, pluginPathName, ctx) || tryLoadingPlugin(plugin, pluginPathNameNoExt, ctx, true);
if (!success) {
throw std::runtime_error("Unusual error occurred trying to load plugin named " +
pluginName);
}
pluginReg->takePluginHandle(plugin);
adoptPluginRegistrationContext(pluginReg);
}
void RegistrationContext::loadPlugins() {
// Build a list of all the plugins we can find
auto pluginPaths = pluginhost::getPluginSearchPath();
auto pluginPathNames = pluginhost::getAllFilesWithExt(pluginPaths, OSVR_PLUGIN_EXTENSION);
// Load all of the non-.manualload plugins
for (const auto &plugin : pluginPathNames) {
OSVR_DEV_VERBOSE("Examining plugin '" << plugin << "'...");
const std::string pluginBaseName = boost::filesystem::path(plugin).filename().stem().generic_string();
if (boost::iends_with(pluginBaseName, OSVR_PLUGIN_IGNORE_SUFFIX)) {
OSVR_DEV_VERBOSE("Ignoring manual-load plugin: " << pluginBaseName);
continue;
}
try {
loadPlugin(pluginBaseName);
OSVR_DEV_VERBOSE("Successfully loaded plugin: " << pluginBaseName);
} catch (const std::exception &e) {
OSVR_DEV_VERBOSE("Failed to load plugin " << pluginBaseName << ": " << e.what());
} catch (...) {
OSVR_DEV_VERBOSE("Failed to load plugin " << pluginBaseName << ": Unknown error.");
}
}
}
void RegistrationContext::adoptPluginRegistrationContext(PluginRegPtr ctx) {
/// This set parent might be a duplicate, but won't be if the plugin reg
/// ctx is not created by loadPlugin above.
ctx->setParent(*this);
m_regMap.insert(std::make_pair(ctx->getName(), ctx));
}
void RegistrationContext::triggerHardwareDetect() {
for (auto &pluginPtr : m_regMap | boost::adaptors::map_values) {
pluginPtr->triggerHardwareDetectCallbacks();
}
}
void
RegistrationContext::instantiateDriver(const std::string &pluginName,
const std::string &driverName,
const std::string ¶ms) const {
auto pluginIt = m_regMap.find(pluginName);
if (pluginIt == end(m_regMap)) {
throw std::runtime_error("Could not find plugin named " +
pluginName);
}
pluginIt->second->instantiateDriver(driverName, params);
}
util::AnyMap &RegistrationContext::data() { return m_data; }
util::AnyMap const &RegistrationContext::data() const { return m_data; }
} // namespace pluginhost
} // namespace osvr
<|endoftext|> |
<commit_before>#include "lxqtfiledialoghelper.h"
#include <libfm-qt/libfmqt.h>
#include <libfm-qt/filedialog.h>
#include <QWindow>
#include <QMimeDatabase>
#include <QDebug>
#include <QTimer>
#include <QSettings>
#include <memory>
static std::unique_ptr<Fm::LibFmQt> libfmQtContext_;
LXQtFileDialogHelper::LXQtFileDialogHelper() {
if(!libfmQtContext_) {
// initialize libfm-qt only once
libfmQtContext_ = std::unique_ptr<Fm::LibFmQt>{new Fm::LibFmQt()};
}
// can only be used after libfm-qt initialization
dlg_ = std::unique_ptr<Fm::FileDialog>(new Fm::FileDialog());
connect(dlg_.get(), &Fm::FileDialog::accepted, [this]() {
saveSettings();
accept();
});
connect(dlg_.get(), &Fm::FileDialog::rejected, [this]() {
saveSettings();
reject();
});
connect(dlg_.get(), &Fm::FileDialog::fileSelected, this, &LXQtFileDialogHelper::fileSelected);
connect(dlg_.get(), &Fm::FileDialog::filesSelected, this, &LXQtFileDialogHelper::filesSelected);
connect(dlg_.get(), &Fm::FileDialog::currentChanged, this, &LXQtFileDialogHelper::currentChanged);
connect(dlg_.get(), &Fm::FileDialog::directoryEntered, this, &LXQtFileDialogHelper::directoryEntered);
connect(dlg_.get(), &Fm::FileDialog::filterSelected, this, &LXQtFileDialogHelper::filterSelected);
}
LXQtFileDialogHelper::~LXQtFileDialogHelper() {
}
void LXQtFileDialogHelper::exec() {
dlg_->exec();
}
bool LXQtFileDialogHelper::show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow* parent) {
dlg_->setAttribute(Qt::WA_NativeWindow, true); // without this, sometimes windowHandle() will return nullptr
dlg_->setWindowFlags(windowFlags);
dlg_->setWindowModality(windowModality);
// Reference: KDE implementation
// https://github.com/KDE/plasma-integration/blob/master/src/platformtheme/kdeplatformfiledialoghelper.cpp
dlg_->windowHandle()->setTransientParent(parent);
loadSettings();
// central positioning with respect to the parent window
if(parent && parent->isVisible()) {
dlg_->move(parent->x() + (parent->width() - dlg_->width()) / 2,
parent->y() + (parent->height() - dlg_->height()) / 2);
}
applyOptions();
// NOTE: the timer here is required as a workaround borrowed from KDE. Without this, the dialog UI will be blocked.
// QFileDialog calls our platform plugin to show our own native file dialog instead of showing its widget.
// However, it still creates a hidden dialog internally, and then make it modal.
// So user input from all other windows that are not the children of the QFileDialog widget will be blocked.
// This includes our own dialog. After the return of this show() method, QFileDialog creates its own window and
// then make it modal, which blocks our UI. The timer schedule a delayed popup of our file dialog, so we can
// show again after QFileDialog and override the modal state. Then our UI can be unblocked.
QTimer::singleShot(0, dlg_.get(), &QDialog::show);
dlg_->setFocus();
return true;
}
void LXQtFileDialogHelper::hide() {
dlg_->hide();
}
bool LXQtFileDialogHelper::defaultNameFilterDisables() const {
return false;
}
void LXQtFileDialogHelper::setDirectory(const QUrl& directory) {
dlg_->setDirectory(directory);
}
QUrl LXQtFileDialogHelper::directory() const {
return dlg_->directory();
}
void LXQtFileDialogHelper::selectFile(const QUrl& filename) {
dlg_->selectFile(filename);
}
QList<QUrl> LXQtFileDialogHelper::selectedFiles() const {
return dlg_->selectedFiles();
}
void LXQtFileDialogHelper::setFilter() {
// FIXME: what's this?
// The gtk+ 3 file dialog helper in Qt5 update options in this method.
applyOptions();
}
void LXQtFileDialogHelper::selectNameFilter(const QString& filter) {
dlg_->selectNameFilter(filter);
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
QString LXQtFileDialogHelper::selectedMimeTypeFilter() const {
const auto mimeTypeFromFilter = QMimeDatabase().mimeTypeForName(dlg_->selectedNameFilter());
if(mimeTypeFromFilter.isValid()) {
return mimeTypeFromFilter.name();
}
QList<QUrl> sel = dlg_->selectedFiles();
if(sel.isEmpty()) {
return QString();
}
return QMimeDatabase().mimeTypeForUrl(sel.at(0)).name();
}
void LXQtFileDialogHelper::selectMimeTypeFilter(const QString& filter) {
dlg_->selectNameFilter(filter);
}
#endif
QString LXQtFileDialogHelper::selectedNameFilter() const {
return dlg_->selectedNameFilter();
}
bool LXQtFileDialogHelper::isSupportedUrl(const QUrl& url) const {
return dlg_->isSupportedUrl(url);
}
void LXQtFileDialogHelper::applyOptions() {
auto& opt = options();
// set title
if(opt->windowTitle().isEmpty()) {
dlg_->setWindowTitle(opt->acceptMode() == QFileDialogOptions::AcceptOpen ? tr("Open File")
: tr("Save File"));
}
else {
dlg_->setWindowTitle(opt->windowTitle());
}
dlg_->setFilter(opt->filter());
dlg_->setViewMode(opt->viewMode() == QFileDialogOptions::Detail ? Fm::FolderView::DetailedListMode
: Fm::FolderView::CompactMode);
dlg_->setFileMode(QFileDialog::FileMode(opt->fileMode()));
dlg_->setAcceptMode(QFileDialog::AcceptMode(opt->acceptMode())); // also sets a default label for accept button
// bool useDefaultNameFilters() const;
dlg_->setNameFilters(opt->nameFilters());
if(!opt->mimeTypeFilters().empty()) {
dlg_->setMimeTypeFilters(opt->mimeTypeFilters());
}
dlg_->setDefaultSuffix(opt->defaultSuffix());
// QStringList history() const;
// explicitly set labels
for(int i = 0; i < QFileDialogOptions::DialogLabelCount; ++i) {
auto label = static_cast<QFileDialogOptions::DialogLabel>(i);
if(opt->isLabelExplicitlySet(label)) {
dlg_->setLabelText(static_cast<QFileDialog::DialogLabel>(label), opt->labelText(label));
}
}
auto url = opt->initialDirectory();
if(url.isValid()) {
dlg_->setDirectory(url);
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
auto filter = opt->initiallySelectedMimeTypeFilter();
if(!filter.isEmpty()) {
selectMimeTypeFilter(filter);
}
else {
filter = opt->initiallySelectedNameFilter();
if(!filter.isEmpty()) {
selectNameFilter(opt->initiallySelectedNameFilter());
}
}
#else
filter = opt->initiallySelectedNameFilter();
if(!filter.isEmpty()) {
selectNameFilter(filter);
}
#endif
auto selectedFiles = opt->initiallySelectedFiles();
for(const auto& selectedFile: selectedFiles) {
selectFile(selectedFile);
}
// QStringList supportedSchemes() const;
}
void LXQtFileDialogHelper::loadSettings() {
QSettings settings(QSettings::UserScope, "lxqt", "filedialog");
settings.beginGroup ("Sizes");
dlg_->resize(settings.value("WindowSize", QSize(700, 500)).toSize());
dlg_->setSplitterPos(settings.value("SplitterPos", 200).toInt());
settings.endGroup();
}
void LXQtFileDialogHelper::saveSettings() {
QSettings settings(QSettings::UserScope, "lxqt", "filedialog");
settings.beginGroup ("Sizes");
QSize windowSize = dlg_->size();
if(settings.value("WindowSize") != windowSize) { // no redundant write
settings.setValue("WindowSize", windowSize);
}
int splitterPos = dlg_->splitterPos();
if(settings.value("SplitterPos") != splitterPos) {
settings.setValue("SplitterPos", splitterPos);
}
settings.endGroup();
}
/*
FileDialogPlugin::FileDialogPlugin() {
}
QPlatformFileDialogHelper *FileDialogPlugin::createHelper() {
return new LXQtFileDialogHelper();
}
*/
<commit_msg>Use mime functions added by @PCMan<commit_after>#include "lxqtfiledialoghelper.h"
#include <libfm-qt/libfmqt.h>
#include <libfm-qt/filedialog.h>
#include <QWindow>
#include <QDebug>
#include <QTimer>
#include <QSettings>
#include <memory>
static std::unique_ptr<Fm::LibFmQt> libfmQtContext_;
LXQtFileDialogHelper::LXQtFileDialogHelper() {
if(!libfmQtContext_) {
// initialize libfm-qt only once
libfmQtContext_ = std::unique_ptr<Fm::LibFmQt>{new Fm::LibFmQt()};
}
// can only be used after libfm-qt initialization
dlg_ = std::unique_ptr<Fm::FileDialog>(new Fm::FileDialog());
connect(dlg_.get(), &Fm::FileDialog::accepted, [this]() {
saveSettings();
accept();
});
connect(dlg_.get(), &Fm::FileDialog::rejected, [this]() {
saveSettings();
reject();
});
connect(dlg_.get(), &Fm::FileDialog::fileSelected, this, &LXQtFileDialogHelper::fileSelected);
connect(dlg_.get(), &Fm::FileDialog::filesSelected, this, &LXQtFileDialogHelper::filesSelected);
connect(dlg_.get(), &Fm::FileDialog::currentChanged, this, &LXQtFileDialogHelper::currentChanged);
connect(dlg_.get(), &Fm::FileDialog::directoryEntered, this, &LXQtFileDialogHelper::directoryEntered);
connect(dlg_.get(), &Fm::FileDialog::filterSelected, this, &LXQtFileDialogHelper::filterSelected);
}
LXQtFileDialogHelper::~LXQtFileDialogHelper() {
}
void LXQtFileDialogHelper::exec() {
dlg_->exec();
}
bool LXQtFileDialogHelper::show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow* parent) {
dlg_->setAttribute(Qt::WA_NativeWindow, true); // without this, sometimes windowHandle() will return nullptr
dlg_->setWindowFlags(windowFlags);
dlg_->setWindowModality(windowModality);
// Reference: KDE implementation
// https://github.com/KDE/plasma-integration/blob/master/src/platformtheme/kdeplatformfiledialoghelper.cpp
dlg_->windowHandle()->setTransientParent(parent);
loadSettings();
// central positioning with respect to the parent window
if(parent && parent->isVisible()) {
dlg_->move(parent->x() + (parent->width() - dlg_->width()) / 2,
parent->y() + (parent->height() - dlg_->height()) / 2);
}
applyOptions();
// NOTE: the timer here is required as a workaround borrowed from KDE. Without this, the dialog UI will be blocked.
// QFileDialog calls our platform plugin to show our own native file dialog instead of showing its widget.
// However, it still creates a hidden dialog internally, and then make it modal.
// So user input from all other windows that are not the children of the QFileDialog widget will be blocked.
// This includes our own dialog. After the return of this show() method, QFileDialog creates its own window and
// then make it modal, which blocks our UI. The timer schedule a delayed popup of our file dialog, so we can
// show again after QFileDialog and override the modal state. Then our UI can be unblocked.
QTimer::singleShot(0, dlg_.get(), &QDialog::show);
dlg_->setFocus();
return true;
}
void LXQtFileDialogHelper::hide() {
dlg_->hide();
}
bool LXQtFileDialogHelper::defaultNameFilterDisables() const {
return false;
}
void LXQtFileDialogHelper::setDirectory(const QUrl& directory) {
dlg_->setDirectory(directory);
}
QUrl LXQtFileDialogHelper::directory() const {
return dlg_->directory();
}
void LXQtFileDialogHelper::selectFile(const QUrl& filename) {
dlg_->selectFile(filename);
}
QList<QUrl> LXQtFileDialogHelper::selectedFiles() const {
return dlg_->selectedFiles();
}
void LXQtFileDialogHelper::setFilter() {
// FIXME: what's this?
// The gtk+ 3 file dialog helper in Qt5 update options in this method.
applyOptions();
}
void LXQtFileDialogHelper::selectNameFilter(const QString& filter) {
dlg_->selectNameFilter(filter);
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
QString LXQtFileDialogHelper::selectedMimeTypeFilter() const {
return dlg_->selectedMimeTypeFilter();
}
void LXQtFileDialogHelper::selectMimeTypeFilter(const QString& filter) {
dlg_->selectMimeTypeFilter(filter);
}
#endif
QString LXQtFileDialogHelper::selectedNameFilter() const {
return dlg_->selectedNameFilter();
}
bool LXQtFileDialogHelper::isSupportedUrl(const QUrl& url) const {
return dlg_->isSupportedUrl(url);
}
void LXQtFileDialogHelper::applyOptions() {
auto& opt = options();
// set title
if(opt->windowTitle().isEmpty()) {
dlg_->setWindowTitle(opt->acceptMode() == QFileDialogOptions::AcceptOpen ? tr("Open File")
: tr("Save File"));
}
else {
dlg_->setWindowTitle(opt->windowTitle());
}
dlg_->setFilter(opt->filter());
dlg_->setViewMode(opt->viewMode() == QFileDialogOptions::Detail ? Fm::FolderView::DetailedListMode
: Fm::FolderView::CompactMode);
dlg_->setFileMode(QFileDialog::FileMode(opt->fileMode()));
dlg_->setAcceptMode(QFileDialog::AcceptMode(opt->acceptMode())); // also sets a default label for accept button
// bool useDefaultNameFilters() const;
dlg_->setNameFilters(opt->nameFilters());
if(!opt->mimeTypeFilters().empty()) {
dlg_->setMimeTypeFilters(opt->mimeTypeFilters());
}
dlg_->setDefaultSuffix(opt->defaultSuffix());
// QStringList history() const;
// explicitly set labels
for(int i = 0; i < QFileDialogOptions::DialogLabelCount; ++i) {
auto label = static_cast<QFileDialogOptions::DialogLabel>(i);
if(opt->isLabelExplicitlySet(label)) {
dlg_->setLabelText(static_cast<QFileDialog::DialogLabel>(label), opt->labelText(label));
}
}
auto url = opt->initialDirectory();
if(url.isValid()) {
dlg_->setDirectory(url);
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
auto filter = opt->initiallySelectedMimeTypeFilter();
if(!filter.isEmpty()) {
selectMimeTypeFilter(filter);
}
else {
filter = opt->initiallySelectedNameFilter();
if(!filter.isEmpty()) {
selectNameFilter(opt->initiallySelectedNameFilter());
}
}
#else
filter = opt->initiallySelectedNameFilter();
if(!filter.isEmpty()) {
selectNameFilter(filter);
}
#endif
auto selectedFiles = opt->initiallySelectedFiles();
for(const auto& selectedFile: selectedFiles) {
selectFile(selectedFile);
}
// QStringList supportedSchemes() const;
}
void LXQtFileDialogHelper::loadSettings() {
QSettings settings(QSettings::UserScope, "lxqt", "filedialog");
settings.beginGroup ("Sizes");
dlg_->resize(settings.value("WindowSize", QSize(700, 500)).toSize());
dlg_->setSplitterPos(settings.value("SplitterPos", 200).toInt());
settings.endGroup();
}
void LXQtFileDialogHelper::saveSettings() {
QSettings settings(QSettings::UserScope, "lxqt", "filedialog");
settings.beginGroup ("Sizes");
QSize windowSize = dlg_->size();
if(settings.value("WindowSize") != windowSize) { // no redundant write
settings.setValue("WindowSize", windowSize);
}
int splitterPos = dlg_->splitterPos();
if(settings.value("SplitterPos") != splitterPos) {
settings.setValue("SplitterPos", splitterPos);
}
settings.endGroup();
}
/*
FileDialogPlugin::FileDialogPlugin() {
}
QPlatformFileDialogHelper *FileDialogPlugin::createHelper() {
return new LXQtFileDialogHelper();
}
*/
<|endoftext|> |
<commit_before><commit_msg>coverity#1309069 Uncaught exception<commit_after><|endoftext|> |
<commit_before><commit_msg>coverity#738654 Uninitialized scalar field<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2016 CodiLime
*
* 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 "db/handle.h"
#include "db/object.h"
#include "db/getter.h"
#include "db/universe.h"
#include "dbif/error.h"
#include "dbif/info.h"
#include "dbif/method.h"
namespace veles {
namespace db {
void LocalObject::getInfo(InfoGetter *getter, PInfoRequest req, bool once) {
if (req.dynamicCast<dbif::ChildrenRequest>()) {
children_reply(getter);
if (!once) {
children_watchers_.insert(getter);
auto shared_this = sharedFromThis();
QObject::connect(getter, &QObject::destroyed, [shared_this, getter] () {
shared_this->remove_children_watcher(getter);
});
}
} else if (req.dynamicCast<dbif::DescriptionRequest>()) {
description_reply(getter);
if (!once) {
description_watchers_.insert(getter);
auto shared_this = sharedFromThis();
QObject::connect(getter, &QObject::destroyed, [shared_this, getter] () {
shared_this->remove_description_watcher(getter);
});
}
} else {
getter->sendError<dbif::ObjectInvalidRequestError>();
}
}
void LocalObject::remove_description_watcher(InfoGetter * getter) {
description_watchers_.remove(getter);
}
void LocalObject::remove_children_watcher(InfoGetter * getter) {
children_watchers_.remove(getter);
}
void LocalObject::runMethod(MethodRunner *runner, PMethodRequest req) {
if (req.dynamicCast<dbif::DeleteRequest>()) {
kill();
runner->sendResult<dbif::NullReply>();
} else if (auto nreq = req.dynamicCast<dbif::SetNameRequest>()) {
name_ = nreq->name;
description_updated();
runner->sendResult<dbif::NullReply>();
} else if (auto creq = req.dynamicCast<dbif::SetCommentRequest>()) {
comment_ = creq->comment;
description_updated();
runner->sendResult<dbif::NullReply>();
} else {
runner->sendError<dbif::ObjectInvalidRequestError>();
}
}
void LocalObject::addChild(PLocalObject obj) {
children_.insert(obj);
children_updated();
}
void LocalObject::delChild(PLocalObject obj) {
children_.remove(obj);
children_updated();
}
void LocalObject::children_reply(InfoGetter *getter) {
std::vector<dbif::ObjectHandle> res;
for (PLocalObject obj : children_) {
res.push_back(db()->handle(obj));
}
getter->sendInfo<dbif::ChildrenReply>(res);
}
void LocalObject::description_reply(InfoGetter *getter) {
getter->sendInfo<dbif::DescriptionReply>(name(), comment());
}
void LocalObject::children_updated() {
for (InfoGetter *getter : children_watchers_) {
children_reply(getter);
}
}
void LocalObject::description_updated() {
for (InfoGetter *getter : description_watchers_) {
description_reply(getter);
}
}
void LocalObject::kill() {
db_ = nullptr;
killed();
QMutableSetIterator<PLocalObject> iter(children_);
while (iter.hasNext()) {
PLocalObject obj = iter.next();
obj->kill();
}
QMutableSetIterator<InfoGetter *> witer(children_watchers_);
while (witer.hasNext()) {
InfoGetter *getter = witer.next();
getter->sendError<dbif::ObjectGoneError>();
}
QMutableSetIterator<InfoGetter *> witer2(description_watchers_);
while (witer2.hasNext()) {
InfoGetter *getter = witer2.next();
getter->sendError<dbif::ObjectGoneError>();
}
Q_ASSERT(children_.empty());
}
void RootLocalObject::runMethod(MethodRunner *runner, PMethodRequest req) {
if (auto blobreq = req.dynamicCast<dbif::RootCreateFileBlobFromDataRequest>()) {
PLocalObject obj = FileBlobObject::create(this, blobreq->data, blobreq->path);
runner->sendResult<dbif::CreatedReply>(db()->handle(obj));
} else {
LocalObject::runMethod(runner, req);
}
}
void DataBlobObject::description_reply(InfoGetter *getter) {
getter->sendInfo<dbif::BlobDescriptionReply>(
name(), comment(), 0, data().size(), 8
);
}
void DataBlobObject::data_reply(InfoGetter *getter, uint64_t start, uint64_t end) {
end = std::min(end, uint64_t(data_.size()));
getter->sendInfo<dbif::BlobDataReply>(data_.data(start, end));
}
void DataBlobObject::remove_data_watcher(InfoGetter *getter) {
data_watchers_.remove(getter);
}
void DataBlobObject::getInfo(InfoGetter *getter, PInfoRequest req, bool once) {
if (auto datareq = req.dynamicCast<dbif::BlobDataRequest>()) {
if (datareq->start > data_.size()) {
getter->sendError<dbif::BlobDataInvalidRangeError>();
return;
}
data_reply(getter, datareq->start, datareq->end);
if (!once) {
data_watchers_[getter] = { datareq->start, datareq->end };
auto shared_this = sharedFromThis();
QObject::connect(getter, &QObject::destroyed, [shared_this, getter] () {
shared_this.dynamicCast<DataBlobObject>()->remove_data_watcher(getter);
});
}
} else {
LocalObject::getInfo(getter, req, once);
}
}
void DataBlobObject::runMethod(MethodRunner *runner, PMethodRequest req) {
if (auto datareq = req.dynamicCast<dbif::ChangeDataRequest>()) {
if (datareq->start >= data_.size()) {
runner->sendError<dbif::BlobDataInvalidRangeError>();
return;
}
uint64_t start = datareq->start;
uint64_t end = std::min(datareq->end, uint64_t(data_.size()));
uint64_t oldsize = end - start;
const data::BinData &newdata = datareq->data;
if (newdata.width() != data_.width()) {
runner->sendError<dbif::BlobDataInvalidWidthError>();
return;
}
if (oldsize == newdata.size()) {
data_.setData(start, end, newdata);
} else {
data::BinData merged(data_.width(), data_.size() - oldsize + newdata.size());
merged.setData(0, start, data_.data(0, start));
uint64_t newend = start + newdata.size();
merged.setData(start, newend, newdata);
merged.setData(newend, merged.size(), data_.data(end, data_.size()));
std::swap(data_, merged);
}
bool moved = newdata.size() != oldsize;
for (auto iter = data_watchers_.begin(); iter != data_watchers_.end(); iter++) {
if (iter.value().second >= start &&
(moved || iter.value().first <= end)) {
data_reply(iter.key(), iter.value().first, iter.value().second);
}
}
runner->sendResult<dbif::NullReply>();
} else if (auto chreq = req.dynamicCast<dbif::ChunkCreateRequest>()) {
PLocalObject parent_chunk;
if (chreq->parent_chunk) {
parent_chunk = chreq->parent_chunk.dynamicCast<LocalObjectHandle>()->obj();
if (!parent_chunk.dynamicCast<ChunkObject>()) {
runner->sendError<dbif::InvalidTypeError>();
return;
}
}
PLocalObject obj = ChunkObject::create(sharedFromThis(), parent_chunk,
chreq->start, chreq->end, chreq->chunk_type, chreq->name);
runner->sendResult<dbif::CreatedReply>(db()->handle(obj));
} else if (req.dynamicCast<dbif::BlobParseRequest>()) {
emit db()->parse(db()->handle(sharedFromThis()), runner->forwarder(db()->parserThread()));
} else {
LocalObject::runMethod(runner, req);
}
}
void DataBlobObject::killed() {
LocalObject::killed();
parent_->delChild(sharedFromThis());
QMutableMapIterator<InfoGetter *, std::pair<uint64_t, uint64_t>> miter(data_watchers_);
while (miter.hasNext()) {
InfoGetter *getter = miter.next().key();
getter->sendError<dbif::ObjectGoneError>();
}
}
void FileBlobObject::description_reply(InfoGetter *getter) {
getter->sendInfo<dbif::FileBlobDescriptionReply>(
name(), comment(), 0, data().size(), 8, path()
);
}
void SubBlobObject::description_reply(InfoGetter *getter) {
getter->sendInfo<dbif::SubBlobDescriptionReply>(
name(), comment(), 0, data().size(), 8, db()->handle(parent()->sharedFromThis())
);
}
void ChunkObject::children_updated() {
LocalObject::children_updated();
parse_updated();
}
void ChunkObject::parse_updated() {
calcParseReplyItems();
for (InfoGetter *getter : parse_watchers_) {
parse_reply(getter);
}
}
void ChunkObject::calcParseReplyItems() {
parseReplyItems_ = items_;
QSet<PLocalObject> chunksInItems;
for (auto &item : items_) {
if (item.type != data::ChunkDataItem::SUBCHUNK) {
continue;
}
if (auto localObjectHandle = item.ref[0].dynamicCast<LocalObjectHandle>()) {
chunksInItems.insert(localObjectHandle->obj());
}
}
for (PLocalObject obj : children()) {
if (chunksInItems.contains(obj)) {
continue;
}
if (auto chunkObj = obj.dynamicCast<ChunkObject>()) {
parseReplyItems_.push_back(
data::ChunkDataItem::subchunk(chunkObj->start_, chunkObj->end_,
chunkObj->name(), db()->handle(obj)));
} else if (auto subBlobObj = obj.dynamicCast<SubBlobObject>()) {
parseReplyItems_.push_back(
data::ChunkDataItem::subblob(subBlobObj->name(), db()->handle(obj)));
}
}
}
void ChunkObject::parse_reply(InfoGetter *getter) {
getter->sendInfo<dbif::ChunkDataReply>(parseReplyItems_);
}
void ChunkObject::description_reply(InfoGetter *getter) {
getter->sendInfo<dbif::ChunkDescriptionReply>(
name(), comment(), db()->handle(blob_), db()->handle(parent_chunk_),
start_, end_, chunk_type_
);
}
void ChunkObject::remove_parse_watcher(InfoGetter *getter) {
parse_watchers_.remove(getter);
}
void ChunkObject::getInfo(InfoGetter *getter, PInfoRequest req, bool once) {
if (auto datareq = req.dynamicCast<dbif::ChunkDataRequest>()) {
parse_reply(getter);
if (!once) {
parse_watchers_.insert(getter);
auto shared_this = sharedFromThis();
QObject::connect(getter, &QObject::destroyed, [shared_this, getter] () {
shared_this.dynamicCast<ChunkObject>()->remove_parse_watcher(getter);
});
}
} else {
LocalObject::getInfo(getter, req, once);
}
}
void ChunkObject::runMethod(MethodRunner *runner, PMethodRequest req) {
if (auto chreq = req.dynamicCast<dbif::SetChunkBoundsRequest>()) {
start_ = chreq->start;
end_ = chreq->end;
description_updated();
runner->sendResult<dbif::NullReply>();
} else if (auto preq = req.dynamicCast<dbif::SetChunkParseRequest>()) {
start_ = preq->start;
end_ = preq->end;
items_ = preq->items;
description_updated();
parse_updated();
runner->sendResult<dbif::NullReply>();
} else if (auto blobreq = req.dynamicCast<dbif::ChunkCreateSubBlobRequest>()) {
PLocalObject obj = SubBlobObject::create(this, blobreq->data, blobreq->name);
runner->sendResult<dbif::CreatedReply>(db()->handle(obj));
} else {
LocalObject::runMethod(runner, req);
}
}
void ChunkObject::killed() {
LocalObject::killed();
if (parent_chunk_)
parent_chunk_->delChild(sharedFromThis());
else
blob_->delChild(sharedFromThis());
QMutableSetIterator<InfoGetter *> witer(parse_watchers_);
while (witer.hasNext()) {
InfoGetter *getter = witer.next();
getter->sendError<dbif::ObjectGoneError>();
}
}
namespace {
class Register {
public:
Register() {
qRegisterMetaType<veles::db::PLocalObject>("veles::db::PLocalObject");
}
} _;
};
};
};
<commit_msg>crash fix<commit_after>/*
* Copyright 2016 CodiLime
*
* 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 "db/handle.h"
#include "db/object.h"
#include "db/getter.h"
#include "db/universe.h"
#include "dbif/error.h"
#include "dbif/info.h"
#include "dbif/method.h"
namespace veles {
namespace db {
void LocalObject::getInfo(InfoGetter *getter, PInfoRequest req, bool once) {
if (req.dynamicCast<dbif::ChildrenRequest>()) {
children_reply(getter);
if (!once) {
children_watchers_.insert(getter);
auto shared_this = sharedFromThis();
QObject::connect(getter, &QObject::destroyed, [shared_this, getter] () {
shared_this->remove_children_watcher(getter);
});
}
} else if (req.dynamicCast<dbif::DescriptionRequest>()) {
description_reply(getter);
if (!once) {
description_watchers_.insert(getter);
auto shared_this = sharedFromThis();
QObject::connect(getter, &QObject::destroyed, [shared_this, getter] () {
shared_this->remove_description_watcher(getter);
});
}
} else {
getter->sendError<dbif::ObjectInvalidRequestError>();
}
}
void LocalObject::remove_description_watcher(InfoGetter * getter) {
description_watchers_.remove(getter);
}
void LocalObject::remove_children_watcher(InfoGetter * getter) {
children_watchers_.remove(getter);
}
void LocalObject::runMethod(MethodRunner *runner, PMethodRequest req) {
if (req.dynamicCast<dbif::DeleteRequest>()) {
kill();
runner->sendResult<dbif::NullReply>();
} else if (auto nreq = req.dynamicCast<dbif::SetNameRequest>()) {
name_ = nreq->name;
description_updated();
runner->sendResult<dbif::NullReply>();
} else if (auto creq = req.dynamicCast<dbif::SetCommentRequest>()) {
comment_ = creq->comment;
description_updated();
runner->sendResult<dbif::NullReply>();
} else {
runner->sendError<dbif::ObjectInvalidRequestError>();
}
}
void LocalObject::addChild(PLocalObject obj) {
children_.insert(obj);
children_updated();
}
void LocalObject::delChild(PLocalObject obj) {
children_.remove(obj);
children_updated();
}
void LocalObject::children_reply(InfoGetter *getter) {
std::vector<dbif::ObjectHandle> res;
for (PLocalObject obj : children_) {
res.push_back(db()->handle(obj));
}
getter->sendInfo<dbif::ChildrenReply>(res);
}
void LocalObject::description_reply(InfoGetter *getter) {
getter->sendInfo<dbif::DescriptionReply>(name(), comment());
}
void LocalObject::children_updated() {
for (InfoGetter *getter : children_watchers_) {
children_reply(getter);
}
}
void LocalObject::description_updated() {
for (InfoGetter *getter : description_watchers_) {
description_reply(getter);
}
}
void LocalObject::kill() {
db_ = nullptr;
killed();
auto children = children_;
for (auto obj: children) {
obj->kill();
}
auto children_watchers = children_watchers_;
for (auto getter: children_watchers) {
getter->sendError<dbif::ObjectGoneError>();
}
auto description_watchers = description_watchers_;
for (auto getter: description_watchers) {
getter->sendError<dbif::ObjectGoneError>();
}
Q_ASSERT(children_.empty());
}
void RootLocalObject::runMethod(MethodRunner *runner, PMethodRequest req) {
if (auto blobreq = req.dynamicCast<dbif::RootCreateFileBlobFromDataRequest>()) {
PLocalObject obj = FileBlobObject::create(this, blobreq->data, blobreq->path);
runner->sendResult<dbif::CreatedReply>(db()->handle(obj));
} else {
LocalObject::runMethod(runner, req);
}
}
void DataBlobObject::description_reply(InfoGetter *getter) {
getter->sendInfo<dbif::BlobDescriptionReply>(
name(), comment(), 0, data().size(), 8
);
}
void DataBlobObject::data_reply(InfoGetter *getter, uint64_t start, uint64_t end) {
end = std::min(end, uint64_t(data_.size()));
getter->sendInfo<dbif::BlobDataReply>(data_.data(start, end));
}
void DataBlobObject::remove_data_watcher(InfoGetter *getter) {
data_watchers_.remove(getter);
}
void DataBlobObject::getInfo(InfoGetter *getter, PInfoRequest req, bool once) {
if (auto datareq = req.dynamicCast<dbif::BlobDataRequest>()) {
if (datareq->start > data_.size()) {
getter->sendError<dbif::BlobDataInvalidRangeError>();
return;
}
data_reply(getter, datareq->start, datareq->end);
if (!once) {
data_watchers_[getter] = { datareq->start, datareq->end };
auto shared_this = sharedFromThis();
QObject::connect(getter, &QObject::destroyed, [shared_this, getter] () {
shared_this.dynamicCast<DataBlobObject>()->remove_data_watcher(getter);
});
}
} else {
LocalObject::getInfo(getter, req, once);
}
}
void DataBlobObject::runMethod(MethodRunner *runner, PMethodRequest req) {
if (auto datareq = req.dynamicCast<dbif::ChangeDataRequest>()) {
if (datareq->start >= data_.size()) {
runner->sendError<dbif::BlobDataInvalidRangeError>();
return;
}
uint64_t start = datareq->start;
uint64_t end = std::min(datareq->end, uint64_t(data_.size()));
uint64_t oldsize = end - start;
const data::BinData &newdata = datareq->data;
if (newdata.width() != data_.width()) {
runner->sendError<dbif::BlobDataInvalidWidthError>();
return;
}
if (oldsize == newdata.size()) {
data_.setData(start, end, newdata);
} else {
data::BinData merged(data_.width(), data_.size() - oldsize + newdata.size());
merged.setData(0, start, data_.data(0, start));
uint64_t newend = start + newdata.size();
merged.setData(start, newend, newdata);
merged.setData(newend, merged.size(), data_.data(end, data_.size()));
std::swap(data_, merged);
}
bool moved = newdata.size() != oldsize;
for (auto iter = data_watchers_.begin(); iter != data_watchers_.end(); iter++) {
if (iter.value().second >= start &&
(moved || iter.value().first <= end)) {
data_reply(iter.key(), iter.value().first, iter.value().second);
}
}
runner->sendResult<dbif::NullReply>();
} else if (auto chreq = req.dynamicCast<dbif::ChunkCreateRequest>()) {
PLocalObject parent_chunk;
if (chreq->parent_chunk) {
parent_chunk = chreq->parent_chunk.dynamicCast<LocalObjectHandle>()->obj();
if (!parent_chunk.dynamicCast<ChunkObject>()) {
runner->sendError<dbif::InvalidTypeError>();
return;
}
}
PLocalObject obj = ChunkObject::create(sharedFromThis(), parent_chunk,
chreq->start, chreq->end, chreq->chunk_type, chreq->name);
runner->sendResult<dbif::CreatedReply>(db()->handle(obj));
} else if (req.dynamicCast<dbif::BlobParseRequest>()) {
emit db()->parse(db()->handle(sharedFromThis()), runner->forwarder(db()->parserThread()));
} else {
LocalObject::runMethod(runner, req);
}
}
void DataBlobObject::killed() {
LocalObject::killed();
parent_->delChild(sharedFromThis());
auto data_watchers = data_watchers_.keys();
for (auto getter: data_watchers) {
getter->sendError<dbif::ObjectGoneError>();
}
}
void FileBlobObject::description_reply(InfoGetter *getter) {
getter->sendInfo<dbif::FileBlobDescriptionReply>(
name(), comment(), 0, data().size(), 8, path()
);
}
void SubBlobObject::description_reply(InfoGetter *getter) {
getter->sendInfo<dbif::SubBlobDescriptionReply>(
name(), comment(), 0, data().size(), 8, db()->handle(parent()->sharedFromThis())
);
}
void ChunkObject::children_updated() {
LocalObject::children_updated();
parse_updated();
}
void ChunkObject::parse_updated() {
calcParseReplyItems();
for (InfoGetter *getter : parse_watchers_) {
parse_reply(getter);
}
}
void ChunkObject::calcParseReplyItems() {
parseReplyItems_ = items_;
QSet<PLocalObject> chunksInItems;
for (auto &item : items_) {
if (item.type != data::ChunkDataItem::SUBCHUNK) {
continue;
}
if (auto localObjectHandle = item.ref[0].dynamicCast<LocalObjectHandle>()) {
chunksInItems.insert(localObjectHandle->obj());
}
}
for (PLocalObject obj : children()) {
if (chunksInItems.contains(obj)) {
continue;
}
if (auto chunkObj = obj.dynamicCast<ChunkObject>()) {
parseReplyItems_.push_back(
data::ChunkDataItem::subchunk(chunkObj->start_, chunkObj->end_,
chunkObj->name(), db()->handle(obj)));
} else if (auto subBlobObj = obj.dynamicCast<SubBlobObject>()) {
parseReplyItems_.push_back(
data::ChunkDataItem::subblob(subBlobObj->name(), db()->handle(obj)));
}
}
}
void ChunkObject::parse_reply(InfoGetter *getter) {
getter->sendInfo<dbif::ChunkDataReply>(parseReplyItems_);
}
void ChunkObject::description_reply(InfoGetter *getter) {
getter->sendInfo<dbif::ChunkDescriptionReply>(
name(), comment(), db()->handle(blob_), db()->handle(parent_chunk_),
start_, end_, chunk_type_
);
}
void ChunkObject::remove_parse_watcher(InfoGetter *getter) {
parse_watchers_.remove(getter);
}
void ChunkObject::getInfo(InfoGetter *getter, PInfoRequest req, bool once) {
if (auto datareq = req.dynamicCast<dbif::ChunkDataRequest>()) {
parse_reply(getter);
if (!once) {
parse_watchers_.insert(getter);
auto shared_this = sharedFromThis();
QObject::connect(getter, &QObject::destroyed, [shared_this, getter] () {
shared_this.dynamicCast<ChunkObject>()->remove_parse_watcher(getter);
});
}
} else {
LocalObject::getInfo(getter, req, once);
}
}
void ChunkObject::runMethod(MethodRunner *runner, PMethodRequest req) {
if (auto chreq = req.dynamicCast<dbif::SetChunkBoundsRequest>()) {
start_ = chreq->start;
end_ = chreq->end;
description_updated();
runner->sendResult<dbif::NullReply>();
} else if (auto preq = req.dynamicCast<dbif::SetChunkParseRequest>()) {
start_ = preq->start;
end_ = preq->end;
items_ = preq->items;
description_updated();
parse_updated();
runner->sendResult<dbif::NullReply>();
} else if (auto blobreq = req.dynamicCast<dbif::ChunkCreateSubBlobRequest>()) {
PLocalObject obj = SubBlobObject::create(this, blobreq->data, blobreq->name);
runner->sendResult<dbif::CreatedReply>(db()->handle(obj));
} else {
LocalObject::runMethod(runner, req);
}
}
void ChunkObject::killed() {
LocalObject::killed();
if (parent_chunk_)
parent_chunk_->delChild(sharedFromThis());
else
blob_->delChild(sharedFromThis());
auto parse_watchers = parse_watchers_;
for (auto getter: parse_watchers) {
getter->sendError<dbif::ObjectGoneError>();
}
}
namespace {
class Register {
public:
Register() {
qRegisterMetaType<veles::db::PLocalObject>("veles::db::PLocalObject");
}
} _;
};
};
};
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "PetscSupport.h"
#ifdef LIBMESH_HAVE_PETSC
#include "FEProblem.h"
#include "DisplacedProblem.h"
#include "NonlinearSystem.h"
#include "DisplacedProblem.h"
#include "PenetrationLocator.h"
#include "NearestNodeLocator.h"
#include "MooseTypes.h"
//libMesh Includes
#include "libmesh/libmesh_common.h"
#include "libmesh/equation_systems.h"
#include "libmesh/nonlinear_implicit_system.h"
#include "libmesh/linear_implicit_system.h"
#include "libmesh/sparse_matrix.h"
#include "libmesh/petsc_vector.h"
#include "libmesh/petsc_matrix.h"
#include "libmesh/petsc_linear_solver.h"
#include "libmesh/petsc_preconditioner.h"
#include "libmesh/getpot.h"
//PETSc includes
#include <petsc.h>
#include <petscsnes.h>
#include <petscksp.h>
#if PETSC_VERSION_LESS_THAN(3,3,0)
// PETSc 3.2.x and lower
#include <private/kspimpl.h>
#include <private/snesimpl.h>
#else
// PETSc 3.3.0+
#include <petsc-private/kspimpl.h>
#include <petsc-private/snesimpl.h>
#include <petscdm.h>
#endif
namespace Moose
{
namespace PetscSupport
{
void petscSetOptions(Problem & problem)
{
const std::vector<MooseEnum> & petsc_options = problem.parameters().get<std::vector<MooseEnum> >("petsc_options");
const std::vector<std::string> & petsc_options_inames = problem.parameters().get<std::vector<std::string> >("petsc_inames");
const std::vector<std::string> & petsc_options_values = problem.parameters().get<std::vector<std::string> >("petsc_values");
if (petsc_options_inames.size() != petsc_options_values.size())
mooseError("Petsc names and options are not the same length");
PetscOptionsClear();
{ // Get any options specified on the command-line
int argc;
char ** args;
PetscGetArgs(&argc, &args);
PetscOptionsInsert(&argc, &args, NULL);
}
// Add any options specified in the input file
for (unsigned int i=0; i<petsc_options.size(); ++i)
PetscOptionsSetValue(std::string(petsc_options[i]).c_str(), PETSC_NULL);
for (unsigned int i=0; i<petsc_options_inames.size(); ++i)
PetscOptionsSetValue(petsc_options_inames[i].c_str(), petsc_options_values[i].c_str());
}
PetscErrorCode petscConverged(KSP ksp,PetscInt n,PetscReal rnorm,KSPConvergedReason *reason,void *dummy)
{
FEProblem & problem = *static_cast<FEProblem *>(dummy);
NonlinearSystem & system = problem.getNonlinearSystem();
*reason = KSP_CONVERGED_ITERATING;
//If it's the beginning of a new set of iterations, reset last_rnorm
if (!n)
system._last_rnorm = 1e99;
PetscReal norm_diff = std::fabs(rnorm - system._last_rnorm);
if(norm_diff < system._l_abs_step_tol)
{
*reason = KSP_CONVERGED_RTOL;
return(0);
}
system._last_rnorm = rnorm;
// From here, we want the default behavior of the KSPDefaultConverged
// test, but we don't want PETSc to die in that function with a
// CHKERRQ call... therefore we Push/Pop a different error handler
// and then call KSPDefaultConverged(). Finally, if we hit the
// max iteration count, we want to set KSP_CONVERGED_ITS.
PetscPushErrorHandler(PetscReturnErrorHandler,/* void* ctx= */PETSC_NULL);
// As of PETSc 3.0.0, you must call KSPDefaultConverged with a
// non-NULL context pointer which must be created with
// KSPDefaultConvergedCreate(), and destroyed with
// KSPDefaultConvergedDestroy().
/*PetscErrorCode ierr = */
KSPDefaultConverged(ksp, n, rnorm, reason, dummy);
// Pop the Error handler we pushed on the stack to go back
// to default PETSc error handling behavior.
PetscPopErrorHandler();
// If we hit max its then we consider that converged
if (n >= ksp->max_it) *reason = KSP_CONVERGED_ITS;
if(*reason == KSP_CONVERGED_ITS || *reason == KSP_CONVERGED_RTOL)
system._current_l_its.push_back(n);
return 0;
}
PetscErrorCode petscNonlinearConverged(SNES snes,PetscInt it,PetscReal xnorm,PetscReal snorm,PetscReal fnorm,SNESConvergedReason *reason,void * dummy)
{
// xnorm: norm of current iterate
// pnorm (snorm): norm of
// fnorm: norm of function
FEProblem & problem = *static_cast<FEProblem *>(dummy);
NonlinearSystem & system = problem.getNonlinearSystem();
#if PETSC_VERSION_LESS_THAN(3,3,0)
PetscInt stol = snes->xtol;
#else
PetscInt stol = snes->stol;
#endif
std::string msg;
const Real ref_resid = system._initial_residual;
const Real div_threshold = system._initial_residual*(1.0/snes->rtol);
MooseNonlinearConvergenceReason moose_reason = problem.checkNonlinearConvergence(msg,
it,
xnorm,
snorm,
fnorm,
snes->ttol,
snes->rtol,
stol,
snes->abstol,
snes->nfuncs,
snes->max_funcs,
ref_resid,
div_threshold);
if (msg.length() > 0)
PetscInfo(snes,msg.c_str());
switch (moose_reason)
{
case MOOSE_ITERATING:
*reason = SNES_CONVERGED_ITERATING;
break;
case MOOSE_CONVERGED_FNORM_ABS:
*reason = SNES_CONVERGED_FNORM_ABS;
break;
case MOOSE_CONVERGED_FNORM_RELATIVE:
*reason = SNES_CONVERGED_FNORM_RELATIVE;
break;
case MOOSE_CONVERGED_SNORM_RELATIVE:
#if PETSC_VERSION_LESS_THAN(3,3,0)
*reason = SNES_CONVERGED_PNORM_RELATIVE;
#else
*reason = SNES_CONVERGED_SNORM_RELATIVE;
#endif
break;
case MOOSE_DIVERGED_FUNCTION_COUNT:
*reason = SNES_DIVERGED_FUNCTION_COUNT;
break;
case MOOSE_DIVERGED_FNORM_NAN:
*reason = SNES_DIVERGED_FNORM_NAN;
break;
case MOOSE_DIVERGED_LINE_SEARCH:
#if PETSC_VERSION_LESS_THAN(3,2,0)
*reason = SNES_DIVERGED_LS_FAILURE;
#else
*reason = SNES_DIVERGED_LINE_SEARCH;
#endif
break;
}
return (0);
}
#if PETSC_VERSION_LESS_THAN(3,3,0)
// PETSc 3.2.x-
PetscErrorCode dampedCheck(SNES /*snes*/, Vec x, Vec y, Vec w, void *lsctx, PetscBool * /*changed_y*/, PetscBool * changed_w)
#else
// PETSc 3.3.0+
PetscErrorCode dampedCheck(SNESLineSearch /* linesearch */, Vec x, Vec y, Vec w, PetscBool * /*changed_y*/, PetscBool * changed_w, void *lsctx)
#endif
{
// From SNESLineSearchSetPostCheck docs:
// + x - old solution vector
// . y - search direction vector
// . w - new solution vector w = x-y
// . changed_y - indicates that the line search changed y
// . changed_w - indicates that the line search changed w
int ierr = 0;
Real damping = 1.0;
FEProblem & problem = *static_cast<FEProblem *>(lsctx);
TransientNonlinearImplicitSystem & system = problem.getNonlinearSystem().sys();
// The whole deal here is that we need ghosted versions of vectors y and w (they are parallel, but not ghosted).
// So to do that I'm going to duplicate current_local_solution (which has the ghosting we want).
// Then stuff values into the duplicates
// Then "close()" the vectors which updates their ghosted vaulues.
{
// cls is a PetscVector wrapper around the Vec in current_local_solution
PetscVector<Number> cls(static_cast<PetscVector<Number> *>(system.current_local_solution.get())->vec(), libMesh::CommWorld);
// Create new NumericVectors with the right ghosting - note: these will be destroyed
// when this function exits, so nobody better hold pointers to them any more!
AutoPtr<NumericVector<Number> > ghosted_y_aptr( cls.zero_clone() );
AutoPtr<NumericVector<Number> > ghosted_w_aptr( cls.zero_clone() );
// Create PetscVector wrappers around the Vecs.
PetscVector<Number> ghosted_y( static_cast<PetscVector<Number> *>(ghosted_y_aptr.get())->vec(), libMesh::CommWorld);
PetscVector<Number> ghosted_w( static_cast<PetscVector<Number> *>(ghosted_w_aptr.get())->vec(), libMesh::CommWorld);
ierr = VecCopy(y, ghosted_y.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr);
ierr = VecCopy(w, ghosted_w.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr);
ghosted_y.close();
ghosted_w.close();
damping = problem.computeDamping(ghosted_w, ghosted_y);
if(damping < 1.0)
{
//recalculate w=-damping*y + x
ierr = VecWAXPY(w, -damping, y, x); CHKERRABORT(libMesh::COMM_WORLD,ierr);
*changed_w = PETSC_TRUE;
}
if (problem.shouldUpdateSolution())
{
//Update the ghosted copy of w
if (*changed_w == PETSC_TRUE)
{
ierr = VecCopy(w, ghosted_w.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr);
ghosted_w.close();
}
//Create vector to directly modify w
PetscVector<Number> vec_w(w, libMesh::CommWorld);
bool updatedSolution = problem.updateSolution(vec_w, ghosted_w);
if (updatedSolution)
*changed_w = PETSC_TRUE;
}
}
return ierr;
}
void petscSetupDampers(NonlinearImplicitSystem& sys)
{
FEProblem * problem = sys.get_equation_systems().parameters.get<FEProblem *>("_fe_problem");
NonlinearSystem & nl = problem->getNonlinearSystem();
PetscNonlinearSolver<Number> * petsc_solver = dynamic_cast<PetscNonlinearSolver<Number> *>(nl.sys().nonlinear_solver.get());
SNES snes = petsc_solver->snes();
#if PETSC_VERSION_LESS_THAN(3,3,0)
// PETSc 3.2.x-
SNESLineSearchSetPostCheck(snes, dampedCheck, problem);
#else
// PETSc 3.3.0+
SNESLineSearch linesearch;
PetscErrorCode ierr = SNESGetSNESLineSearch(snes, &linesearch);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
ierr = SNESLineSearchSetPostCheck(linesearch, dampedCheck, problem);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
#endif
}
PCSide
getPetscPCSide(Moose::PCSideType pcs)
{
switch (pcs)
{
case Moose::PCS_LEFT: return PC_LEFT;
case Moose::PCS_RIGHT: return PC_RIGHT;
case Moose::PCS_SYMMETRIC: return PC_SYMMETRIC;
default: mooseError("Unknown PC side requested."); break;
}
}
void petscSetDefaults(FEProblem & problem)
{
// dig out Petsc solver
NonlinearSystem & nl = problem.getNonlinearSystem();
PetscNonlinearSolver<Number> * petsc_solver = dynamic_cast<PetscNonlinearSolver<Number> *>(nl.sys().nonlinear_solver.get());
SNES snes = petsc_solver->snes();
KSP ksp;
SNESGetKSP(snes, &ksp);
PCSide pcside = getPetscPCSide(nl.getPCSide());
#if PETSC_VERSION_LESS_THAN(3,2,0)
// PETSc 3.1.x-
KSPSetPreconditionerSide(ksp, pcside);
#else
// PETSc 3.2.x+
KSPSetPCSide(ksp, pcside);
#endif
SNESSetMaxLinearSolveFailures(snes, 1000000);
#if PETSC_VERSION_LESS_THAN(3,0,0)
// PETSc 2.3.3-
KSPSetConvergenceTest(ksp, petscConverged, &problem);
SNESSetConvergenceTest(snes, petscNonlinearConverged, &problem);
#else
// PETSc 3.0.0+
// In 3.0.0, the context pointer must actually be used, and the
// final argument to KSPSetConvergenceTest() is a pointer to a
// routine for destroying said private data context. In this case,
// we use the default context provided by PETSc in addition to
// a few other tests.
{
PetscErrorCode ierr = KSPSetConvergenceTest(ksp,
petscConverged,
&problem,
PETSC_NULL);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
ierr = SNESSetConvergenceTest(snes,
petscNonlinearConverged,
&problem,
PETSC_NULL);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
}
#endif
}
} // Namespace PetscSupport
} // Namespace MOOSE
#endif //LIBMESH_HAVE_PETSC
<commit_msg>Use less private data from PETSc when possible.<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "PetscSupport.h"
#ifdef LIBMESH_HAVE_PETSC
#include "FEProblem.h"
#include "DisplacedProblem.h"
#include "NonlinearSystem.h"
#include "DisplacedProblem.h"
#include "PenetrationLocator.h"
#include "NearestNodeLocator.h"
#include "MooseTypes.h"
//libMesh Includes
#include "libmesh/libmesh_common.h"
#include "libmesh/equation_systems.h"
#include "libmesh/nonlinear_implicit_system.h"
#include "libmesh/linear_implicit_system.h"
#include "libmesh/sparse_matrix.h"
#include "libmesh/petsc_vector.h"
#include "libmesh/petsc_matrix.h"
#include "libmesh/petsc_linear_solver.h"
#include "libmesh/petsc_preconditioner.h"
#include "libmesh/getpot.h"
//PETSc includes
#include <petsc.h>
#include <petscsnes.h>
#include <petscksp.h>
#if PETSC_VERSION_LESS_THAN(3,3,0)
// PETSc 3.2.x and lower
#include <private/kspimpl.h>
#include <private/snesimpl.h>
#else
// PETSc 3.3.0+
#include <petsc-private/snesimpl.h>
#include <petscdm.h>
#endif
namespace Moose
{
namespace PetscSupport
{
void petscSetOptions(Problem & problem)
{
const std::vector<MooseEnum> & petsc_options = problem.parameters().get<std::vector<MooseEnum> >("petsc_options");
const std::vector<std::string> & petsc_options_inames = problem.parameters().get<std::vector<std::string> >("petsc_inames");
const std::vector<std::string> & petsc_options_values = problem.parameters().get<std::vector<std::string> >("petsc_values");
if (petsc_options_inames.size() != petsc_options_values.size())
mooseError("Petsc names and options are not the same length");
PetscOptionsClear();
{ // Get any options specified on the command-line
int argc;
char ** args;
PetscGetArgs(&argc, &args);
PetscOptionsInsert(&argc, &args, NULL);
}
// Add any options specified in the input file
for (unsigned int i=0; i<petsc_options.size(); ++i)
PetscOptionsSetValue(std::string(petsc_options[i]).c_str(), PETSC_NULL);
for (unsigned int i=0; i<petsc_options_inames.size(); ++i)
PetscOptionsSetValue(petsc_options_inames[i].c_str(), petsc_options_values[i].c_str());
}
PetscErrorCode petscConverged(KSP ksp,PetscInt n,PetscReal rnorm,KSPConvergedReason *reason,void *dummy)
{
FEProblem & problem = *static_cast<FEProblem *>(dummy);
NonlinearSystem & system = problem.getNonlinearSystem();
*reason = KSP_CONVERGED_ITERATING;
//If it's the beginning of a new set of iterations, reset last_rnorm
if (!n)
system._last_rnorm = 1e99;
PetscReal norm_diff = std::fabs(rnorm - system._last_rnorm);
if(norm_diff < system._l_abs_step_tol)
{
*reason = KSP_CONVERGED_RTOL;
return(0);
}
system._last_rnorm = rnorm;
// From here, we want the default behavior of the KSPDefaultConverged
// test, but we don't want PETSc to die in that function with a
// CHKERRQ call... therefore we Push/Pop a different error handler
// and then call KSPDefaultConverged(). Finally, if we hit the
// max iteration count, we want to set KSP_CONVERGED_ITS.
PetscPushErrorHandler(PetscReturnErrorHandler,/* void* ctx= */PETSC_NULL);
// As of PETSc 3.0.0, you must call KSPDefaultConverged with a
// non-NULL context pointer which must be created with
// KSPDefaultConvergedCreate(), and destroyed with
// KSPDefaultConvergedDestroy().
/*PetscErrorCode ierr = */
KSPDefaultConverged(ksp, n, rnorm, reason, dummy);
// Pop the Error handler we pushed on the stack to go back
// to default PETSc error handling behavior.
PetscPopErrorHandler();
// If we hit max its, then we consider that converged (rather than
// KSP_DIVERGED_ITS). Note: ksp->max_it is a private parameter of
// KSP, so using it would require us to include the
// petsc-private/kspimpl.h header file, which we'd rather avoid.
if (*reason == KSP_DIVERGED_ITS) // (n >= ksp->max_it)
*reason = KSP_CONVERGED_ITS;
if(*reason == KSP_CONVERGED_ITS || *reason == KSP_CONVERGED_RTOL)
system._current_l_its.push_back(n);
return 0;
}
PetscErrorCode petscNonlinearConverged(SNES snes,PetscInt it,PetscReal xnorm,PetscReal snorm,PetscReal fnorm,SNESConvergedReason *reason,void * dummy)
{
// xnorm: norm of current iterate
// pnorm (snorm): norm of
// fnorm: norm of function
FEProblem & problem = *static_cast<FEProblem *>(dummy);
NonlinearSystem & system = problem.getNonlinearSystem();
// Let's be nice and always check PETSc error codes.
PetscErrorCode ierr = 0;
// Temporary variables to store SNES tolerances. Usual C-style would be to declare
// but not initialize these... but it bothers me to leave anything uninitialized.
PetscReal atol = 0.; // absolute convergence tolerance
PetscReal rtol = 0.; // relative convergence tolerance
PetscReal stol = 0.; // convergence (step) tolerance in terms of the norm of the change in the solution between steps
PetscInt maxit = 0; // maximum number of iterations
PetscInt maxf = 0; // maximum number of function evaluations
// Ask the SNES object about its tolerances.
ierr = SNESGetTolerances(snes,
&atol,
&rtol,
&stol,
&maxit,
&maxf);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// Get current number of function evaluations done by SNES.
PetscInt nfuncs = 0;
ierr = SNESGetNumberFunctionEvals(snes, &nfuncs);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// Error message that will be set by the FEProblem.
std::string msg;
const Real ref_resid = system._initial_residual;
const Real div_threshold = system._initial_residual*(1.0/rtol);
MooseNonlinearConvergenceReason moose_reason = problem.checkNonlinearConvergence(msg,
it,
xnorm,
snorm,
fnorm,
snes->ttol, // We still need <petsc-private/snesimpl.h> for this...
rtol,
stol,
atol,
nfuncs,
maxf,
ref_resid,
div_threshold);
if (msg.length() > 0)
PetscInfo(snes,msg.c_str());
switch (moose_reason)
{
case MOOSE_ITERATING:
*reason = SNES_CONVERGED_ITERATING;
break;
case MOOSE_CONVERGED_FNORM_ABS:
*reason = SNES_CONVERGED_FNORM_ABS;
break;
case MOOSE_CONVERGED_FNORM_RELATIVE:
*reason = SNES_CONVERGED_FNORM_RELATIVE;
break;
case MOOSE_CONVERGED_SNORM_RELATIVE:
#if PETSC_VERSION_LESS_THAN(3,3,0)
*reason = SNES_CONVERGED_PNORM_RELATIVE;
#else
*reason = SNES_CONVERGED_SNORM_RELATIVE;
#endif
break;
case MOOSE_DIVERGED_FUNCTION_COUNT:
*reason = SNES_DIVERGED_FUNCTION_COUNT;
break;
case MOOSE_DIVERGED_FNORM_NAN:
*reason = SNES_DIVERGED_FNORM_NAN;
break;
case MOOSE_DIVERGED_LINE_SEARCH:
#if PETSC_VERSION_LESS_THAN(3,2,0)
*reason = SNES_DIVERGED_LS_FAILURE;
#else
*reason = SNES_DIVERGED_LINE_SEARCH;
#endif
break;
}
return (0);
}
#if PETSC_VERSION_LESS_THAN(3,3,0)
// PETSc 3.2.x-
PetscErrorCode dampedCheck(SNES /*snes*/, Vec x, Vec y, Vec w, void *lsctx, PetscBool * /*changed_y*/, PetscBool * changed_w)
#else
// PETSc 3.3.0+
PetscErrorCode dampedCheck(SNESLineSearch /* linesearch */, Vec x, Vec y, Vec w, PetscBool * /*changed_y*/, PetscBool * changed_w, void *lsctx)
#endif
{
// From SNESLineSearchSetPostCheck docs:
// + x - old solution vector
// . y - search direction vector
// . w - new solution vector w = x-y
// . changed_y - indicates that the line search changed y
// . changed_w - indicates that the line search changed w
int ierr = 0;
Real damping = 1.0;
FEProblem & problem = *static_cast<FEProblem *>(lsctx);
TransientNonlinearImplicitSystem & system = problem.getNonlinearSystem().sys();
// The whole deal here is that we need ghosted versions of vectors y and w (they are parallel, but not ghosted).
// So to do that I'm going to duplicate current_local_solution (which has the ghosting we want).
// Then stuff values into the duplicates
// Then "close()" the vectors which updates their ghosted vaulues.
{
// cls is a PetscVector wrapper around the Vec in current_local_solution
PetscVector<Number> cls(static_cast<PetscVector<Number> *>(system.current_local_solution.get())->vec(), libMesh::CommWorld);
// Create new NumericVectors with the right ghosting - note: these will be destroyed
// when this function exits, so nobody better hold pointers to them any more!
AutoPtr<NumericVector<Number> > ghosted_y_aptr( cls.zero_clone() );
AutoPtr<NumericVector<Number> > ghosted_w_aptr( cls.zero_clone() );
// Create PetscVector wrappers around the Vecs.
PetscVector<Number> ghosted_y( static_cast<PetscVector<Number> *>(ghosted_y_aptr.get())->vec(), libMesh::CommWorld);
PetscVector<Number> ghosted_w( static_cast<PetscVector<Number> *>(ghosted_w_aptr.get())->vec(), libMesh::CommWorld);
ierr = VecCopy(y, ghosted_y.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr);
ierr = VecCopy(w, ghosted_w.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr);
ghosted_y.close();
ghosted_w.close();
damping = problem.computeDamping(ghosted_w, ghosted_y);
if(damping < 1.0)
{
//recalculate w=-damping*y + x
ierr = VecWAXPY(w, -damping, y, x); CHKERRABORT(libMesh::COMM_WORLD,ierr);
*changed_w = PETSC_TRUE;
}
if (problem.shouldUpdateSolution())
{
//Update the ghosted copy of w
if (*changed_w == PETSC_TRUE)
{
ierr = VecCopy(w, ghosted_w.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr);
ghosted_w.close();
}
//Create vector to directly modify w
PetscVector<Number> vec_w(w, libMesh::CommWorld);
bool updatedSolution = problem.updateSolution(vec_w, ghosted_w);
if (updatedSolution)
*changed_w = PETSC_TRUE;
}
}
return ierr;
}
void petscSetupDampers(NonlinearImplicitSystem& sys)
{
FEProblem * problem = sys.get_equation_systems().parameters.get<FEProblem *>("_fe_problem");
NonlinearSystem & nl = problem->getNonlinearSystem();
PetscNonlinearSolver<Number> * petsc_solver = dynamic_cast<PetscNonlinearSolver<Number> *>(nl.sys().nonlinear_solver.get());
SNES snes = petsc_solver->snes();
#if PETSC_VERSION_LESS_THAN(3,3,0)
// PETSc 3.2.x-
SNESLineSearchSetPostCheck(snes, dampedCheck, problem);
#else
// PETSc 3.3.0+
SNESLineSearch linesearch;
PetscErrorCode ierr = SNESGetSNESLineSearch(snes, &linesearch);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
ierr = SNESLineSearchSetPostCheck(linesearch, dampedCheck, problem);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
#endif
}
PCSide
getPetscPCSide(Moose::PCSideType pcs)
{
switch (pcs)
{
case Moose::PCS_LEFT: return PC_LEFT;
case Moose::PCS_RIGHT: return PC_RIGHT;
case Moose::PCS_SYMMETRIC: return PC_SYMMETRIC;
default: mooseError("Unknown PC side requested."); break;
}
}
void petscSetDefaults(FEProblem & problem)
{
// dig out Petsc solver
NonlinearSystem & nl = problem.getNonlinearSystem();
PetscNonlinearSolver<Number> * petsc_solver = dynamic_cast<PetscNonlinearSolver<Number> *>(nl.sys().nonlinear_solver.get());
SNES snes = petsc_solver->snes();
KSP ksp;
SNESGetKSP(snes, &ksp);
PCSide pcside = getPetscPCSide(nl.getPCSide());
#if PETSC_VERSION_LESS_THAN(3,2,0)
// PETSc 3.1.x-
KSPSetPreconditionerSide(ksp, pcside);
#else
// PETSc 3.2.x+
KSPSetPCSide(ksp, pcside);
#endif
SNESSetMaxLinearSolveFailures(snes, 1000000);
#if PETSC_VERSION_LESS_THAN(3,0,0)
// PETSc 2.3.3-
KSPSetConvergenceTest(ksp, petscConverged, &problem);
SNESSetConvergenceTest(snes, petscNonlinearConverged, &problem);
#else
// PETSc 3.0.0+
// In 3.0.0, the context pointer must actually be used, and the
// final argument to KSPSetConvergenceTest() is a pointer to a
// routine for destroying said private data context. In this case,
// we use the default context provided by PETSc in addition to
// a few other tests.
{
PetscErrorCode ierr = KSPSetConvergenceTest(ksp,
petscConverged,
&problem,
PETSC_NULL);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
ierr = SNESSetConvergenceTest(snes,
petscNonlinearConverged,
&problem,
PETSC_NULL);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
}
#endif
}
} // Namespace PetscSupport
} // Namespace MOOSE
#endif //LIBMESH_HAVE_PETSC
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/fileapi/file_system_usage_cache.h"
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "testing/gtest/include/gtest/gtest.h"
using namespace fileapi;
class FileSystemUsageCacheTest : public testing::Test {
public:
FileSystemUsageCacheTest() {}
void SetUp() {
ASSERT_TRUE(data_dir_.CreateUniqueTempDir());
}
protected:
FilePath GetUsageFilePath() {
return data_dir_.path().AppendASCII(FileSystemUsageCache::kUsageFileName);
}
private:
ScopedTempDir data_dir_;
DISALLOW_COPY_AND_ASSIGN(FileSystemUsageCacheTest);
};
TEST_F(FileSystemUsageCacheTest, CreateTest) {
FilePath usage_file_path = GetUsageFilePath();
EXPECT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, 0));
}
TEST_F(FileSystemUsageCacheTest, SetSizeTest) {
static const int64 size = 240122;
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, size));
EXPECT_EQ(size, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, SetLargeSizeTest) {
static const int64 size = kint64max;
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, size));
EXPECT_EQ(size, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, IncAndGetSizeTest) {
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, 98214));
ASSERT_TRUE(FileSystemUsageCache::IncrementDirty(usage_file_path));
EXPECT_EQ(-1, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, DecAndGetSizeTest) {
static const int64 size = 71839;
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, size));
// DecrementDirty for dirty = 0 is invalid. It returns false.
ASSERT_FALSE(FileSystemUsageCache::DecrementDirty(usage_file_path));
EXPECT_EQ(size, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, IncDecAndGetSizeTest) {
static const int64 size = 198491;
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, size));
ASSERT_TRUE(FileSystemUsageCache::IncrementDirty(usage_file_path));
ASSERT_TRUE(FileSystemUsageCache::DecrementDirty(usage_file_path));
EXPECT_EQ(size, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, DecIncAndGetSizeTest) {
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, 854238));
// DecrementDirty for dirty = 0 is invalid. It returns false.
ASSERT_FALSE(FileSystemUsageCache::DecrementDirty(usage_file_path));
ASSERT_TRUE(FileSystemUsageCache::IncrementDirty(usage_file_path));
// It tests DecrementDirty (which returns false) has no effect, i.e
// does not make dirty = -1 after DecrementDirty.
EXPECT_EQ(-1, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, ManyIncsSameDecsAndGetSizeTest) {
static const int64 size = 82412;
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, size));
for (int i = 0; i < 20; i++)
ASSERT_TRUE(FileSystemUsageCache::IncrementDirty(usage_file_path));
for (int i = 0; i < 20; i++)
ASSERT_TRUE(FileSystemUsageCache::DecrementDirty(usage_file_path));
EXPECT_EQ(size, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, ManyIncsLessDecsAndGetSizeTest) {
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, 19319));
for (int i = 0; i < 20; i++)
ASSERT_TRUE(FileSystemUsageCache::IncrementDirty(usage_file_path));
for (int i = 0; i < 19; i++)
ASSERT_TRUE(FileSystemUsageCache::DecrementDirty(usage_file_path));
EXPECT_EQ(-1, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, GetSizeWithoutCacheFileTest) {
FilePath usage_file_path = GetUsageFilePath();
EXPECT_EQ(-1, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, IncrementDirtyWithoutCacheFileTest) {
FilePath usage_file_path = GetUsageFilePath();
EXPECT_EQ(false, FileSystemUsageCache::IncrementDirty(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, DecrementDirtyWithoutCacheFileTest) {
FilePath usage_file_path = GetUsageFilePath();
EXPECT_EQ(false, FileSystemUsageCache::IncrementDirty(usage_file_path));
}
<commit_msg>Replace EXPECT_EQ(false, ...) with EXPECT_FALSE(...) to fix clang build<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/fileapi/file_system_usage_cache.h"
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "testing/gtest/include/gtest/gtest.h"
using namespace fileapi;
class FileSystemUsageCacheTest : public testing::Test {
public:
FileSystemUsageCacheTest() {}
void SetUp() {
ASSERT_TRUE(data_dir_.CreateUniqueTempDir());
}
protected:
FilePath GetUsageFilePath() {
return data_dir_.path().AppendASCII(FileSystemUsageCache::kUsageFileName);
}
private:
ScopedTempDir data_dir_;
DISALLOW_COPY_AND_ASSIGN(FileSystemUsageCacheTest);
};
TEST_F(FileSystemUsageCacheTest, CreateTest) {
FilePath usage_file_path = GetUsageFilePath();
EXPECT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, 0));
}
TEST_F(FileSystemUsageCacheTest, SetSizeTest) {
static const int64 size = 240122;
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, size));
EXPECT_EQ(size, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, SetLargeSizeTest) {
static const int64 size = kint64max;
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, size));
EXPECT_EQ(size, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, IncAndGetSizeTest) {
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, 98214));
ASSERT_TRUE(FileSystemUsageCache::IncrementDirty(usage_file_path));
EXPECT_EQ(-1, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, DecAndGetSizeTest) {
static const int64 size = 71839;
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, size));
// DecrementDirty for dirty = 0 is invalid. It returns false.
ASSERT_FALSE(FileSystemUsageCache::DecrementDirty(usage_file_path));
EXPECT_EQ(size, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, IncDecAndGetSizeTest) {
static const int64 size = 198491;
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, size));
ASSERT_TRUE(FileSystemUsageCache::IncrementDirty(usage_file_path));
ASSERT_TRUE(FileSystemUsageCache::DecrementDirty(usage_file_path));
EXPECT_EQ(size, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, DecIncAndGetSizeTest) {
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, 854238));
// DecrementDirty for dirty = 0 is invalid. It returns false.
ASSERT_FALSE(FileSystemUsageCache::DecrementDirty(usage_file_path));
ASSERT_TRUE(FileSystemUsageCache::IncrementDirty(usage_file_path));
// It tests DecrementDirty (which returns false) has no effect, i.e
// does not make dirty = -1 after DecrementDirty.
EXPECT_EQ(-1, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, ManyIncsSameDecsAndGetSizeTest) {
static const int64 size = 82412;
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, size));
for (int i = 0; i < 20; i++)
ASSERT_TRUE(FileSystemUsageCache::IncrementDirty(usage_file_path));
for (int i = 0; i < 20; i++)
ASSERT_TRUE(FileSystemUsageCache::DecrementDirty(usage_file_path));
EXPECT_EQ(size, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, ManyIncsLessDecsAndGetSizeTest) {
FilePath usage_file_path = GetUsageFilePath();
ASSERT_EQ(FileSystemUsageCache::kUsageFileSize,
FileSystemUsageCache::UpdateUsage(usage_file_path, 19319));
for (int i = 0; i < 20; i++)
ASSERT_TRUE(FileSystemUsageCache::IncrementDirty(usage_file_path));
for (int i = 0; i < 19; i++)
ASSERT_TRUE(FileSystemUsageCache::DecrementDirty(usage_file_path));
EXPECT_EQ(-1, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, GetSizeWithoutCacheFileTest) {
FilePath usage_file_path = GetUsageFilePath();
EXPECT_EQ(-1, FileSystemUsageCache::GetUsage(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, IncrementDirtyWithoutCacheFileTest) {
FilePath usage_file_path = GetUsageFilePath();
EXPECT_FALSE(FileSystemUsageCache::IncrementDirty(usage_file_path));
}
TEST_F(FileSystemUsageCacheTest, DecrementDirtyWithoutCacheFileTest) {
FilePath usage_file_path = GetUsageFilePath();
EXPECT_FALSE(FileSystemUsageCache::IncrementDirty(usage_file_path));
}
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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.
*********************************************************************/
/* Author: Ioan Sucan */
#include "ompl_interface_ros/ompl_interface_ros.h"
#include "planning_scene_monitor/planning_scene_monitor.h"
#include <tf/transform_listener.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "ompl_planning");
ros::NodeHandle nh;
ros::AsyncSpinner spinner(1);
spinner.start();
tf::TransformListener tf;
planning_scene_monitor::PlanningSceneMonitor psm("robot_description", &tf);
psm.startWorldGeometryMonitor();
psm.startSceneMonitor();
psm.startStateMonitor();
ompl_interface_ros::OMPLInterfaceROS o(psm.getPlanningScene());
o.printStatus();
ompl_interface::PlanningGroupPtr pg = o.getPlanningConfiguration("right_arm");
moveit_msgs::Constraints constr;
constr.orientation_constraints.resize(1);
moveit_msgs::OrientationConstraint &ocm = constr.orientation_constraints[0];
ocm.link_name = "r_wrist_roll_link";
ocm.orientation.header.frame_id = psm.getPlanningScene()->getPlanningFrame();
ocm.orientation.quaternion.x = 0.0;
ocm.orientation.quaternion.y = 0.0;
ocm.orientation.quaternion.z = 0.0;
ocm.orientation.quaternion.w = 1.0;
ocm.absolute_roll_tolerance = 0.01;
ocm.absolute_pitch_tolerance = 0.01;
ocm.absolute_yaw_tolerance = M_PI;
ocm.weight = 1.0;
pg->constructValidStateDatabase(psm.getPlanningScene()->getCurrentState(), constr,
100000, "/home/isucan/right_arm.ompldb");
sleep(1);
return 0;
}
<commit_msg>using new db api<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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.
*********************************************************************/
/* Author: Ioan Sucan */
#include "ompl_interface_ros/ompl_interface_ros.h"
#include "planning_scene_monitor/planning_scene_monitor.h"
#include <tf/transform_listener.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "ompl_planning");
ros::NodeHandle nh;
ros::AsyncSpinner spinner(1);
spinner.start();
tf::TransformListener tf;
planning_scene_monitor::PlanningSceneMonitor psm("robot_description", &tf);
psm.startWorldGeometryMonitor();
psm.startSceneMonitor();
psm.startStateMonitor();
ompl_interface_ros::OMPLInterfaceROS o(psm.getPlanningScene());
o.printStatus();
ompl_interface::PlanningGroupPtr pg = o.getPlanningConfiguration("right_arm");
moveit_msgs::Constraints constr;
constr.orientation_constraints.resize(1);
moveit_msgs::OrientationConstraint &ocm = constr.orientation_constraints[0];
ocm.link_name = "r_wrist_roll_link";
ocm.orientation.header.frame_id = psm.getPlanningScene()->getPlanningFrame();
ocm.orientation.quaternion.x = 0.0;
ocm.orientation.quaternion.y = 0.0;
ocm.orientation.quaternion.z = 0.0;
ocm.orientation.quaternion.w = 1.0;
ocm.absolute_roll_tolerance = 0.01;
ocm.absolute_pitch_tolerance = 0.01;
ocm.absolute_yaw_tolerance = M_PI;
ocm.weight = 1.0;
pg->constructValidStateDatabase(constr, 100000, "/home/isucan/right_arm.ompldb");
sleep(1);
return 0;
}
<|endoftext|> |
<commit_before>// Start by just creating shared memory and checking multiple processes can read
// and write to it.
// Then get the atomic operations working (add and cas).
// Then implement the algorithm. Option to clear all the memory?
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <memory>
#include <chrono>
#include <thread>
#include <napi.h>
typedef uint64_t sequence_t;
class Disruptor : public Napi::ObjectWrap<Disruptor>
{
public:
Disruptor(const Napi::CallbackInfo& info);
~Disruptor();
static void Initialize(Napi::Env env, Napi::Object exports);
// Unmap the shared memory. Don't access it again from this process!
void Release(const Napi::CallbackInfo& info);
// Return unconsumed values for a consumer
Napi::Value ConsumeNewSync(const Napi::CallbackInfo& info);
void ConsumeNewAsync(const Napi::CallbackInfo& info);
// Update consumer sequence without consuming more
void ConsumeCommit(const Napi::CallbackInfo&);
// Claim a slot for writing a value
Napi::Value ProduceClaimSync(const Napi::CallbackInfo& info);
// Commit a claimed slot.
Napi::Value ProduceCommitSync(const Napi::CallbackInfo& info);
private:
friend class ConsumeAsync;
int Release();
void UpdatePending(sequence_t seq_consumer, sequence_t seq_cursor);
Napi::Value ConsumeNewSync(const Napi::Env& env);
void ConsumeCommit();
uint32_t num_elements;
uint32_t element_size;
uint32_t num_consumers;
uint32_t consumer;
int32_t spin_sleep;
size_t shm_size;
void* shm_buf;
sequence_t *consumers; // for each consumer, next slot to read
sequence_t *cursor; // next slot to be filled
sequence_t *next; // next slot to claim
uint8_t* elements;
sequence_t *ptr_consumer;
sequence_t pending_seq_consumer;
sequence_t pending_seq_cursor;
};
struct CloseFD
{
void operator()(int *fd)
{
close(*fd);
delete fd;
}
};
void ThrowErrnoError(const Napi::CallbackInfo& info, const char *msg)
{
int errnum = errno;
char buf[1024] = {0};
auto errmsg = strerror_r(errnum, buf, sizeof(buf));
static_assert(std::is_same<decltype(errmsg), char*>::value,
"strerror_r must return char*");
throw Napi::Error::New(info.Env(),
std::string(msg) + ": " + (errmsg ? errmsg : std::to_string(errnum)));
}
Disruptor::Disruptor(const Napi::CallbackInfo& info) :
Napi::ObjectWrap<Disruptor>(info),
shm_buf(MAP_FAILED)
{
// TODO: How do we ensure non-initers don't read while init is happening?
// Arguments
Napi::String shm_name = info[0].As<Napi::String>();
num_elements = info[1].As<Napi::Number>();
element_size = info[2].As<Napi::Number>();
num_consumers = info[3].As<Napi::Number>();
bool init = info[4].As<Napi::Boolean>();
consumer = info[5].As<Napi::Number>();
if (info[6].IsNumber())
{
spin_sleep = info[6].As<Napi::Number>();
}
else
{
spin_sleep = -1;
}
// Open shared memory object
std::unique_ptr<int, CloseFD> shm_fd(new int(
shm_open(shm_name.Utf8Value().c_str(),
O_CREAT | O_RDWR | (init ? O_TRUNC : 0),
S_IRUSR | S_IWUSR)));
if (*shm_fd < 0)
{
ThrowErrnoError(info, "Failed to open shared memory object");
}
// Allow space for all the elements,
// a sequence number for each consumer,
// the cursor sequence number (last filled slot) and
// the next sequence number (first free slot).
shm_size = (num_consumers + 2) * sizeof(sequence_t) +
num_elements * element_size;
// Resize the shared memory if we're initializing it.
// Note: ftruncate initializes to null bytes.
if (init && (ftruncate(*shm_fd, shm_size) < 0))
{
ThrowErrnoError(info, "Failed to size shared memory");
}
// Map the shared memory
shm_buf = mmap(NULL,
shm_size,
PROT_READ | PROT_WRITE, MAP_SHARED,
*shm_fd,
0);
if (shm_buf == MAP_FAILED)
{
ThrowErrnoError(info, "Failed to map shared memory");
}
consumers = static_cast<sequence_t*>(shm_buf);
cursor = &consumers[num_consumers];
next = &cursor[1];
elements = reinterpret_cast<uint8_t*>(&next[1]);
ptr_consumer = &consumers[consumer];
pending_seq_consumer = 0;
pending_seq_cursor = 0;
}
Disruptor::~Disruptor()
{
Release();
}
int Disruptor::Release()
{
if (shm_buf != MAP_FAILED)
{
int r = munmap(shm_buf, shm_size);
if (r < 0)
{
return r;
}
shm_buf = MAP_FAILED;
}
return 0;
}
void Disruptor::Release(const Napi::CallbackInfo& info)
{
if (Release() < 0)
{
ThrowErrnoError(info, "Failed to unmap shared memory");
}
}
Napi::Value Disruptor::ConsumeNewSync(const Napi::Env& env)
{
// Return all elements [&consumers[consumer], cursor)
// Commit previous consume
ConsumeCommit();
Napi::Array r = Napi::Array::New(env);
sequence_t seq_consumer, pos_consumer;
sequence_t seq_cursor, pos_cursor;
do
{
// TODO: Do we need to access consumer sequence atomically if we know
// only this thread is updating it?
seq_consumer = __sync_val_compare_and_swap(ptr_consumer, 0, 0);
seq_cursor = __sync_val_compare_and_swap(cursor, 0, 0);
pos_consumer = seq_consumer % num_elements;
pos_cursor = seq_cursor % num_elements;
if (pos_cursor > pos_consumer)
{
r.Set(0U, Napi::Buffer<uint8_t>::New(
env,
elements + pos_consumer * element_size,
(pos_cursor - pos_consumer) * element_size));
UpdatePending(seq_consumer, seq_cursor);
break;
}
if (pos_cursor < pos_consumer)
{
r.Set(0U, Napi::Buffer<uint8_t>::New(
env,
elements + pos_consumer * element_size,
(num_elements - pos_consumer) * element_size));
if (pos_cursor > 0)
{
r.Set(1U, Napi::Buffer<uint8_t>::New(
env,
elements,
pos_cursor * element_size));
}
UpdatePending(seq_consumer, seq_cursor);
break;
}
if (spin_sleep < 0)
{
break;
}
if (spin_sleep > 0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(spin_sleep));
}
}
while (true);
return r;
}
Napi::Value Disruptor::ConsumeNewSync(const Napi::CallbackInfo& info)
{
return ConsumeNewSync(info.Env());
}
class ConsumeAsync : public Napi::AsyncWorker
{
public:
ConsumeAsync(const Napi::CallbackInfo& info) :
Napi::AsyncWorker(info[0].As<Napi::Function>()),
env(info.Env()),
disruptor_ref(Napi::Persistent(info.This().As<Napi::Object>()))
{
}
protected:
void Execute() override
{
Disruptor *disruptor = Napi::ObjectWrap<Disruptor>::Unwrap(
disruptor_ref.Value());
// TODO: Really there should be a way of passing result to the callback
Receiver().Set("result", disruptor->ConsumeNewSync(env));
}
private:
Napi::Env env;
Napi::ObjectReference disruptor_ref;
};
void Disruptor::ConsumeNewAsync(const Napi::CallbackInfo& info)
{
ConsumeAsync *worker = new ConsumeAsync(info);
worker->Queue();
}
void Disruptor::ConsumeCommit(const Napi::CallbackInfo&)
{
ConsumeCommit();
}
void Disruptor::UpdatePending(sequence_t seq_consumer, sequence_t seq_cursor)
{
pending_seq_consumer = seq_consumer;
pending_seq_cursor = seq_cursor;
}
void Disruptor::ConsumeCommit()
{
if (pending_seq_cursor)
{
__sync_val_compare_and_swap(ptr_consumer,
pending_seq_consumer,
pending_seq_cursor);
pending_seq_consumer = 0;
pending_seq_cursor = 0;
}
}
Napi::Value Disruptor::ProduceClaimSync(const Napi::CallbackInfo& info)
{
sequence_t seq_next, pos_next;
sequence_t seq_consumer, pos_consumer;
bool can_claim;
do
{
seq_next = __sync_val_compare_and_swap(next, 0, 0);
pos_next = seq_next % num_elements;
can_claim = true;
for (uint32_t i = 0; i < num_consumers; ++i)
{
seq_consumer = __sync_val_compare_and_swap(&consumers[i], 0, 0);
pos_consumer = seq_consumer % num_elements;
if ((pos_consumer == pos_next) && (seq_consumer != pos_next))
{
can_claim = false;
break;
}
}
if (can_claim &&
(__sync_val_compare_and_swap(next, seq_next, seq_next + 1) ==
seq_next))
{
Napi::Buffer<uint8_t> r = Napi::Buffer<uint8_t>::New(
info.Env(),
elements + pos_next * element_size,
element_size);
r.Set("seq_next", Napi::Number::New(info.Env(), seq_next));
return r;
}
if (spin_sleep < 0)
{
return Napi::Buffer<uint8_t>::New(info.Env(), 0);
}
if (spin_sleep > 0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(spin_sleep));
}
}
while (true);
}
Napi::Value Disruptor::ProduceCommitSync(const Napi::CallbackInfo& info)
{
sequence_t seq_next = (int64_t) info[0].As<Napi::Number>();
do
{
if (__sync_val_compare_and_swap(cursor, seq_next, seq_next + 1) ==
seq_next)
{
return Napi::Boolean::New(info.Env(), true);
}
if (spin_sleep < 0)
{
return Napi::Boolean::New(info.Env(), false);
}
if (spin_sleep > 0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(spin_sleep));
}
}
while (true);
}
// Async versions of ProduceClaim and ProduceCommit
void Disruptor::Initialize(Napi::Env env, Napi::Object exports)
{
exports["Disruptor"] = DefineClass(env, "Disruptor",
{
InstanceMethod("release", &Disruptor::Release),
InstanceMethod("consumeNewSync", &Disruptor::ConsumeNewSync),
InstanceMethod("consumeNewAsync", &Disruptor::ConsumeNewAsync),
InstanceMethod("consumeCommit", &Disruptor::ConsumeCommit),
InstanceMethod("produceClaimSync", &Disruptor::ProduceClaimSync),
InstanceMethod("produceCommitSync", &Disruptor::ProduceCommitSync)
});
}
void Initialize(Napi::Env env, Napi::Object exports, Napi::Object module)
{
Disruptor::Initialize(env, exports);
}
NODE_API_MODULE(disruptor, Initialize)
<commit_msg>Complete candidate producer implementation. Untested!<commit_after>// Start by just creating shared memory and checking multiple processes can read
// and write to it.
// Then get the atomic operations working (add and cas).
// Then implement the algorithm. Option to clear all the memory?
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <memory>
#include <chrono>
#include <thread>
#include <napi.h>
typedef uint64_t sequence_t;
class Disruptor : public Napi::ObjectWrap<Disruptor>
{
public:
Disruptor(const Napi::CallbackInfo& info);
~Disruptor();
static void Initialize(Napi::Env env, Napi::Object exports);
// Unmap the shared memory. Don't access it again from this process!
void Release(const Napi::CallbackInfo& info);
// Return unconsumed values for a consumer
Napi::Value ConsumeNewSync(const Napi::CallbackInfo& info);
void ConsumeNewAsync(const Napi::CallbackInfo& info);
// Update consumer sequence without consuming more
void ConsumeCommit(const Napi::CallbackInfo&);
// Claim a slot for writing a value
Napi::Value ProduceClaimSync(const Napi::CallbackInfo& info);
void ProduceClaimAsync(const Napi::CallbackInfo& info);
// Commit a claimed slot.
Napi::Value ProduceCommitSync(const Napi::CallbackInfo& info);
void ProduceCommitAsync(const Napi::CallbackInfo& info);
private:
friend class ConsumeNewAsyncWorker;
friend class ProduceClaimAsyncWorker;
friend class ProduceCommitAsyncWorker;
int Release();
void UpdatePending(sequence_t seq_consumer, sequence_t seq_cursor);
Napi::Value ConsumeNewSync(const Napi::Env& env);
void ConsumeCommit();
Napi::Value ProduceClaimSync(const Napi::Env& env);
Napi::Value ProduceCommitSync(const Napi::Env& env,
const Napi::Object& obj);
uint32_t num_elements;
uint32_t element_size;
uint32_t num_consumers;
uint32_t consumer;
int32_t spin_sleep;
size_t shm_size;
void* shm_buf;
sequence_t *consumers; // for each consumer, next slot to read
sequence_t *cursor; // next slot to be filled
sequence_t *next; // next slot to claim
uint8_t* elements;
sequence_t *ptr_consumer;
sequence_t pending_seq_consumer;
sequence_t pending_seq_cursor;
};
template <uint32_t CB>
class DisruptorAsyncWorker : public Napi::AsyncWorker
{
public:
DisruptorAsyncWorker(const Napi::CallbackInfo& info) :
Napi::AsyncWorker(info[CB].As<Napi::Function>()),
env(info.Env()),
disruptor_ref(Napi::Persistent(info.This().As<Napi::Object>()))
{
}
protected:
virtual Napi::Value Execute(Disruptor *disruptor) = 0;
void Execute() override
{
Disruptor *disruptor = Napi::ObjectWrap<Disruptor>::Unwrap(
disruptor_ref.Value());
// TODO: Really there should be a way of passing result to the callback
Receiver().Set("result", Execute(disruptor));
}
Napi::Env env;
Napi::ObjectReference disruptor_ref;
};
struct CloseFD
{
void operator()(int *fd)
{
close(*fd);
delete fd;
}
};
void ThrowErrnoError(const Napi::CallbackInfo& info, const char *msg)
{
int errnum = errno;
char buf[1024] = {0};
auto errmsg = strerror_r(errnum, buf, sizeof(buf));
static_assert(std::is_same<decltype(errmsg), char*>::value,
"strerror_r must return char*");
throw Napi::Error::New(info.Env(),
std::string(msg) + ": " + (errmsg ? errmsg : std::to_string(errnum)));
}
Disruptor::Disruptor(const Napi::CallbackInfo& info) :
Napi::ObjectWrap<Disruptor>(info),
shm_buf(MAP_FAILED)
{
// TODO: How do we ensure non-initers don't read while init is happening?
// Arguments
Napi::String shm_name = info[0].As<Napi::String>();
num_elements = info[1].As<Napi::Number>();
element_size = info[2].As<Napi::Number>();
num_consumers = info[3].As<Napi::Number>();
bool init = info[4].As<Napi::Boolean>();
consumer = info[5].As<Napi::Number>();
if (info[6].IsNumber())
{
spin_sleep = info[6].As<Napi::Number>();
}
else
{
spin_sleep = -1;
}
// Open shared memory object
std::unique_ptr<int, CloseFD> shm_fd(new int(
shm_open(shm_name.Utf8Value().c_str(),
O_CREAT | O_RDWR | (init ? O_TRUNC : 0),
S_IRUSR | S_IWUSR)));
if (*shm_fd < 0)
{
ThrowErrnoError(info, "Failed to open shared memory object");
}
// Allow space for all the elements,
// a sequence number for each consumer,
// the cursor sequence number (last filled slot) and
// the next sequence number (first free slot).
shm_size = (num_consumers + 2) * sizeof(sequence_t) +
num_elements * element_size;
// Resize the shared memory if we're initializing it.
// Note: ftruncate initializes to null bytes.
if (init && (ftruncate(*shm_fd, shm_size) < 0))
{
ThrowErrnoError(info, "Failed to size shared memory");
}
// Map the shared memory
shm_buf = mmap(NULL,
shm_size,
PROT_READ | PROT_WRITE, MAP_SHARED,
*shm_fd,
0);
if (shm_buf == MAP_FAILED)
{
ThrowErrnoError(info, "Failed to map shared memory");
}
consumers = static_cast<sequence_t*>(shm_buf);
cursor = &consumers[num_consumers];
next = &cursor[1];
elements = reinterpret_cast<uint8_t*>(&next[1]);
ptr_consumer = &consumers[consumer];
pending_seq_consumer = 0;
pending_seq_cursor = 0;
}
Disruptor::~Disruptor()
{
Release();
}
int Disruptor::Release()
{
if (shm_buf != MAP_FAILED)
{
int r = munmap(shm_buf, shm_size);
if (r < 0)
{
return r;
}
shm_buf = MAP_FAILED;
}
return 0;
}
void Disruptor::Release(const Napi::CallbackInfo& info)
{
if (Release() < 0)
{
ThrowErrnoError(info, "Failed to unmap shared memory");
}
}
Napi::Value Disruptor::ConsumeNewSync(const Napi::Env& env)
{
// Return all elements [&consumers[consumer], cursor)
// Commit previous consume
ConsumeCommit();
Napi::Array r = Napi::Array::New(env);
sequence_t seq_consumer, pos_consumer;
sequence_t seq_cursor, pos_cursor;
do
{
// TODO: Do we need to access consumer sequence atomically if we know
// only this thread is updating it?
seq_consumer = __sync_val_compare_and_swap(ptr_consumer, 0, 0);
seq_cursor = __sync_val_compare_and_swap(cursor, 0, 0);
pos_consumer = seq_consumer % num_elements;
pos_cursor = seq_cursor % num_elements;
if (pos_cursor > pos_consumer)
{
r.Set(0U, Napi::Buffer<uint8_t>::New(
env,
elements + pos_consumer * element_size,
(pos_cursor - pos_consumer) * element_size));
UpdatePending(seq_consumer, seq_cursor);
break;
}
if (pos_cursor < pos_consumer)
{
r.Set(0U, Napi::Buffer<uint8_t>::New(
env,
elements + pos_consumer * element_size,
(num_elements - pos_consumer) * element_size));
if (pos_cursor > 0)
{
r.Set(1U, Napi::Buffer<uint8_t>::New(
env,
elements,
pos_cursor * element_size));
}
UpdatePending(seq_consumer, seq_cursor);
break;
}
if (spin_sleep < 0)
{
break;
}
if (spin_sleep > 0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(spin_sleep));
}
}
while (true);
return r;
}
Napi::Value Disruptor::ConsumeNewSync(const Napi::CallbackInfo& info)
{
return ConsumeNewSync(info.Env());
}
class ConsumeNewAsyncWorker : public DisruptorAsyncWorker<0>
{
public:
ConsumeNewAsyncWorker(const Napi::CallbackInfo& info) :
DisruptorAsyncWorker<0>(info)
{
}
protected:
Napi::Value Execute(Disruptor* disruptor) override
{
return disruptor->ConsumeNewSync(env);
}
};
void Disruptor::ConsumeNewAsync(const Napi::CallbackInfo& info)
{
ConsumeNewAsyncWorker *worker = new ConsumeNewAsyncWorker(info);
worker->Queue();
}
void Disruptor::ConsumeCommit(const Napi::CallbackInfo&)
{
ConsumeCommit();
}
void Disruptor::UpdatePending(sequence_t seq_consumer, sequence_t seq_cursor)
{
pending_seq_consumer = seq_consumer;
pending_seq_cursor = seq_cursor;
}
void Disruptor::ConsumeCommit()
{
if (pending_seq_cursor)
{
__sync_val_compare_and_swap(ptr_consumer,
pending_seq_consumer,
pending_seq_cursor);
pending_seq_consumer = 0;
pending_seq_cursor = 0;
}
}
Napi::Value Disruptor::ProduceClaimSync(const Napi::Env& env)
{
sequence_t seq_next, pos_next;
sequence_t seq_consumer, pos_consumer;
bool can_claim;
do
{
seq_next = __sync_val_compare_and_swap(next, 0, 0);
pos_next = seq_next % num_elements;
can_claim = true;
for (uint32_t i = 0; i < num_consumers; ++i)
{
seq_consumer = __sync_val_compare_and_swap(&consumers[i], 0, 0);
pos_consumer = seq_consumer % num_elements;
if ((pos_consumer == pos_next) && (seq_consumer != pos_next))
{
can_claim = false;
break;
}
}
if (can_claim &&
(__sync_val_compare_and_swap(next, seq_next, seq_next + 1) ==
seq_next))
{
Napi::Buffer<uint8_t> r = Napi::Buffer<uint8_t>::New(
env,
elements + pos_next * element_size,
element_size);
r.Set("seq_next", Napi::Number::New(env, seq_next));
return r;
}
if (spin_sleep < 0)
{
return Napi::Buffer<uint8_t>::New(env, 0);
}
if (spin_sleep > 0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(spin_sleep));
}
}
while (true);
}
Napi::Value Disruptor::ProduceClaimSync(const Napi::CallbackInfo& info)
{
return ProduceClaimSync(info.Env());
}
class ProduceClaimAsyncWorker : public DisruptorAsyncWorker<0>
{
public:
ProduceClaimAsyncWorker(const Napi::CallbackInfo& info) :
DisruptorAsyncWorker<0>(info)
{
}
protected:
Napi::Value Execute(Disruptor* disruptor) override
{
return disruptor->ProduceClaimSync(env);
}
};
void Disruptor::ProduceClaimAsync(const Napi::CallbackInfo& info)
{
ProduceClaimAsyncWorker *worker = new ProduceClaimAsyncWorker(info);
worker->Queue();
}
Napi::Value Disruptor::ProduceCommitSync(const Napi::Env& env,
const Napi::Object& obj)
{
sequence_t seq_next = obj.Get("seq_next").As<Napi::Number>().Int64Value();
do
{
if (__sync_val_compare_and_swap(cursor, seq_next, seq_next + 1) ==
seq_next)
{
return Napi::Boolean::New(env, true);
}
if (spin_sleep < 0)
{
return Napi::Boolean::New(env, false);
}
if (spin_sleep > 0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(spin_sleep));
}
}
while (true);
}
Napi::Value Disruptor::ProduceCommitSync(const Napi::CallbackInfo& info)
{
return ProduceCommitSync(info.Env(), info[0].As<Napi::Object>());
}
class ProduceCommitAsyncWorker : public DisruptorAsyncWorker<1>
{
public:
ProduceCommitAsyncWorker(const Napi::CallbackInfo& info) :
DisruptorAsyncWorker<1>(info),
obj_ref(Napi::Persistent(info[0].As<Napi::Object>()))
{
}
protected:
Napi::Value Execute(Disruptor* disruptor) override
{
return disruptor->ProduceCommitSync(env, obj_ref.Value());
}
Napi::ObjectReference obj_ref;
};
void Disruptor::Initialize(Napi::Env env, Napi::Object exports)
{
exports["Disruptor"] = DefineClass(env, "Disruptor",
{
InstanceMethod("release", &Disruptor::Release),
InstanceMethod("consumeNew", &Disruptor::ConsumeNewAsync),
InstanceMethod("consumeNewSync", &Disruptor::ConsumeNewSync),
InstanceMethod("consumeCommit", &Disruptor::ConsumeCommit),
InstanceMethod("produceClaim", &Disruptor::ProduceClaimAsync),
InstanceMethod("produceClaimSync", &Disruptor::ProduceClaimSync),
InstanceMethod("produceCommit", &Disruptor::ProduceCommitAsync),
InstanceMethod("produceCommitSync", &Disruptor::ProduceCommitSync),
});
}
void Initialize(Napi::Env env, Napi::Object exports, Napi::Object module)
{
Disruptor::Initialize(env, exports);
}
NODE_API_MODULE(disruptor, Initialize)
<|endoftext|> |
<commit_before>// Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// macho_id.cc: Functions to gather identifying information from a macho file
//
// See macho_id.h for documentation
//
// Author: Dan Waylonis
#include <fcntl.h>
#include <mach-o/loader.h>
#include <mach-o/swap.h>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "common/mac/macho_id.h"
#include "common/mac/macho_walker.h"
namespace MacFileUtilities {
MachoID::MachoID(const char *path) {
strlcpy(path_, path, sizeof(path_));
file_ = open(path, O_RDONLY);
}
MachoID::~MachoID() {
if (file_ != -1)
close(file_);
}
// The CRC info is from http://en.wikipedia.org/wiki/Adler-32
// With optimizations from http://www.zlib.net/
// The largest prime smaller than 65536
#define MOD_ADLER 65521
// MAX_BLOCK is the largest n such that 255n(n+1)/2 + (n+1)(MAX_BLOCK-1) <= 2^32-1
#define MAX_BLOCK 5552
void MachoID::UpdateCRC(unsigned char *bytes, size_t size) {
// Unrolled loops for summing
#define DO1(buf,i) {sum1 += (buf)[i]; sum2 += sum1;}
#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
#define DO16(buf) DO8(buf,0); DO8(buf,8);
// Split up the crc
uint32_t sum1 = crc_ & 0xFFFF;
uint32_t sum2 = (crc_ >> 16) & 0xFFFF;
// Do large blocks
while (size >= MAX_BLOCK) {
size -= MAX_BLOCK;
int block_count = MAX_BLOCK / 16;
do {
DO16(bytes);
bytes += 16;
} while (--block_count);
sum1 %= MOD_ADLER;
sum2 %= MOD_ADLER;
}
// Do remaining bytes
if (size) {
while (size >= 16) {
size -= 16;
DO16(bytes);
bytes += 16;
}
while (size--) {
sum1 += *bytes++;
sum2 += sum1;
}
sum1 %= MOD_ADLER;
sum2 %= MOD_ADLER;
crc_ = (sum2 << 16) | sum1;
}
}
void MachoID::UpdateMD5(unsigned char *bytes, size_t size) {
MD5_Update(&md5_context_, bytes, size);
}
void MachoID::UpdateSHA1(unsigned char *bytes, size_t size) {
SHA_Update(&sha1_context_, bytes, size);
}
void MachoID::Update(MachoWalker *walker, unsigned long offset, size_t size) {
if (!update_function_ || !size)
return;
// Read up to 4k bytes at a time
unsigned char buffer[4096];
size_t buffer_size;
off_t file_offset = offset;
while (size > 0) {
if (size > sizeof(buffer)) {
buffer_size = sizeof(buffer);
size -= buffer_size;
} else {
buffer_size = size;
size = 0;
}
if (!walker->ReadBytes(buffer, buffer_size, file_offset))
return;
(this->*update_function_)(buffer, buffer_size);
file_offset += buffer_size;
}
}
bool MachoID::UUIDCommand(int cpu_type, unsigned char bytes[16]) {
struct uuid_command uuid_cmd;
MachoWalker walker(path_, UUIDWalkerCB, &uuid_cmd);
uuid_cmd.cmd = 0;
if (!walker.WalkHeader(cpu_type))
return false;
// If we found the command, we'll have initialized the uuid_command
// structure
if (uuid_cmd.cmd == LC_UUID) {
memcpy(bytes, uuid_cmd.uuid, sizeof(uuid_cmd.uuid));
return true;
}
return false;
}
bool MachoID::IDCommand(int cpu_type, unsigned char identifier[16]) {
struct dylib_command dylib_cmd;
MachoWalker walker(path_, IDWalkerCB, &dylib_cmd);
dylib_cmd.cmd = 0;
if (!walker.WalkHeader(cpu_type))
return false;
// If we found the command, we'll have initialized the dylib_command
// structure
if (dylib_cmd.cmd == LC_ID_DYLIB) {
// Take the timestamp, version, and compatability version bytes to form
// the first 12 bytes, pad the rest with zeros
identifier[0] = (dylib_cmd.dylib.timestamp >> 24) & 0xFF;
identifier[1] = (dylib_cmd.dylib.timestamp >> 16) & 0xFF;
identifier[2] = (dylib_cmd.dylib.timestamp >> 8) & 0xFF;
identifier[3] = dylib_cmd.dylib.timestamp & 0xFF;
identifier[4] = (dylib_cmd.dylib.current_version >> 24) & 0xFF;
identifier[5] = (dylib_cmd.dylib.current_version >> 16) & 0xFF;
identifier[6] = (dylib_cmd.dylib.current_version >> 8) & 0xFF;
identifier[7] = dylib_cmd.dylib.current_version & 0xFF;
identifier[8] = (dylib_cmd.dylib.compatibility_version >> 24) & 0xFF;
identifier[9] = (dylib_cmd.dylib.compatibility_version >> 16) & 0xFF;
identifier[10] = (dylib_cmd.dylib.compatibility_version >> 8) & 0xFF;
identifier[11] = dylib_cmd.dylib.compatibility_version & 0xFF;
identifier[12] = identifier[13] = identifier[14] = identifier[15] = 0;
return true;
}
return false;
}
uint32_t MachoID::Adler32(int cpu_type) {
MachoWalker walker(path_, WalkerCB, this);
update_function_ = &MachoID::UpdateCRC;
crc_ = 0;
if (!walker.WalkHeader(cpu_type))
return 0;
return crc_;
}
bool MachoID::MD5(int cpu_type, unsigned char identifier[16]) {
MachoWalker walker(path_, WalkerCB, this);
update_function_ = &MachoID::UpdateMD5;
if (MD5_Init(&md5_context_)) {
if (!walker.WalkHeader(cpu_type))
return false;
MD5_Final(identifier, &md5_context_);
return true;
}
return false;
}
bool MachoID::SHA1(int cpu_type, unsigned char identifier[16]) {
MachoWalker walker(path_, WalkerCB, this);
update_function_ = &MachoID::UpdateSHA1;
if (SHA_Init(&sha1_context_)) {
if (!walker.WalkHeader(cpu_type))
return false;
SHA_Final(identifier, &sha1_context_);
return true;
}
return false;
}
// static
bool MachoID::WalkerCB(MachoWalker *walker, load_command *cmd, off_t offset,
bool swap, void *context) {
MachoID *macho_id = (MachoID *)context;
if (cmd->cmd == LC_SEGMENT) {
struct segment_command seg;
if (!walker->ReadBytes(&seg, sizeof(seg), offset))
return false;
if (swap)
swap_segment_command(&seg, NXHostByteOrder());
struct mach_header_64 header;
off_t header_offset;
if (!walker->CurrentHeader(&header, &header_offset))
return false;
// Process segments that have sections:
// (e.g., __TEXT, __DATA, __IMPORT, __OBJC)
offset += sizeof(struct segment_command);
struct section sec;
for (unsigned long i = 0; i < seg.nsects; ++i) {
if (!walker->ReadBytes(&sec, sizeof(sec), offset))
return false;
if (swap)
swap_section(&sec, 1, NXHostByteOrder());
macho_id->Update(walker, header_offset + sec.offset, sec.size);
offset += sizeof(struct section);
}
} else if (cmd->cmd == LC_SEGMENT_64) {
struct segment_command_64 seg64;
if (!walker->ReadBytes(&seg64, sizeof(seg64), offset))
return false;
if (swap)
swap_segment_command_64(&seg64, NXHostByteOrder());
struct mach_header_64 header;
off_t header_offset;
if (!walker->CurrentHeader(&header, &header_offset))
return false;
// Process segments that have sections:
// (e.g., __TEXT, __DATA, __IMPORT, __OBJC)
offset += sizeof(struct segment_command_64);
struct section_64 sec64;
for (unsigned long i = 0; i < seg64.nsects; ++i) {
if (!walker->ReadBytes(&sec64, sizeof(sec64), offset))
return false;
if (swap)
swap_section_64(&sec64, 1, NXHostByteOrder());
macho_id->Update(walker, header_offset + sec64.offset, sec64.size);
offset += sizeof(struct section_64);
}
}
// Continue processing
return true;
}
// static
bool MachoID::UUIDWalkerCB(MachoWalker *walker, load_command *cmd, off_t offset,
bool swap, void *context) {
if (cmd->cmd == LC_UUID) {
struct uuid_command *uuid_cmd = (struct uuid_command *)context;
if (!walker->ReadBytes(uuid_cmd, sizeof(struct uuid_command), offset))
return false;
if (swap)
swap_uuid_command(uuid_cmd, NXHostByteOrder());
return false;
}
// Continue processing
return true;
}
// static
bool MachoID::IDWalkerCB(MachoWalker *walker, load_command *cmd, off_t offset,
bool swap, void *context) {
if (cmd->cmd == LC_ID_DYLIB) {
struct dylib_command *dylib_cmd = (struct dylib_command *)context;
if (!walker->ReadBytes(dylib_cmd, sizeof(struct dylib_command), offset))
return false;
if (swap)
swap_dylib_command(dylib_cmd, NXHostByteOrder());
return false;
}
// Continue processing
return true;
}
} // namespace MacFileUtilities
<commit_msg>issue 133: Mach-o UUID generation has problems - reviewed by waylonis<commit_after>// Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// macho_id.cc: Functions to gather identifying information from a macho file
//
// See macho_id.h for documentation
//
// Author: Dan Waylonis
#include <fcntl.h>
#include <mach-o/loader.h>
#include <mach-o/swap.h>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "common/mac/macho_id.h"
#include "common/mac/macho_walker.h"
namespace MacFileUtilities {
MachoID::MachoID(const char *path) {
strlcpy(path_, path, sizeof(path_));
file_ = open(path, O_RDONLY);
}
MachoID::~MachoID() {
if (file_ != -1)
close(file_);
}
// The CRC info is from http://en.wikipedia.org/wiki/Adler-32
// With optimizations from http://www.zlib.net/
// The largest prime smaller than 65536
#define MOD_ADLER 65521
// MAX_BLOCK is the largest n such that 255n(n+1)/2 + (n+1)(MAX_BLOCK-1) <= 2^32-1
#define MAX_BLOCK 5552
void MachoID::UpdateCRC(unsigned char *bytes, size_t size) {
// Unrolled loops for summing
#define DO1(buf,i) {sum1 += (buf)[i]; sum2 += sum1;}
#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
#define DO16(buf) DO8(buf,0); DO8(buf,8);
// Split up the crc
uint32_t sum1 = crc_ & 0xFFFF;
uint32_t sum2 = (crc_ >> 16) & 0xFFFF;
// Do large blocks
while (size >= MAX_BLOCK) {
size -= MAX_BLOCK;
int block_count = MAX_BLOCK / 16;
do {
DO16(bytes);
bytes += 16;
} while (--block_count);
sum1 %= MOD_ADLER;
sum2 %= MOD_ADLER;
}
// Do remaining bytes
if (size) {
while (size >= 16) {
size -= 16;
DO16(bytes);
bytes += 16;
}
while (size--) {
sum1 += *bytes++;
sum2 += sum1;
}
sum1 %= MOD_ADLER;
sum2 %= MOD_ADLER;
crc_ = (sum2 << 16) | sum1;
}
}
void MachoID::UpdateMD5(unsigned char *bytes, size_t size) {
MD5_Update(&md5_context_, bytes, size);
}
void MachoID::UpdateSHA1(unsigned char *bytes, size_t size) {
SHA_Update(&sha1_context_, bytes, size);
}
void MachoID::Update(MachoWalker *walker, unsigned long offset, size_t size) {
if (!update_function_ || !size)
return;
// Read up to 4k bytes at a time
unsigned char buffer[4096];
size_t buffer_size;
off_t file_offset = offset;
while (size > 0) {
if (size > sizeof(buffer)) {
buffer_size = sizeof(buffer);
size -= buffer_size;
} else {
buffer_size = size;
size = 0;
}
if (!walker->ReadBytes(buffer, buffer_size, file_offset))
return;
(this->*update_function_)(buffer, buffer_size);
file_offset += buffer_size;
}
}
bool MachoID::UUIDCommand(int cpu_type, unsigned char bytes[16]) {
struct uuid_command uuid_cmd;
MachoWalker walker(path_, UUIDWalkerCB, &uuid_cmd);
uuid_cmd.cmd = 0;
if (!walker.WalkHeader(cpu_type))
return false;
// If we found the command, we'll have initialized the uuid_command
// structure
if (uuid_cmd.cmd == LC_UUID) {
memcpy(bytes, uuid_cmd.uuid, sizeof(uuid_cmd.uuid));
return true;
}
return false;
}
bool MachoID::IDCommand(int cpu_type, unsigned char identifier[16]) {
struct dylib_command dylib_cmd;
MachoWalker walker(path_, IDWalkerCB, &dylib_cmd);
dylib_cmd.cmd = 0;
if (!walker.WalkHeader(cpu_type))
return false;
// If we found the command, we'll have initialized the dylib_command
// structure
if (dylib_cmd.cmd == LC_ID_DYLIB) {
// Take the hashed filename, version, and compatability version bytes
// to form the first 12 bytes, pad the rest with zeros
// create a crude hash of the filename to generate the first 4 bytes
identifier[0] = 0;
identifier[1] = 0;
identifier[2] = 0;
identifier[3] = 0;
for (int j = 0, i = strlen(path_)-1; i >= 0 && path_[i]!='/'; ++j, --i) {
identifier[j%4] += path_[i];
}
identifier[4] = (dylib_cmd.dylib.current_version >> 24) & 0xFF;
identifier[5] = (dylib_cmd.dylib.current_version >> 16) & 0xFF;
identifier[6] = (dylib_cmd.dylib.current_version >> 8) & 0xFF;
identifier[7] = dylib_cmd.dylib.current_version & 0xFF;
identifier[8] = (dylib_cmd.dylib.compatibility_version >> 24) & 0xFF;
identifier[9] = (dylib_cmd.dylib.compatibility_version >> 16) & 0xFF;
identifier[10] = (dylib_cmd.dylib.compatibility_version >> 8) & 0xFF;
identifier[11] = dylib_cmd.dylib.compatibility_version & 0xFF;
identifier[12] = identifier[13] = identifier[14] = identifier[15] = 0;
return true;
}
return false;
}
uint32_t MachoID::Adler32(int cpu_type) {
MachoWalker walker(path_, WalkerCB, this);
update_function_ = &MachoID::UpdateCRC;
crc_ = 0;
if (!walker.WalkHeader(cpu_type))
return 0;
return crc_;
}
bool MachoID::MD5(int cpu_type, unsigned char identifier[16]) {
MachoWalker walker(path_, WalkerCB, this);
update_function_ = &MachoID::UpdateMD5;
if (MD5_Init(&md5_context_)) {
if (!walker.WalkHeader(cpu_type))
return false;
MD5_Final(identifier, &md5_context_);
return true;
}
return false;
}
bool MachoID::SHA1(int cpu_type, unsigned char identifier[16]) {
MachoWalker walker(path_, WalkerCB, this);
update_function_ = &MachoID::UpdateSHA1;
if (SHA_Init(&sha1_context_)) {
if (!walker.WalkHeader(cpu_type))
return false;
SHA_Final(identifier, &sha1_context_);
return true;
}
return false;
}
// static
bool MachoID::WalkerCB(MachoWalker *walker, load_command *cmd, off_t offset,
bool swap, void *context) {
MachoID *macho_id = (MachoID *)context;
if (cmd->cmd == LC_SEGMENT) {
struct segment_command seg;
if (!walker->ReadBytes(&seg, sizeof(seg), offset))
return false;
if (swap)
swap_segment_command(&seg, NXHostByteOrder());
struct mach_header_64 header;
off_t header_offset;
if (!walker->CurrentHeader(&header, &header_offset))
return false;
// Process segments that have sections:
// (e.g., __TEXT, __DATA, __IMPORT, __OBJC)
offset += sizeof(struct segment_command);
struct section sec;
for (unsigned long i = 0; i < seg.nsects; ++i) {
if (!walker->ReadBytes(&sec, sizeof(sec), offset))
return false;
if (swap)
swap_section(&sec, 1, NXHostByteOrder());
macho_id->Update(walker, header_offset + sec.offset, sec.size);
offset += sizeof(struct section);
}
} else if (cmd->cmd == LC_SEGMENT_64) {
struct segment_command_64 seg64;
if (!walker->ReadBytes(&seg64, sizeof(seg64), offset))
return false;
if (swap)
swap_segment_command_64(&seg64, NXHostByteOrder());
struct mach_header_64 header;
off_t header_offset;
if (!walker->CurrentHeader(&header, &header_offset))
return false;
// Process segments that have sections:
// (e.g., __TEXT, __DATA, __IMPORT, __OBJC)
offset += sizeof(struct segment_command_64);
struct section_64 sec64;
for (unsigned long i = 0; i < seg64.nsects; ++i) {
if (!walker->ReadBytes(&sec64, sizeof(sec64), offset))
return false;
if (swap)
swap_section_64(&sec64, 1, NXHostByteOrder());
macho_id->Update(walker, header_offset + sec64.offset, sec64.size);
offset += sizeof(struct section_64);
}
}
// Continue processing
return true;
}
// static
bool MachoID::UUIDWalkerCB(MachoWalker *walker, load_command *cmd, off_t offset,
bool swap, void *context) {
if (cmd->cmd == LC_UUID) {
struct uuid_command *uuid_cmd = (struct uuid_command *)context;
if (!walker->ReadBytes(uuid_cmd, sizeof(struct uuid_command), offset))
return false;
if (swap)
swap_uuid_command(uuid_cmd, NXHostByteOrder());
return false;
}
// Continue processing
return true;
}
// static
bool MachoID::IDWalkerCB(MachoWalker *walker, load_command *cmd, off_t offset,
bool swap, void *context) {
if (cmd->cmd == LC_ID_DYLIB) {
struct dylib_command *dylib_cmd = (struct dylib_command *)context;
if (!walker->ReadBytes(dylib_cmd, sizeof(struct dylib_command), offset))
return false;
if (swap)
swap_dylib_command(dylib_cmd, NXHostByteOrder());
return false;
}
// Continue processing
return true;
}
} // namespace MacFileUtilities
<|endoftext|> |
<commit_before>// Copyright (C) M.Golov 2016
#include <iostream>
#include <string>
#include <functional>
struct InputData { int value; };
struct TransformedData { double value; };
InputData produceFx() { return InputData{42}; }
TransformedData transformFx(InputData input) { return TransformedData{(double)input.value}; }
template<typename TResult, typename TInput, typename TMeta>
std::function<TResult(TInput)> getFinalizer(TMeta) {
throw std::runtime_error("getFinalizer must be specialized");
}
using MetaInfo = std::string;
template<typename TContent>
struct Meta {
using TMeta = MetaInfo;
TMeta meta;
TContent content;
template<typename TResult>
Meta<TResult> transform(std::function<TResult(TContent)> fx) {
return Meta<TResult>{meta, fx(content)};
}
template<typename TResult>
TResult finalize() {
const auto finalizer = getFinalizer<TResult, TContent, TMeta>(meta);
return finalizer(content);
}
};
Meta<InputData> producer() {
return Meta<InputData>{"meta", produceFx()};
}
struct Backend {
std::string finalize(MetaInfo info, TransformedData input) {
return std::string("[") + info + "]: " + std::to_string(input.value);
}
};
template<>
std::function<std::string(TransformedData)>
getFinalizer<std::string, TransformedData, Meta<TransformedData>::TMeta>(Meta<TransformedData>::TMeta meta) {
return [meta](TransformedData content){
return Backend().finalize(meta, content);
};
}
int main(int argc, char **argv)
{
Meta<InputData> input = producer();
Meta<TransformedData> transformed = input.transform<TransformedData>(transformFx);
std::string output = transformed.finalize<std::string>();
std::cout << "Output: " << output << "\n";
return 0;
}
<commit_msg>Added stateful Backend<commit_after>// Copyright (C) M.Golov 2016
#include <iostream>
#include <string>
#include <functional>
// Definition
template<typename TResult, typename TInput, typename TMeta>
std::function<TResult(TInput)> getFinalizer(TMeta) {
throw std::runtime_error("getFinalizer must be specialized");
}
using MetaInfo = std::string;
template<typename TContent>
struct Meta {
using TMeta = MetaInfo;
TMeta meta;
TContent content;
template<typename TResult>
Meta<TResult> transform(std::function<TResult(TContent)> fx) {
return Meta<TResult>{meta, fx(content)};
}
template<typename TResult>
TResult finalize() {
const auto finalizer = getFinalizer<TResult, TContent, TMeta>(meta);
return finalizer(content);
}
};
// Usage example
struct InputData { int value; };
struct TransformedData { double value; };
class Backend {
public:
explicit Backend(const std::string &id) : id(id) {}
Meta<InputData> addMeta(std::function<InputData()> fx) {
return Meta<InputData>{"meta", fx()};
}
std::string finalize(MetaInfo info, TransformedData input) {
return std::string("[") + id + ":" + info + "]: " + std::to_string(input.value);
}
private:
const std::string id;
};
template<>
std::function<std::string(TransformedData)>
getFinalizer<std::string, TransformedData, Meta<TransformedData>::TMeta>(Meta<TransformedData>::TMeta meta) {
return [meta](TransformedData content){
return Backend("xxx").finalize(meta, content);
};
}
TransformedData transformFx(InputData input) { return TransformedData{(double)input.value}; }
int main(int argc, char **argv)
{
Backend backend("id");
Meta<InputData> input = backend.addMeta([](){return InputData{42};});
Meta<TransformedData> transformed = input.transform<TransformedData>(transformFx);
std::string output = transformed.finalize<std::string>();
std::cout << "Output: " << output << "\n";
return 0;
}
<|endoftext|> |
<commit_before>/*
* C S O U N D
*
* L I C E N S E
*
* This software is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "CppSound.hpp"
#include "Lindenmayer.hpp"
#include <iostream>
#include <iomanip>
#include <boost/format.hpp>
#include <sstream>
#if defined(HAVE_IO_H)
#include <io.h>
#endif
#include <stdio.h>
using boost::format;
using boost::io::group;
namespace csound
{
Lindenmayer::Lindenmayer() : angle(1.0)
{
}
Lindenmayer::~Lindenmayer()
{
}
std::string Lindenmayer::getReplacement(std::string word)
{
if(rules.find(word) == rules.end())
{
return word;
}
else
{
return rules[word];
}
}
void Lindenmayer::generate()
{
std::string word;
std::string replacement;
std::ifstream inputStream;
std::ofstream outputStream;
std::string inputFilename = "a.lindenmayer";
std::string outputFilename = "b.lindenmayer";
std::string tempFilename;
outputStream.open(outputFilename.c_str());
outputStream << axiom.c_str() << std::endl;
outputStream.close();
for(int i = 0; i < iterationCount; i++)
{
std::ifstream inputStream;
std::ofstream outputStream;
tempFilename = inputFilename;
inputFilename = outputFilename;
outputFilename = tempFilename;
unlink(outputFilename.c_str());
inputStream.open(inputFilename.c_str());
inputStream.seekg(0, std::ios_base::beg);
outputStream.open(outputFilename.c_str());
while(!inputStream.eof())
{
inputStream >> word;
inputStream >> std::ws;
replacement = getReplacement(word);
outputStream << replacement << std::endl;
}
inputStream.close();
outputStream.close();
}
score.scaleActualMinima = turtle;
score.scaleActualRanges = turtle;
initialize();
inputStream.open(inputFilename.c_str());
while(!inputStream.eof())
{
inputStream >> word;
interpret(word, false);
}
initialize();
inputStream.close();
std::ifstream finalInputStream(inputFilename.c_str());
while(!finalInputStream.eof())
{
finalInputStream >> word;
//std::cerr << word << std::endl;
interpret(word, true);
}
finalInputStream.close();
for(std::vector<Event>::iterator i = score.begin(); i != score.end(); ++i)
{
Event &event = *i;
event.setStatus(MidiFile::CHANNEL_NOTE_ON);
}
}
void Lindenmayer::initialize()
{
turtle = csound::Event();
turtleStep = csound::Event();
for(size_t i = 0; i < Event::HOMOGENEITY; i++)
{
turtleStep[i] = 1.0;
}
turtleOrientation = csound::Event();
turtleOrientation[Event::TIME] = 1.0;
}
void Lindenmayer::interpret(std::string action, bool render)
{
try
{
action = Conversions::trim(action);
char command = action[0];
switch(command)
{
case 'N':
{
// N
// 0
if(render)
{
Event event = turtle;
//score.rescale(event);
score.push_back(event);
}
else
{
updateActual(turtle);
}
}
break;
case 'M':
{
// Mn
// 01
double a = 1.0;
if(action.length () > 1)
{
a = Conversions::stringToDouble(action.substr(1));
}
double step;
for (int i = 0; i < Event::HOMOGENEITY; i++)
{
step = turtle[i] + (turtleStep[i] * a * turtleOrientation[i]);
turtle[i] = step;
}
}
break;
case 'R':
{
// Rddn
// 0123
size_t d1 = getDimension(action[1]);
size_t d2 = getDimension(action[2]);
double n = 1.0;
if(action.length() > 3)
{
n = Conversions::stringToDouble(action.substr(3));
}
double a = angle * n;
ublas::matrix<double> rotation = createRotation (d1, d2, a);
std::cerr << "Orientation before rotation: " << std::endl;
for (int i = 0; i < turtleOrientation.size(); i++)
{
std::cerr << format("%9.3f ") % turtleOrientation(i);
}
std::cerr << std::endl;
std::cerr << "Rotation for angle " << a << ":" << std::endl;
for (int i = 0; i < rotation.size1(); i++)
{
for (int j = 0; j < rotation.size2(); j++ )
{
std::cerr << format("%9.3f ") % rotation(i, j);
}
std::cerr << std::endl;
}
turtleOrientation = ublas::prod(rotation, turtleOrientation);
std::cerr << "Orientation after rotation: " << std::endl;
for (int i = 0; i < turtleOrientation.size(); i++)
{
std::cerr << format("%9.3f ") % turtleOrientation(i);
}
std::cerr << std::endl;
std::cerr << std::endl;
}
break;
case 'T':
{
// Tdon
// 0123
size_t dimension = getDimension(action[1]);
char operation = action[2];
double n = 1.0;
if(action.length() > 3)
{
n = Conversions::stringToDouble(action.substr(3));
}
switch(operation)
{
case '=':
turtle[dimension] = (turtleStep[dimension] * n);
break;
case '*':
turtle[dimension] = (turtle[dimension] * (turtleStep[dimension] * n));
break;
case '/':
turtle[dimension] = (turtle[dimension] / (turtleStep[dimension] * n));
break;
case '+':
turtle[dimension] = (turtle[dimension] + (turtleStep[dimension] * n));
break;
case '-':
turtle[dimension] = (turtle[dimension] - (turtleStep[dimension] * n));
break;
}
if(dimension == Event::PITCHES)
{
turtle[dimension] = Conversions::modulus(turtle[dimension], 4096.0);
}
}
break;
case 'S':
{
// Sdon
// 0123
size_t dimension = getDimension(action[1]);
char operation = action[2];
double n = 1.0;
if(action.length() > 3)
{
n = Conversions::stringToDouble(action.substr(3));
}
switch(operation)
{
case '=':
turtleStep[dimension] = n;
break;
case '*':
turtleStep[dimension] = (turtleStep[dimension] * n);
break;
case '/':
turtleStep[dimension] = (turtleStep[dimension] / n);
break;
case '+':
turtleStep[dimension] = (turtleStep[dimension] + n);
break;
case '-':
turtleStep[dimension] = (turtleStep[dimension] - n);
break;
}
//std::cerr << "step for " << dimension << " = " << turtleStep[dimension] << std::endl;
if(dimension == Event::PITCHES)
{
turtle[dimension] = Conversions::modulus(turtle[dimension], 4096.0);
}
}
break;
case '[':
{
Event a = turtle;
turtleStack.push(a);
Event b = turtleStep;
turtleStepStack.push(b);
Event c = turtleOrientation;
turtleOrientationStack.push(c);
}
break;
case ']':
{
turtle = turtleStack.top();
turtleStack.pop();
turtleStep = turtleStepStack.top();
turtleStepStack.pop();
turtleOrientation = turtleOrientationStack.top();
turtleOrientationStack.pop();
}
break;
}
}
catch(void *x)
{
std::cout << x << std::endl;
}
}
int Lindenmayer::getDimension (char dimension) const
{
switch(dimension)
{
case 'i': return Event::INSTRUMENT;
case 't': return Event::TIME;
case 'd': return Event::DURATION;
case 'k': return Event::KEY;
case 'v': return Event::VELOCITY;
case 'p': return Event::PHASE;
case 'x': return Event::PAN;
case 'y': return Event::HEIGHT;
case 'z': return Event::DEPTH;
case 's': return Event::PITCHES;
}
return -1;
}
ublas::matrix<double> Lindenmayer::createRotation (int dimension1, int dimension2, double angle) const
{
ublas::matrix<double> rotation_ = ublas::identity_matrix<double>(Event::ELEMENT_COUNT);
rotation_(dimension1,dimension1) = std::cos(angle);
rotation_(dimension1,dimension2) = -std::sin(angle);
rotation_(dimension2,dimension1) = std::sin(angle);
rotation_(dimension2,dimension2) = std::cos(angle);
return rotation_;
}
void Lindenmayer::updateActual(Event &event)
{
for(int i = 0, n = event.size(); i < n; i++)
{
if(score.scaleActualMinima[i] < event[i])
{
score.scaleActualMinima[i] = event[i];
}
if(score.scaleActualRanges[i] >= (score.scaleActualMinima[i] + event[i]))
{
score.scaleActualRanges[i] = (score.scaleActualMinima[i] + event[i]);
}
}
}
void Lindenmayer::rewrite()
{
System::inform("BEGAN Lindenmayer::rewrite()...");
std::stringstream production(axiom);
std::stringstream priorProduction;
std::string symbol;
std::string replacement;
for (int i = 0; i < iterationCount; i++)
{
priorProduction.clear();
priorProduction << production.str();
production.clear();
while (!priorProduction.eof())
{
priorProduction >> symbol;
if(rules.find(symbol) == rules.end())
{
replacement = symbol;
}
else
{
replacement = rules[symbol];
}
production << replacement;
}
}
System::inform("ENDED Lindenmayer::rewrite().");
}
double Lindenmayer::getAngle() const
{
return angle;
}
void Lindenmayer::setAngle(double angle)
{
this->angle = angle;
}
std::string Lindenmayer::getAxiom() const
{
return axiom;
}
void Lindenmayer::setAxiom(std::string axiom)
{
this->axiom = axiom;
}
void Lindenmayer::addRule(std::string command, std::string replacement)
{
rules[command] = replacement;
}
int Lindenmayer::getIterationCount() const
{
return iterationCount;
}
void Lindenmayer::setIterationCount(int count)
{
iterationCount = count;
}
void Lindenmayer::clear()
{
initialize();
rules.clear();
while(!turtleStack.empty())
{
turtleStack.pop();
}
while(!turtleStepStack.empty())
{
turtleStepStack.pop();
}
while(!turtleOrientationStack.empty())
{
turtleOrientationStack.pop();
}
}
}
<commit_msg>Fixed loop iterator types.<commit_after>/*
* C S O U N D
*
* L I C E N S E
*
* This software is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "CppSound.hpp"
#include "Lindenmayer.hpp"
#include <iostream>
#include <iomanip>
#include <boost/format.hpp>
#include <sstream>
#if defined(HAVE_IO_H)
#include <io.h>
#endif
#include <stdio.h>
using boost::format;
using boost::io::group;
namespace csound
{
Lindenmayer::Lindenmayer() : angle(1.0)
{
}
Lindenmayer::~Lindenmayer()
{
}
std::string Lindenmayer::getReplacement(std::string word)
{
if(rules.find(word) == rules.end())
{
return word;
}
else
{
return rules[word];
}
}
void Lindenmayer::generate()
{
std::string word;
std::string replacement;
std::ifstream inputStream;
std::ofstream outputStream;
std::string inputFilename = "a.lindenmayer";
std::string outputFilename = "b.lindenmayer";
std::string tempFilename;
outputStream.open(outputFilename.c_str());
outputStream << axiom.c_str() << std::endl;
outputStream.close();
for(int i = 0; i < iterationCount; i++)
{
std::ifstream inputStream;
std::ofstream outputStream;
tempFilename = inputFilename;
inputFilename = outputFilename;
outputFilename = tempFilename;
unlink(outputFilename.c_str());
inputStream.open(inputFilename.c_str());
inputStream.seekg(0, std::ios_base::beg);
outputStream.open(outputFilename.c_str());
while(!inputStream.eof())
{
inputStream >> word;
inputStream >> std::ws;
replacement = getReplacement(word);
outputStream << replacement << std::endl;
}
inputStream.close();
outputStream.close();
}
score.scaleActualMinima = turtle;
score.scaleActualRanges = turtle;
initialize();
inputStream.open(inputFilename.c_str());
while(!inputStream.eof())
{
inputStream >> word;
interpret(word, false);
}
initialize();
inputStream.close();
std::ifstream finalInputStream(inputFilename.c_str());
while(!finalInputStream.eof())
{
finalInputStream >> word;
//std::cerr << word << std::endl;
interpret(word, true);
}
finalInputStream.close();
for(std::vector<Event>::iterator i = score.begin(); i != score.end(); ++i)
{
Event &event = *i;
event.setStatus(MidiFile::CHANNEL_NOTE_ON);
}
}
void Lindenmayer::initialize()
{
turtle = csound::Event();
turtleStep = csound::Event();
for(size_t i = 0; i < Event::HOMOGENEITY; i++)
{
turtleStep[i] = 1.0;
}
turtleOrientation = csound::Event();
turtleOrientation[Event::TIME] = 1.0;
}
void Lindenmayer::interpret(std::string action, bool render)
{
try
{
action = Conversions::trim(action);
char command = action[0];
switch(command)
{
case 'N':
{
// N
// 0
if(render)
{
Event event = turtle;
//score.rescale(event);
score.push_back(event);
}
else
{
updateActual(turtle);
}
}
break;
case 'M':
{
// Mn
// 01
double a = 1.0;
if(action.length () > 1)
{
a = Conversions::stringToDouble(action.substr(1));
}
double step;
for (int i = 0; i < Event::HOMOGENEITY; i++)
{
step = turtle[i] + (turtleStep[i] * a * turtleOrientation[i]);
turtle[i] = step;
}
}
break;
case 'R':
{
// Rddn
// 0123
size_t d1 = getDimension(action[1]);
size_t d2 = getDimension(action[2]);
double n = 1.0;
if(action.length() > 3)
{
n = Conversions::stringToDouble(action.substr(3));
}
double a = angle * n;
ublas::matrix<double> rotation = createRotation (d1, d2, a);
std::cerr << "Orientation before rotation: " << std::endl;
for (size_t i = 0; i < turtleOrientation.size(); i++)
{
std::cerr << format("%9.3f ") % turtleOrientation(i);
}
std::cerr << std::endl;
std::cerr << "Rotation for angle " << a << ":" << std::endl;
for (size_t i = 0; i < rotation.size1(); i++)
{
for (size_t j = 0; j < rotation.size2(); j++ )
{
std::cerr << format("%9.3f ") % rotation(i, j);
}
std::cerr << std::endl;
}
turtleOrientation = ublas::prod(rotation, turtleOrientation);
std::cerr << "Orientation after rotation: " << std::endl;
for (size_t i = 0; i < turtleOrientation.size(); i++)
{
std::cerr << format("%9.3f ") % turtleOrientation(i);
}
std::cerr << std::endl;
std::cerr << std::endl;
}
break;
case 'T':
{
// Tdon
// 0123
size_t dimension = getDimension(action[1]);
char operation = action[2];
double n = 1.0;
if(action.length() > 3)
{
n = Conversions::stringToDouble(action.substr(3));
}
switch(operation)
{
case '=':
turtle[dimension] = (turtleStep[dimension] * n);
break;
case '*':
turtle[dimension] = (turtle[dimension] * (turtleStep[dimension] * n));
break;
case '/':
turtle[dimension] = (turtle[dimension] / (turtleStep[dimension] * n));
break;
case '+':
turtle[dimension] = (turtle[dimension] + (turtleStep[dimension] * n));
break;
case '-':
turtle[dimension] = (turtle[dimension] - (turtleStep[dimension] * n));
break;
}
if(dimension == Event::PITCHES)
{
turtle[dimension] = Conversions::modulus(turtle[dimension], 4096.0);
}
}
break;
case 'S':
{
// Sdon
// 0123
size_t dimension = getDimension(action[1]);
char operation = action[2];
double n = 1.0;
if(action.length() > 3)
{
n = Conversions::stringToDouble(action.substr(3));
}
switch(operation)
{
case '=':
turtleStep[dimension] = n;
break;
case '*':
turtleStep[dimension] = (turtleStep[dimension] * n);
break;
case '/':
turtleStep[dimension] = (turtleStep[dimension] / n);
break;
case '+':
turtleStep[dimension] = (turtleStep[dimension] + n);
break;
case '-':
turtleStep[dimension] = (turtleStep[dimension] - n);
break;
}
//std::cerr << "step for " << dimension << " = " << turtleStep[dimension] << std::endl;
if(dimension == Event::PITCHES)
{
turtle[dimension] = Conversions::modulus(turtle[dimension], 4096.0);
}
}
break;
case '[':
{
Event a = turtle;
turtleStack.push(a);
Event b = turtleStep;
turtleStepStack.push(b);
Event c = turtleOrientation;
turtleOrientationStack.push(c);
}
break;
case ']':
{
turtle = turtleStack.top();
turtleStack.pop();
turtleStep = turtleStepStack.top();
turtleStepStack.pop();
turtleOrientation = turtleOrientationStack.top();
turtleOrientationStack.pop();
}
break;
}
}
catch(void *x)
{
std::cout << x << std::endl;
}
}
int Lindenmayer::getDimension (char dimension) const
{
switch(dimension)
{
case 'i': return Event::INSTRUMENT;
case 't': return Event::TIME;
case 'd': return Event::DURATION;
case 'k': return Event::KEY;
case 'v': return Event::VELOCITY;
case 'p': return Event::PHASE;
case 'x': return Event::PAN;
case 'y': return Event::HEIGHT;
case 'z': return Event::DEPTH;
case 's': return Event::PITCHES;
}
return -1;
}
ublas::matrix<double> Lindenmayer::createRotation (int dimension1, int dimension2, double angle) const
{
ublas::matrix<double> rotation_ = ublas::identity_matrix<double>(Event::ELEMENT_COUNT);
rotation_(dimension1,dimension1) = std::cos(angle);
rotation_(dimension1,dimension2) = -std::sin(angle);
rotation_(dimension2,dimension1) = std::sin(angle);
rotation_(dimension2,dimension2) = std::cos(angle);
return rotation_;
}
void Lindenmayer::updateActual(Event &event)
{
for(int i = 0, n = event.size(); i < n; i++)
{
if(score.scaleActualMinima[i] < event[i])
{
score.scaleActualMinima[i] = event[i];
}
if(score.scaleActualRanges[i] >= (score.scaleActualMinima[i] + event[i]))
{
score.scaleActualRanges[i] = (score.scaleActualMinima[i] + event[i]);
}
}
}
void Lindenmayer::rewrite()
{
System::inform("BEGAN Lindenmayer::rewrite()...");
std::stringstream production(axiom);
std::stringstream priorProduction;
std::string symbol;
std::string replacement;
for (int i = 0; i < iterationCount; i++)
{
priorProduction.clear();
priorProduction << production.str();
production.clear();
while (!priorProduction.eof())
{
priorProduction >> symbol;
if(rules.find(symbol) == rules.end())
{
replacement = symbol;
}
else
{
replacement = rules[symbol];
}
production << replacement;
}
}
System::inform("ENDED Lindenmayer::rewrite().");
}
double Lindenmayer::getAngle() const
{
return angle;
}
void Lindenmayer::setAngle(double angle)
{
this->angle = angle;
}
std::string Lindenmayer::getAxiom() const
{
return axiom;
}
void Lindenmayer::setAxiom(std::string axiom)
{
this->axiom = axiom;
}
void Lindenmayer::addRule(std::string command, std::string replacement)
{
rules[command] = replacement;
}
int Lindenmayer::getIterationCount() const
{
return iterationCount;
}
void Lindenmayer::setIterationCount(int count)
{
iterationCount = count;
}
void Lindenmayer::clear()
{
initialize();
rules.clear();
while(!turtleStack.empty())
{
turtleStack.pop();
}
while(!turtleStepStack.empty())
{
turtleStepStack.pop();
}
while(!turtleOrientationStack.empty())
{
turtleOrientationStack.pop();
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
namespace {
static const FilePath::CharType kBaseUrl[] =
FILE_PATH_LITERAL("http://localhost:8000/");
static const FilePath::CharType kTestDirectory[] =
FILE_PATH_LITERAL("dom_checker/");
static const FilePath::CharType kStartFile[] =
FILE_PATH_LITERAL("dom_checker.html");
const wchar_t kRunDomCheckerTest[] = L"run-dom-checker-test";
class DomCheckerTest : public UITest {
public:
typedef std::list<std::string> ResultsList;
typedef std::set<std::string> ResultsSet;
DomCheckerTest() {
dom_automation_enabled_ = true;
enable_file_cookies_ = false;
show_window_ = true;
launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
}
void RunTest(bool use_http, ResultsList* new_passes,
ResultsList* new_failures) {
int test_count = 0;
ResultsSet expected_failures, current_failures;
std::string failures_file = use_http ?
"expected_failures-http.txt" : "expected_failures-file.txt";
GetExpectedFailures(failures_file, &expected_failures);
RunDomChecker(use_http, &test_count, ¤t_failures);
printf("\nTests run: %d\n", test_count);
// Compute the list of new passes and failures.
CompareSets(current_failures, expected_failures, new_passes);
CompareSets(expected_failures, current_failures, new_failures);
}
void PrintResults(const ResultsList& new_passes,
const ResultsList& new_failures) {
PrintResults(new_failures, "new tests failing", true);
PrintResults(new_passes, "new tests passing", false);
}
private:
void PrintResults(const ResultsList& results, const char* message,
bool add_failure) {
if (!results.empty()) {
if (add_failure)
ADD_FAILURE();
printf("%s:\n", message);
ResultsList::const_iterator it = results.begin();
for (; it != results.end(); ++it)
printf(" %s\n", it->c_str());
printf("\n");
}
}
// Find the elements of "b" that are not in "a".
void CompareSets(const ResultsSet& a, const ResultsSet& b,
ResultsList* only_in_b) {
ResultsSet::const_iterator it = b.begin();
for (; it != b.end(); ++it) {
if (a.find(*it) == a.end())
only_in_b->push_back(*it);
}
}
// Return the path to the DOM checker directory on the local filesystem.
FilePath GetDomCheckerDir() {
FilePath test_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
return test_dir.AppendASCII("dom_checker");
}
bool ReadExpectedResults(const std::string& failures_file,
std::string* results) {
FilePath results_path = GetDomCheckerDir();
results_path = results_path.AppendASCII(failures_file);
return file_util::ReadFileToString(results_path, results);
}
void ParseExpectedFailures(const std::string& input, ResultsSet* output) {
if (input.empty())
return;
std::vector<std::string> tokens;
SplitString(input, '\n', &tokens);
std::vector<std::string>::const_iterator it = tokens.begin();
for (; it != tokens.end(); ++it) {
// Allow comments (lines that start with #).
if (it->length() > 0 && it->at(0) != '#')
output->insert(*it);
}
}
void GetExpectedFailures(const std::string& failures_file,
ResultsSet* expected_failures) {
std::string expected_failures_text;
bool have_expected_results = ReadExpectedResults(failures_file,
&expected_failures_text);
ASSERT_TRUE(have_expected_results);
ParseExpectedFailures(expected_failures_text, expected_failures);
}
bool WaitUntilTestCompletes(TabProxy* tab) {
return WaitUntilJavaScriptCondition(tab, L"",
L"window.domAutomationController.send(automation.IsDone());",
1000, UITest::test_timeout_ms());
}
bool GetTestCount(TabProxy* tab, int* test_count) {
return tab->ExecuteAndExtractInt(L"",
L"window.domAutomationController.send(automation.GetTestCount());",
test_count);
}
bool GetTestsFailed(TabProxy* tab, ResultsSet* tests_failed) {
std::wstring json_wide;
bool succeeded = tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L" JSON.stringify(automation.GetFailures()));",
&json_wide);
// Note that we don't use ASSERT_TRUE here (and in some other places) as it
// doesn't work inside a function with a return type other than void.
EXPECT_TRUE(succeeded);
if (!succeeded)
return false;
std::string json = WideToUTF8(json_wide);
JSONStringValueSerializer deserializer(json);
scoped_ptr<Value> value(deserializer.Deserialize(NULL));
EXPECT_TRUE(value.get());
if (!value.get())
return false;
EXPECT_TRUE(value->IsType(Value::TYPE_LIST));
if (!value->IsType(Value::TYPE_LIST))
return false;
ListValue* list_value = static_cast<ListValue*>(value.get());
// The parsed JSON object will be an array of strings, each of which is a
// test failure. Add those strings to the results set.
ListValue::const_iterator it = list_value->begin();
for (; it != list_value->end(); ++it) {
EXPECT_TRUE((*it)->IsType(Value::TYPE_STRING));
if ((*it)->IsType(Value::TYPE_STRING)) {
std::string test_name;
succeeded = (*it)->GetAsString(&test_name);
EXPECT_TRUE(succeeded);
if (succeeded)
tests_failed->insert(test_name);
}
}
return true;
}
void RunDomChecker(bool use_http, int* test_count, ResultsSet* tests_failed) {
GURL test_url;
FilePath::StringType start_file(kStartFile);
if (use_http) {
FilePath::StringType test_directory(kTestDirectory);
FilePath::StringType url_string(kBaseUrl);
url_string.append(test_directory);
url_string.append(start_file);
test_url = GURL(url_string);
} else {
FilePath test_path = GetDomCheckerDir();
test_path = test_path.Append(start_file);
test_url = net::FilePathToFileURL(test_path);
}
scoped_ptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilTestCompletes(tab.get()));
// Get the test results.
ASSERT_TRUE(GetTestCount(tab.get(), test_count));
ASSERT_TRUE(GetTestsFailed(tab.get(), tests_failed));
ASSERT_GT(*test_count, 0);
}
DISALLOW_COPY_AND_ASSIGN(DomCheckerTest);
};
} // namespace
TEST_F(DomCheckerTest, File) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(false, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
TEST_F(DomCheckerTest, Http) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(true, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
<commit_msg>Disable DomCheckerTest.Http. TBR=nsylvain Review URL: http://codereview.chromium.org/42670<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
namespace {
static const FilePath::CharType kBaseUrl[] =
FILE_PATH_LITERAL("http://localhost:8000/");
static const FilePath::CharType kTestDirectory[] =
FILE_PATH_LITERAL("dom_checker/");
static const FilePath::CharType kStartFile[] =
FILE_PATH_LITERAL("dom_checker.html");
const wchar_t kRunDomCheckerTest[] = L"run-dom-checker-test";
class DomCheckerTest : public UITest {
public:
typedef std::list<std::string> ResultsList;
typedef std::set<std::string> ResultsSet;
DomCheckerTest() {
dom_automation_enabled_ = true;
enable_file_cookies_ = false;
show_window_ = true;
launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
}
void RunTest(bool use_http, ResultsList* new_passes,
ResultsList* new_failures) {
int test_count = 0;
ResultsSet expected_failures, current_failures;
std::string failures_file = use_http ?
"expected_failures-http.txt" : "expected_failures-file.txt";
GetExpectedFailures(failures_file, &expected_failures);
RunDomChecker(use_http, &test_count, ¤t_failures);
printf("\nTests run: %d\n", test_count);
// Compute the list of new passes and failures.
CompareSets(current_failures, expected_failures, new_passes);
CompareSets(expected_failures, current_failures, new_failures);
}
void PrintResults(const ResultsList& new_passes,
const ResultsList& new_failures) {
PrintResults(new_failures, "new tests failing", true);
PrintResults(new_passes, "new tests passing", false);
}
private:
void PrintResults(const ResultsList& results, const char* message,
bool add_failure) {
if (!results.empty()) {
if (add_failure)
ADD_FAILURE();
printf("%s:\n", message);
ResultsList::const_iterator it = results.begin();
for (; it != results.end(); ++it)
printf(" %s\n", it->c_str());
printf("\n");
}
}
// Find the elements of "b" that are not in "a".
void CompareSets(const ResultsSet& a, const ResultsSet& b,
ResultsList* only_in_b) {
ResultsSet::const_iterator it = b.begin();
for (; it != b.end(); ++it) {
if (a.find(*it) == a.end())
only_in_b->push_back(*it);
}
}
// Return the path to the DOM checker directory on the local filesystem.
FilePath GetDomCheckerDir() {
FilePath test_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
return test_dir.AppendASCII("dom_checker");
}
bool ReadExpectedResults(const std::string& failures_file,
std::string* results) {
FilePath results_path = GetDomCheckerDir();
results_path = results_path.AppendASCII(failures_file);
return file_util::ReadFileToString(results_path, results);
}
void ParseExpectedFailures(const std::string& input, ResultsSet* output) {
if (input.empty())
return;
std::vector<std::string> tokens;
SplitString(input, '\n', &tokens);
std::vector<std::string>::const_iterator it = tokens.begin();
for (; it != tokens.end(); ++it) {
// Allow comments (lines that start with #).
if (it->length() > 0 && it->at(0) != '#')
output->insert(*it);
}
}
void GetExpectedFailures(const std::string& failures_file,
ResultsSet* expected_failures) {
std::string expected_failures_text;
bool have_expected_results = ReadExpectedResults(failures_file,
&expected_failures_text);
ASSERT_TRUE(have_expected_results);
ParseExpectedFailures(expected_failures_text, expected_failures);
}
bool WaitUntilTestCompletes(TabProxy* tab) {
return WaitUntilJavaScriptCondition(tab, L"",
L"window.domAutomationController.send(automation.IsDone());",
1000, UITest::test_timeout_ms());
}
bool GetTestCount(TabProxy* tab, int* test_count) {
return tab->ExecuteAndExtractInt(L"",
L"window.domAutomationController.send(automation.GetTestCount());",
test_count);
}
bool GetTestsFailed(TabProxy* tab, ResultsSet* tests_failed) {
std::wstring json_wide;
bool succeeded = tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L" JSON.stringify(automation.GetFailures()));",
&json_wide);
// Note that we don't use ASSERT_TRUE here (and in some other places) as it
// doesn't work inside a function with a return type other than void.
EXPECT_TRUE(succeeded);
if (!succeeded)
return false;
std::string json = WideToUTF8(json_wide);
JSONStringValueSerializer deserializer(json);
scoped_ptr<Value> value(deserializer.Deserialize(NULL));
EXPECT_TRUE(value.get());
if (!value.get())
return false;
EXPECT_TRUE(value->IsType(Value::TYPE_LIST));
if (!value->IsType(Value::TYPE_LIST))
return false;
ListValue* list_value = static_cast<ListValue*>(value.get());
// The parsed JSON object will be an array of strings, each of which is a
// test failure. Add those strings to the results set.
ListValue::const_iterator it = list_value->begin();
for (; it != list_value->end(); ++it) {
EXPECT_TRUE((*it)->IsType(Value::TYPE_STRING));
if ((*it)->IsType(Value::TYPE_STRING)) {
std::string test_name;
succeeded = (*it)->GetAsString(&test_name);
EXPECT_TRUE(succeeded);
if (succeeded)
tests_failed->insert(test_name);
}
}
return true;
}
void RunDomChecker(bool use_http, int* test_count, ResultsSet* tests_failed) {
GURL test_url;
FilePath::StringType start_file(kStartFile);
if (use_http) {
FilePath::StringType test_directory(kTestDirectory);
FilePath::StringType url_string(kBaseUrl);
url_string.append(test_directory);
url_string.append(start_file);
test_url = GURL(url_string);
} else {
FilePath test_path = GetDomCheckerDir();
test_path = test_path.Append(start_file);
test_url = net::FilePathToFileURL(test_path);
}
scoped_ptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilTestCompletes(tab.get()));
// Get the test results.
ASSERT_TRUE(GetTestCount(tab.get(), test_count));
ASSERT_TRUE(GetTestsFailed(tab.get(), tests_failed));
ASSERT_GT(*test_count, 0);
}
DISALLOW_COPY_AND_ASSIGN(DomCheckerTest);
};
} // namespace
TEST_F(DomCheckerTest, DISABLED_File) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(false, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
TEST_F(DomCheckerTest, DISABLED_Http) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(true, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
<|endoftext|> |
<commit_before>/**
* This file is part of Slideshow.
* Copyright (C) 2008 David Sveningsson <[email protected]>
*
* Slideshow is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Slideshow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Log.h"
#include "Exceptions.h"
#include <stdarg.h>
#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <time.h>
#include <libdaemon/daemon.h>
Log::Severity Log::_level = Info;
FILE* Log::_file = NULL;
void Log::initialize(const char* filename){
_file = fopen(filename, "a");
if ( !_file ){
fprintf(stderr, "Failed to open logfile '%s' ! Fatal error!\n", filename);
exit(1);
}
}
void Log::deinitialize(){
fclose(_file);
}
void Log::message(Severity severity, const char* fmt, ...){
va_list arg;
va_start(arg, fmt);
char buf[255];
char* line;
verify( vasprintf(&line, fmt, arg) >= 0 );
if ( severity >= _level ){
fprintf(stdout, "(%s) [%s] %s", severity_string(severity), timestring(buf, 255), line);
}
fprintf(_file, "(%s) [%s] %s", severity_string(severity), timestring(buf, 255), line);
free(line);
va_end(arg);
}
static Log::Severity last_severity;
void Log::message_begin(Severity severity){
last_severity = severity;
char buf[255];
timestring(buf, 255);
if ( severity >= _level ){
fprintf(stdout, "(%s) [%s] ", severity_string(severity), buf);
fflush(stdout);
}
fprintf(_file, "(%s) [%s] ", severity_string(severity), buf);
fflush(_file);
}
void Log::message_ex(const char* str){
if ( last_severity >= _level ){
fprintf(stdout, "%s", str);
fflush(stdout);
}
fprintf(_file, "%s", str);
fflush(_file);
}
void Log::message_ex_fmt(const char* fmt, ...){
va_list arg;
va_start(arg, fmt);
char* line;
verify( vasprintf(&line, fmt, arg) >= 0 );
if ( last_severity >= _level ){
fprintf(stdout, "%s", line);
fflush(stdout);
}
fprintf(_file, "%s", line);
fflush(_file);
free(line);
}
char* Log::timestring(char *buffer, int bufferlen) {
time_t t = time(NULL);
struct tm* nt;
#ifdef WIN32
nt = new struct tm;
localtime_s(nt, &t);
#else
nt = localtime(&t);
#endif
strftime(buffer, bufferlen, "%Y-%m-%d %H:%M:%S", nt);
#ifdef WIN32
delete nt;
#endif
return buffer;
}
const char* Log::severity_string(Severity severity){
switch ( severity ){
case Debug: return "DD";
case Verbose: return "--";
case Info: return " ";
case Warning: return "WW";
case Fatal: return "!!";
}
return NULL;
}
void Log::flush(){
fflush(stdout);
fflush(_file);
}
int Log::fileno(){
return _file->_fileno;
}
<commit_msg>Forgot to commit Log.cpp<commit_after>/**
* This file is part of Slideshow.
* Copyright (C) 2008 David Sveningsson <[email protected]>
*
* Slideshow is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Slideshow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Log.h"
#include "Exceptions.h"
#include <stdarg.h>
#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <time.h>
#include <libdaemon/daemon.h>
Log::Severity Log::_level = Info;
FILE* Log::_file = NULL;
void Log::initialize(const char* filename){
_file = fopen(filename, "a");
if ( !_file ){
fprintf(stderr, "Failed to open logfile '%s' ! Fatal error!\n", filename);
exit(1);
}
}
void Log::deinitialize(){
fclose(_file);
}
void Log::message(Severity severity, const char* fmt, ...){
va_list arg;
va_start(arg, fmt);
char buf[255];
char* line;
verify( vasprintf(&line, fmt, arg) >= 0 );
if ( severity >= _level ){
fprintf(stdout, "(%s) [%s] %s", severity_string(severity), timestring(buf, 255), line);
}
fprintf(_file, "(%s) [%s] %s", severity_string(severity), timestring(buf, 255), line);
free(line);
va_end(arg);
}
static Log::Severity last_severity;
void Log::message_begin(Severity severity){
last_severity = severity;
char buf[255];
timestring(buf, 255);
if ( severity >= _level ){
fprintf(stdout, "(%s) [%s] ", severity_string(severity), buf);
fflush(stdout);
}
fprintf(_file, "(%s) [%s] ", severity_string(severity), buf);
fflush(_file);
}
void Log::message_ex(const char* str){
if ( last_severity >= _level ){
fprintf(stdout, "%s", str);
fflush(stdout);
}
fprintf(_file, "%s", str);
fflush(_file);
}
void Log::message_ex_fmt(const char* fmt, ...){
va_list arg;
va_start(arg, fmt);
char* line;
verify( vasprintf(&line, fmt, arg) >= 0 );
if ( last_severity >= _level ){
fprintf(stdout, "%s", line);
fflush(stdout);
}
fprintf(_file, "%s", line);
fflush(_file);
free(line);
}
char* Log::timestring(char *buffer, int bufferlen) {
time_t t = time(NULL);
struct tm* nt;
#ifdef WIN32
nt = new struct tm;
localtime_s(nt, &t);
#else
nt = localtime(&t);
#endif
strftime(buffer, bufferlen, "%Y-%m-%d %H:%M:%S", nt);
#ifdef WIN32
delete nt;
#endif
return buffer;
}
const char* Log::severity_string(Severity severity){
switch ( severity ){
case Debug: return "DD";
case Verbose: return "--";
case Info: return " ";
case Warning: return "WW";
case Fatal: return "!!";
}
return NULL;
}
void Log::flush(){
fflush(stdout);
fflush(_file);
}
int Log::file_no(){
return _file->_fileno;
}
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_network.h"
#include "condor_config.h"
#include "condor_classad.h"
#include "condor_debug.h"
#include "condor_attributes.h"
#include "MyString.h"
#include "condor_commands.h"
#include "condor_io.h"
#include "daemon.h"
#include "condor_distribution.h"
#define NUM_ELEMENTS(_ary) (sizeof(_ary) / sizeof((_ary)[0]))
//------------------------------------------------------------------------
static int CalcTime(int,int,int);
static int TimeLine(const MyString& Name,int FromDate, int ToDate, int Res);
//------------------------------------------------------------------------
static void Usage(char* name)
{
fprintf(stderr, "Usage: %s [-f filename] [-orgformat] [-pool hostname] [-lastday | -lastweek | -lastmonth | -lasthours h | -from m d y [-to m d y]] {-resourcequery <name> | -resourcelist | -resgroupquery <name> | -resgrouplist | -userquery <name> | -userlist | -usergroupquery <name> | -usergrouplist | -ckptquery | -ckptlist}\n",name);
exit(1);
}
//------------------------------------------------------------------------
const int MinuteSec=60;
const int HourSec=MinuteSec*60;
const int DaySec=HourSec*24;
const int WeekSec=DaySec*7;
const int MonthSec=DaySec*30;
const int YearSec=DaySec*365;
//------------------------------------------------------------------------
/*
int GrpConvStr(char* InpStr, char* OutStr)
{
float T,Unclaimed, Matched, Claimed,Preempting,Owner;
if (sscanf(InpStr," %f %f %f %f %f %f",&T,&Unclaimed,&Matched,&Claimed,&Preempting,&Owner)!=6) return -1;
sprintf(OutStr,"%f\t%f\t%f\t%f\t%f\t%f\n",T,Unclaimed,Matched,Claimed,Preempting,Owner);
return 0;
}
*/
//------------------------------------------------------------------------
int ResConvStr(char* InpStr, char* OutStr)
{
float T,LoadAvg;
int KbdIdle;
unsigned int State;
if (sscanf(InpStr," %f %d %f %d",&T,&KbdIdle,&LoadAvg,&State)!=4) return -1;
const char *stateStr;
// Note: This should be kept in sync with condor_state.h, and with
// StartdScanFunc() of view_server.C, and with
// typedef enum ViewStates of view_server.h
const char* StateName[] = {
"UNCLAIMED",
"MATCHED",
"CLAIMED",
"PRE-EMPTING",
"OWNER",
"SHUTDOWN",
"DELETE",
"BACKFILL",
"DRAINED",
};
if (State <= NUM_ELEMENTS(StateName) ) {
stateStr = StateName[State-1];
} else {
stateStr = "UNKNOWN";
}
sprintf(OutStr,"%f\t%d\t%f\t%s\n",T,KbdIdle,LoadAvg,stateStr);
return 0;
}
//------------------------------------------------------------------------
int main(int argc, char* argv[]);
int main(int argc, char* argv[])
{
int Now=time(0);
int ToDate=Now;
int FromDate=ToDate-DaySec;
int Options=0;
int QueryType=-1;
MyString QueryArg;
MyString FileName;
MyString TimeFileName;
char* pool = NULL;
myDistro->Init( argc, argv );
for(int i=1; i<argc; i++) {
// Analyze date specifiers
if (strcmp(argv[i],"-lastday")==0) {
ToDate=Now;
FromDate=ToDate-DaySec;
}
else if (strcmp(argv[i],"-lastweek")==0) {
ToDate=Now;
FromDate=ToDate-WeekSec;
}
else if (strcmp(argv[i],"-lastmonth")==0) {
ToDate=Now;
FromDate=ToDate-MonthSec;
}
else if (strcmp(argv[i],"-lasthours")==0) {
if (argc-i<=1) Usage(argv[0]);
int hours=atoi(argv[i+1]);
ToDate=Now;
FromDate=ToDate-HourSec*hours;
i++;
}
else if (strcmp(argv[i],"-from")==0) {
if (argc-i<=3) Usage(argv[0]);
int month=atoi(argv[i+1]);
int day=atoi(argv[i+2]);
int year=atoi(argv[i+3]);
FromDate=CalcTime(month,day,year);
// printf("Date translation: %d/%d/%d = %d\n",month,day,year,FromDate);
i+=3;
}
else if (strcmp(argv[i],"-to")==0) {
if (argc-i<=3) Usage(argv[0]);
int month=atoi(argv[i+1]);
int day=atoi(argv[i+2]);
int year=atoi(argv[i+3]);
ToDate=CalcTime(month,day,year);
// printf("Date translation: %d/%d/%d = %d\n",month,day,year,ToDate);
i+=3;
}
// Query type
else if (strcmp(argv[i],"-resourcelist")==0) {
QueryType=QUERY_HIST_STARTD_LIST;
}
else if (strcmp(argv[i],"-resourcequery")==0) {
QueryType=QUERY_HIST_STARTD;
if (argc-i<=1) Usage(argv[0]);
QueryArg=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-resgrouplist")==0) {
QueryType=QUERY_HIST_GROUPS_LIST;
}
else if (strcmp(argv[i],"-resgroupquery")==0) {
QueryType=QUERY_HIST_GROUPS;
if (argc-i<=1) Usage(argv[0]);
QueryArg=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-userlist")==0) {
QueryType=QUERY_HIST_SUBMITTOR_LIST;
}
else if (strcmp(argv[i],"-userquery")==0) {
QueryType=QUERY_HIST_SUBMITTOR;
if (argc-i<=1) Usage(argv[0]);
QueryArg=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-usergrouplist")==0) {
QueryType=QUERY_HIST_SUBMITTORGROUPS_LIST;
}
else if (strcmp(argv[i],"-usergroupquery")==0) {
QueryType=QUERY_HIST_SUBMITTORGROUPS;
if (argc-i<=1) Usage(argv[0]);
QueryArg=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-ckptlist")==0) {
QueryType=QUERY_HIST_CKPTSRVR_LIST;
}
else if (strcmp(argv[i],"-ckptquery")==0) {
QueryType=QUERY_HIST_CKPTSRVR;
if (argc-i<=1) Usage(argv[0]);
QueryArg=argv[i+1];
i++;
}
// miscaleneous
else if (strcmp(argv[i],"-f")==0) {
if (argc-i<=1) Usage(argv[0]);
FileName=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-timedat")==0) {
if (argc-i<=1) Usage(argv[0]);
TimeFileName=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-orgformat")==0) {
Options=1;
}
else if (strcmp(argv[i],"-pool")==0) {
if (argc-i<=1) Usage(argv[0]);
pool=argv[i+1];
i++;
}
else {
Usage(argv[0]);
}
}
// Check validity or arguments
if (QueryType==-1 || FromDate<0 || FromDate>Now || ToDate<FromDate) Usage(argv[0]);
// if (ToDate>Now) ToDate=Now;
config();
Daemon view_host( DT_VIEW_COLLECTOR, 0, pool );
if( ! view_host.locate() ) {
fprintf( stderr, "%s: %s\n", argv[0], view_host.error() );
exit(1);
}
const int MaxLen=200;
char Line[MaxLen+1];
char* LinePtr=Line;
if (QueryArg.Length()>MaxLen) {
fprintf(stderr, "Command line argument is too long\n");
exit(1);
}
strcpy(LinePtr, QueryArg.Value());
if (TimeFileName.Length()>0) TimeLine(TimeFileName,FromDate,ToDate,10);
// Open the output file
FILE* outfile=stdout;
if (FileName.Length()>0) outfile=safe_fopen_wrapper_follow(FileName.Value(),"w");
if (outfile == NULL) {
fprintf( stderr, "Failed to open file %s\n", FileName.Value() );
exit( 1 );
}
int LineCount=0;
ReliSock sock;
bool connect_error = true;
do {
if (sock.connect((char*) view_host.addr(), 0)) {
connect_error = false;
break;
}
} while (view_host.nextValidCm() == true);
if (connect_error == true) {
fprintf( stderr, "failed to connect to the CondorView server (%s)\n",
view_host.fullHostname() );
fputs("No Data.\n",outfile);
exit(1);
}
view_host.startCommand(QueryType, &sock);
sock.encode();
if (!sock.code(FromDate) ||
!sock.code(ToDate) ||
!sock.code(Options) ||
!sock.code(LinePtr) ||
!sock.end_of_message()) {
fprintf( stderr, "failed to send query to the CondorView server %s\n",
view_host.fullHostname() );
fputs("No Data.\n",outfile);
exit(1);
}
char NewStr[200];
sock.decode();
while(1) {
if (!sock.get(LinePtr,MaxLen)) {
fprintf(stderr, "failed to receive data from the CondorView server %s\n",
view_host.fullHostname());
if (LineCount==0) fputs("No Data.\n",outfile);
exit(1);
}
if (strlen(LinePtr)==0) break;
LineCount++;
if (Options==0 && QueryType==QUERY_HIST_STARTD) {
ResConvStr(LinePtr,NewStr);
fputs(NewStr,outfile);
}
else {
fputs(LinePtr,outfile);
}
}
if (!sock.end_of_message()) {
fprintf(stderr, "failed to receive data from the CondorView server\n");
}
if (LineCount==0) fputs("No Data.\n",outfile);
if (FileName.Length()>0) fclose(outfile);
return 0;
}
int CalcTime(int month, int day, int year) {
struct tm time_str;
if (year<50) year+= 100; // If I ask for 1 1 00, I want 1 1 2000
if (year>1900) year-=1900;
time_str.tm_year=year;
time_str.tm_mon=month-1;
time_str.tm_mday=day;
time_str.tm_hour=0;
time_str.tm_min=0;
time_str.tm_sec=0;
time_str.tm_isdst=-1;
return mktime(&time_str);
}
int TimeLine(const MyString& TimeFileName,int FromDate, int ToDate, int Res)
{
double Interval=double(ToDate-FromDate)/double(Res);
float RelT;
time_t T;
FILE* TimeFile=safe_fopen_wrapper_follow(TimeFileName.Value(),"w");
if (!TimeFile) return -1;
for (int i=0; i<=Res; i++) {
T=(time_t)FromDate+((int)Interval*i);
RelT=float(100.0/Res)*i;
fprintf(TimeFile,"%.2f\t%s",RelT,asctime(localtime(&T)));
}
fclose(TimeFile);
return 0;
}
<commit_msg>Comment out currently-unused variable.<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_network.h"
#include "condor_config.h"
#include "condor_classad.h"
#include "condor_debug.h"
#include "condor_attributes.h"
#include "MyString.h"
#include "condor_commands.h"
#include "condor_io.h"
#include "daemon.h"
#include "condor_distribution.h"
#define NUM_ELEMENTS(_ary) (sizeof(_ary) / sizeof((_ary)[0]))
//------------------------------------------------------------------------
static int CalcTime(int,int,int);
static int TimeLine(const MyString& Name,int FromDate, int ToDate, int Res);
//------------------------------------------------------------------------
static void Usage(char* name)
{
fprintf(stderr, "Usage: %s [-f filename] [-orgformat] [-pool hostname] [-lastday | -lastweek | -lastmonth | -lasthours h | -from m d y [-to m d y]] {-resourcequery <name> | -resourcelist | -resgroupquery <name> | -resgrouplist | -userquery <name> | -userlist | -usergroupquery <name> | -usergrouplist | -ckptquery | -ckptlist}\n",name);
exit(1);
}
//------------------------------------------------------------------------
const int MinuteSec=60;
const int HourSec=MinuteSec*60;
const int DaySec=HourSec*24;
const int WeekSec=DaySec*7;
const int MonthSec=DaySec*30;
//const int YearSec=DaySec*365;
//------------------------------------------------------------------------
/*
int GrpConvStr(char* InpStr, char* OutStr)
{
float T,Unclaimed, Matched, Claimed,Preempting,Owner;
if (sscanf(InpStr," %f %f %f %f %f %f",&T,&Unclaimed,&Matched,&Claimed,&Preempting,&Owner)!=6) return -1;
sprintf(OutStr,"%f\t%f\t%f\t%f\t%f\t%f\n",T,Unclaimed,Matched,Claimed,Preempting,Owner);
return 0;
}
*/
//------------------------------------------------------------------------
int ResConvStr(char* InpStr, char* OutStr)
{
float T,LoadAvg;
int KbdIdle;
unsigned int State;
if (sscanf(InpStr," %f %d %f %d",&T,&KbdIdle,&LoadAvg,&State)!=4) return -1;
const char *stateStr;
// Note: This should be kept in sync with condor_state.h, and with
// StartdScanFunc() of view_server.C, and with
// typedef enum ViewStates of view_server.h
const char* StateName[] = {
"UNCLAIMED",
"MATCHED",
"CLAIMED",
"PRE-EMPTING",
"OWNER",
"SHUTDOWN",
"DELETE",
"BACKFILL",
"DRAINED",
};
if (State <= NUM_ELEMENTS(StateName) ) {
stateStr = StateName[State-1];
} else {
stateStr = "UNKNOWN";
}
sprintf(OutStr,"%f\t%d\t%f\t%s\n",T,KbdIdle,LoadAvg,stateStr);
return 0;
}
//------------------------------------------------------------------------
int main(int argc, char* argv[]);
int main(int argc, char* argv[])
{
int Now=time(0);
int ToDate=Now;
int FromDate=ToDate-DaySec;
int Options=0;
int QueryType=-1;
MyString QueryArg;
MyString FileName;
MyString TimeFileName;
char* pool = NULL;
myDistro->Init( argc, argv );
for(int i=1; i<argc; i++) {
// Analyze date specifiers
if (strcmp(argv[i],"-lastday")==0) {
ToDate=Now;
FromDate=ToDate-DaySec;
}
else if (strcmp(argv[i],"-lastweek")==0) {
ToDate=Now;
FromDate=ToDate-WeekSec;
}
else if (strcmp(argv[i],"-lastmonth")==0) {
ToDate=Now;
FromDate=ToDate-MonthSec;
}
else if (strcmp(argv[i],"-lasthours")==0) {
if (argc-i<=1) Usage(argv[0]);
int hours=atoi(argv[i+1]);
ToDate=Now;
FromDate=ToDate-HourSec*hours;
i++;
}
else if (strcmp(argv[i],"-from")==0) {
if (argc-i<=3) Usage(argv[0]);
int month=atoi(argv[i+1]);
int day=atoi(argv[i+2]);
int year=atoi(argv[i+3]);
FromDate=CalcTime(month,day,year);
// printf("Date translation: %d/%d/%d = %d\n",month,day,year,FromDate);
i+=3;
}
else if (strcmp(argv[i],"-to")==0) {
if (argc-i<=3) Usage(argv[0]);
int month=atoi(argv[i+1]);
int day=atoi(argv[i+2]);
int year=atoi(argv[i+3]);
ToDate=CalcTime(month,day,year);
// printf("Date translation: %d/%d/%d = %d\n",month,day,year,ToDate);
i+=3;
}
// Query type
else if (strcmp(argv[i],"-resourcelist")==0) {
QueryType=QUERY_HIST_STARTD_LIST;
}
else if (strcmp(argv[i],"-resourcequery")==0) {
QueryType=QUERY_HIST_STARTD;
if (argc-i<=1) Usage(argv[0]);
QueryArg=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-resgrouplist")==0) {
QueryType=QUERY_HIST_GROUPS_LIST;
}
else if (strcmp(argv[i],"-resgroupquery")==0) {
QueryType=QUERY_HIST_GROUPS;
if (argc-i<=1) Usage(argv[0]);
QueryArg=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-userlist")==0) {
QueryType=QUERY_HIST_SUBMITTOR_LIST;
}
else if (strcmp(argv[i],"-userquery")==0) {
QueryType=QUERY_HIST_SUBMITTOR;
if (argc-i<=1) Usage(argv[0]);
QueryArg=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-usergrouplist")==0) {
QueryType=QUERY_HIST_SUBMITTORGROUPS_LIST;
}
else if (strcmp(argv[i],"-usergroupquery")==0) {
QueryType=QUERY_HIST_SUBMITTORGROUPS;
if (argc-i<=1) Usage(argv[0]);
QueryArg=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-ckptlist")==0) {
QueryType=QUERY_HIST_CKPTSRVR_LIST;
}
else if (strcmp(argv[i],"-ckptquery")==0) {
QueryType=QUERY_HIST_CKPTSRVR;
if (argc-i<=1) Usage(argv[0]);
QueryArg=argv[i+1];
i++;
}
// miscaleneous
else if (strcmp(argv[i],"-f")==0) {
if (argc-i<=1) Usage(argv[0]);
FileName=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-timedat")==0) {
if (argc-i<=1) Usage(argv[0]);
TimeFileName=argv[i+1];
i++;
}
else if (strcmp(argv[i],"-orgformat")==0) {
Options=1;
}
else if (strcmp(argv[i],"-pool")==0) {
if (argc-i<=1) Usage(argv[0]);
pool=argv[i+1];
i++;
}
else {
Usage(argv[0]);
}
}
// Check validity or arguments
if (QueryType==-1 || FromDate<0 || FromDate>Now || ToDate<FromDate) Usage(argv[0]);
// if (ToDate>Now) ToDate=Now;
config();
Daemon view_host( DT_VIEW_COLLECTOR, 0, pool );
if( ! view_host.locate() ) {
fprintf( stderr, "%s: %s\n", argv[0], view_host.error() );
exit(1);
}
const int MaxLen=200;
char Line[MaxLen+1];
char* LinePtr=Line;
if (QueryArg.Length()>MaxLen) {
fprintf(stderr, "Command line argument is too long\n");
exit(1);
}
strcpy(LinePtr, QueryArg.Value());
if (TimeFileName.Length()>0) TimeLine(TimeFileName,FromDate,ToDate,10);
// Open the output file
FILE* outfile=stdout;
if (FileName.Length()>0) outfile=safe_fopen_wrapper_follow(FileName.Value(),"w");
if (outfile == NULL) {
fprintf( stderr, "Failed to open file %s\n", FileName.Value() );
exit( 1 );
}
int LineCount=0;
ReliSock sock;
bool connect_error = true;
do {
if (sock.connect((char*) view_host.addr(), 0)) {
connect_error = false;
break;
}
} while (view_host.nextValidCm() == true);
if (connect_error == true) {
fprintf( stderr, "failed to connect to the CondorView server (%s)\n",
view_host.fullHostname() );
fputs("No Data.\n",outfile);
exit(1);
}
view_host.startCommand(QueryType, &sock);
sock.encode();
if (!sock.code(FromDate) ||
!sock.code(ToDate) ||
!sock.code(Options) ||
!sock.code(LinePtr) ||
!sock.end_of_message()) {
fprintf( stderr, "failed to send query to the CondorView server %s\n",
view_host.fullHostname() );
fputs("No Data.\n",outfile);
exit(1);
}
char NewStr[200];
sock.decode();
while(1) {
if (!sock.get(LinePtr,MaxLen)) {
fprintf(stderr, "failed to receive data from the CondorView server %s\n",
view_host.fullHostname());
if (LineCount==0) fputs("No Data.\n",outfile);
exit(1);
}
if (strlen(LinePtr)==0) break;
LineCount++;
if (Options==0 && QueryType==QUERY_HIST_STARTD) {
ResConvStr(LinePtr,NewStr);
fputs(NewStr,outfile);
}
else {
fputs(LinePtr,outfile);
}
}
if (!sock.end_of_message()) {
fprintf(stderr, "failed to receive data from the CondorView server\n");
}
if (LineCount==0) fputs("No Data.\n",outfile);
if (FileName.Length()>0) fclose(outfile);
return 0;
}
int CalcTime(int month, int day, int year) {
struct tm time_str;
if (year<50) year+= 100; // If I ask for 1 1 00, I want 1 1 2000
if (year>1900) year-=1900;
time_str.tm_year=year;
time_str.tm_mon=month-1;
time_str.tm_mday=day;
time_str.tm_hour=0;
time_str.tm_min=0;
time_str.tm_sec=0;
time_str.tm_isdst=-1;
return mktime(&time_str);
}
int TimeLine(const MyString& TimeFileName,int FromDate, int ToDate, int Res)
{
double Interval=double(ToDate-FromDate)/double(Res);
float RelT;
time_t T;
FILE* TimeFile=safe_fopen_wrapper_follow(TimeFileName.Value(),"w");
if (!TimeFile) return -1;
for (int i=0; i<=Res; i++) {
T=(time_t)FromDate+((int)Interval*i);
RelT=float(100.0/Res)*i;
fprintf(TimeFile,"%.2f\t%s",RelT,asctime(localtime(&T)));
}
fclose(TimeFile);
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: helpdispatch.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-07 17:39:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "helpdispatch.hxx"
#include "sfxuno.hxx"
#include "newhelp.hxx"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XNOTIFYINGDISPATCH_HPP_
#include <com/sun/star/frame/XNotifyingDispatch.hpp>
#endif
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
// class HelpInterceptor_Impl --------------------------------------------
HelpDispatch_Impl::HelpDispatch_Impl( HelpInterceptor_Impl& _rInterceptor,
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatch >& _xDisp ) :
m_rInterceptor ( _rInterceptor ),
m_xRealDispatch ( _xDisp )
{
}
// -----------------------------------------------------------------------
HelpDispatch_Impl::~HelpDispatch_Impl()
{
}
// -----------------------------------------------------------------------
// XDispatch
void SAL_CALL HelpDispatch_Impl::dispatch(
const URL& aURL, const Sequence< PropertyValue >& aArgs ) throw( RuntimeException )
{
DBG_ASSERT( m_xRealDispatch.is(), "invalid dispatch" );
// search for a keyword (dispatch from the basic ide)
sal_Bool bHasKeyword = sal_False;
String sKeyword;
const PropertyValue* pBegin = aArgs.getConstArray();
const PropertyValue* pEnd = pBegin + aArgs.getLength();
for ( ; pBegin != pEnd; ++pBegin )
{
if ( 0 == ( *pBegin ).Name.compareToAscii( "HelpKeyword" ) )
{
rtl::OUString sHelpKeyword;
if ( ( ( *pBegin ).Value >>= sHelpKeyword ) && sHelpKeyword.getLength() > 0 )
{
sKeyword = String( sHelpKeyword );
bHasKeyword = ( sKeyword.Len() > 0 );
break;
}
}
}
// if a keyword was found, then open it
SfxHelpWindow_Impl* pHelpWin = m_rInterceptor.GetHelpWindow();
DBG_ASSERT( pHelpWin, "invalid HelpWindow" );
if ( bHasKeyword )
{
pHelpWin->OpenKeyword( sKeyword );
return;
}
pHelpWin->loadHelpContent(aURL.Complete);
}
// -----------------------------------------------------------------------
void SAL_CALL HelpDispatch_Impl::addStatusListener(
const Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException )
{
DBG_ASSERT( m_xRealDispatch.is(), "invalid dispatch" );
m_xRealDispatch->addStatusListener( xControl, aURL );
}
// -----------------------------------------------------------------------
void SAL_CALL HelpDispatch_Impl::removeStatusListener(
const Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException )
{
DBG_ASSERT( m_xRealDispatch.is(), "invalid dispatch" );
m_xRealDispatch->removeStatusListener( xControl, aURL );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.6.312); FILE MERGED 2006/09/01 17:38:23 kaib 1.6.312.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: helpdispatch.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-09-17 16:17:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include "helpdispatch.hxx"
#include "sfxuno.hxx"
#include "newhelp.hxx"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XNOTIFYINGDISPATCH_HPP_
#include <com/sun/star/frame/XNotifyingDispatch.hpp>
#endif
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
// class HelpInterceptor_Impl --------------------------------------------
HelpDispatch_Impl::HelpDispatch_Impl( HelpInterceptor_Impl& _rInterceptor,
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatch >& _xDisp ) :
m_rInterceptor ( _rInterceptor ),
m_xRealDispatch ( _xDisp )
{
}
// -----------------------------------------------------------------------
HelpDispatch_Impl::~HelpDispatch_Impl()
{
}
// -----------------------------------------------------------------------
// XDispatch
void SAL_CALL HelpDispatch_Impl::dispatch(
const URL& aURL, const Sequence< PropertyValue >& aArgs ) throw( RuntimeException )
{
DBG_ASSERT( m_xRealDispatch.is(), "invalid dispatch" );
// search for a keyword (dispatch from the basic ide)
sal_Bool bHasKeyword = sal_False;
String sKeyword;
const PropertyValue* pBegin = aArgs.getConstArray();
const PropertyValue* pEnd = pBegin + aArgs.getLength();
for ( ; pBegin != pEnd; ++pBegin )
{
if ( 0 == ( *pBegin ).Name.compareToAscii( "HelpKeyword" ) )
{
rtl::OUString sHelpKeyword;
if ( ( ( *pBegin ).Value >>= sHelpKeyword ) && sHelpKeyword.getLength() > 0 )
{
sKeyword = String( sHelpKeyword );
bHasKeyword = ( sKeyword.Len() > 0 );
break;
}
}
}
// if a keyword was found, then open it
SfxHelpWindow_Impl* pHelpWin = m_rInterceptor.GetHelpWindow();
DBG_ASSERT( pHelpWin, "invalid HelpWindow" );
if ( bHasKeyword )
{
pHelpWin->OpenKeyword( sKeyword );
return;
}
pHelpWin->loadHelpContent(aURL.Complete);
}
// -----------------------------------------------------------------------
void SAL_CALL HelpDispatch_Impl::addStatusListener(
const Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException )
{
DBG_ASSERT( m_xRealDispatch.is(), "invalid dispatch" );
m_xRealDispatch->addStatusListener( xControl, aURL );
}
// -----------------------------------------------------------------------
void SAL_CALL HelpDispatch_Impl::removeStatusListener(
const Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException )
{
DBG_ASSERT( m_xRealDispatch.is(), "invalid dispatch" );
m_xRealDispatch->removeStatusListener( xControl, aURL );
}
<|endoftext|> |
<commit_before>#include "leveldb_ext.h"
static void PyLevelDB_set_error(leveldb::Status& status)
{
extern PyObject* leveldb_exception;
PyErr_SetString(leveldb_exception, status.ToString().c_str());
}
const char leveldb_repair_db_doc[] =
"leveldb.RepairDB(db_dir)\n"
;
PyObject* leveldb_repair_db(PyObject* self, PyObject* args)
{
const char* db_dir = 0;
if (!PyArg_ParseTuple(args, "s", &db_dir))
return 0;
std::string _db_dir(db_dir);
leveldb::Status status;
leveldb::Options options;
Py_BEGIN_ALLOW_THREADS
status = leveldb::RepairDB(_db_dir.c_str(), options);
Py_END_ALLOW_THREADS
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static void PyLevelDB_dealloc(PyLevelDB* self)
{
if (self->db) {
Py_BEGIN_ALLOW_THREADS
delete self->db;
Py_END_ALLOW_THREADS
self->db = 0;
}
Py_TYPE(self)->tp_free(self);
}
static PyObject* PyLevelDB_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
PyLevelDB* self = (PyLevelDB*)type->tp_alloc(type, 0);
if (self) {
self->db = 0;
}
return (PyObject*)self;
}
static PyObject* PyLevelDB_Put(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
PyObject* sync = Py_False;
Py_buffer key, value;
static char* kwargs[] = {"key", "value", "sync", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*s*|O!", kwargs, &key, &value, &PyBool_Type, &sync))
return 0;
leveldb::Slice key_slice((const char*)key.buf, (size_t)key.len);
leveldb::Slice value_slice((const char*)value.buf, (size_t)value.len);
leveldb::WriteOptions options;
options.sync = (sync == Py_True) ? true : false;
leveldb::Status status;
Py_BEGIN_ALLOW_THREADS
status = self->db->Put(options, key_slice, value_slice);
Py_END_ALLOW_THREADS
PyBuffer_Release(&key);
PyBuffer_Release(&value);
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* PyLevelDB_Get(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
PyObject* verify_checksums = Py_False;
PyObject* fill_cache = Py_True;
Py_buffer key;
static char* kwargs[] = {"key", "verify_checksums", "fill_cache", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*|O!O!", kwargs, &key, &PyBool_Type, &verify_checksums, &PyBool_Type, &fill_cache))
return 0;
leveldb::Slice key_slice((const char*)key.buf, (size_t)key.len);
leveldb::ReadOptions options;
options.verify_checksums = (verify_checksums == Py_True) ? true : false;
options.fill_cache = (fill_cache == Py_True) ? true : false;
leveldb::Status status;
std::string value;
Py_BEGIN_ALLOW_THREADS
status = self->db->Get(options, key_slice, &value);
Py_END_ALLOW_THREADS
PyBuffer_Release(&key);
if (status.IsNotFound()) {
PyErr_SetNone(PyExc_KeyError);
return 0;
}
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
return PyString_FromStringAndSize(value.c_str(), value.length());
}
static PyMethodDef PyLevelDB_methods[] = {
{"Put", (PyCFunction)PyLevelDB_Put, METH_KEYWORDS, "add a key/value pair to database, with an optional synchronous disk write" },
{"Get", (PyCFunction)PyLevelDB_Get, METH_KEYWORDS, "get a value from the database" },
{NULL}
};
static int PyLevelDB_init(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
if (self->db) {
Py_BEGIN_ALLOW_THREADS
delete self->db;
Py_END_ALLOW_THREADS
self->db = 0;
}
const char* db_dir = 0;
PyObject* create_if_missing = Py_True;
static char* kwargs[] = {"filename", "create_if_missing", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O!", kwargs, &db_dir, &PyBool_Type, &create_if_missing))
return -1;
leveldb::Options options;
options.create_if_missing = (create_if_missing == Py_True) ? true : false;
leveldb::Status status;
// copy string parameter, since we might lose when we release the GIL
std::string _db_dir(db_dir);
Py_BEGIN_ALLOW_THREADS
status = leveldb::DB::Open(options, _db_dir, &self->db);
Py_END_ALLOW_THREADS
if (!status.ok()) {
PyLevelDB_set_error(status);
return -1;
}
return 0;
}
PyTypeObject PyLevelDBType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"leveldb.LevelDB", /*tp_name*/
sizeof(PyLevelDB), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)PyLevelDB_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
"PyLevelDB wrapper", /*tp_doc */
0, /*tp_traverse */
0, /*tp_clear */
0, /*tp_richcompare */
0, /*tp_weaklistoffset */
0, /*tp_iter */
0, /*tp_iternext */
PyLevelDB_methods, /*tp_methods */
0, /*tp_members */
0, /*tp_getset */
0, /*tp_base */
0, /*tp_dict */
0, /*tp_descr_get */
0, /*tp_descr_set */
0, /*tp_dictoffset */
(initproc)PyLevelDB_init, /*tp_init */
0, /*tp_alloc */
PyLevelDB_new, /*tp_new */
};
<commit_msg>a lot more options for db open<commit_after>#include "leveldb_ext.h"
static void PyLevelDB_set_error(leveldb::Status& status)
{
extern PyObject* leveldb_exception;
PyErr_SetString(leveldb_exception, status.ToString().c_str());
}
const char leveldb_repair_db_doc[] =
"leveldb.RepairDB(db_dir)\n"
;
PyObject* leveldb_repair_db(PyObject* self, PyObject* args)
{
const char* db_dir = 0;
if (!PyArg_ParseTuple(args, "s", &db_dir))
return 0;
std::string _db_dir(db_dir);
leveldb::Status status;
leveldb::Options options;
Py_BEGIN_ALLOW_THREADS
status = leveldb::RepairDB(_db_dir.c_str(), options);
Py_END_ALLOW_THREADS
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static void PyLevelDB_dealloc(PyLevelDB* self)
{
if (self->db) {
Py_BEGIN_ALLOW_THREADS
delete self->db;
Py_END_ALLOW_THREADS
self->db = 0;
}
Py_TYPE(self)->tp_free(self);
}
static PyObject* PyLevelDB_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
PyLevelDB* self = (PyLevelDB*)type->tp_alloc(type, 0);
if (self) {
self->db = 0;
}
return (PyObject*)self;
}
static PyObject* PyLevelDB_Put(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
PyObject* sync = Py_False;
Py_buffer key, value;
static char* kwargs[] = {"key", "value", "sync", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*s*|O!", kwargs, &key, &value, &PyBool_Type, &sync))
return 0;
leveldb::Slice key_slice((const char*)key.buf, (size_t)key.len);
leveldb::Slice value_slice((const char*)value.buf, (size_t)value.len);
leveldb::WriteOptions options;
options.sync = (sync == Py_True) ? true : false;
leveldb::Status status;
Py_BEGIN_ALLOW_THREADS
status = self->db->Put(options, key_slice, value_slice);
Py_END_ALLOW_THREADS
PyBuffer_Release(&key);
PyBuffer_Release(&value);
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* PyLevelDB_Get(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
PyObject* verify_checksums = Py_False;
PyObject* fill_cache = Py_True;
Py_buffer key;
static char* kwargs[] = {"key", "verify_checksums", "fill_cache", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*|O!O!", kwargs, &key, &PyBool_Type, &verify_checksums, &PyBool_Type, &fill_cache))
return 0;
leveldb::Slice key_slice((const char*)key.buf, (size_t)key.len);
leveldb::ReadOptions options;
options.verify_checksums = (verify_checksums == Py_True) ? true : false;
options.fill_cache = (fill_cache == Py_True) ? true : false;
leveldb::Status status;
std::string value;
Py_BEGIN_ALLOW_THREADS
status = self->db->Get(options, key_slice, &value);
Py_END_ALLOW_THREADS
PyBuffer_Release(&key);
if (status.IsNotFound()) {
PyErr_SetNone(PyExc_KeyError);
return 0;
}
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
return PyString_FromStringAndSize(value.c_str(), value.length());
}
static PyObject* PyLevelDB_Delete(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
PyObject* sync = Py_False;
Py_buffer key;
static char* kwargs[] = {"key", "sync", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*|O!", kwargs, &key, &PyBool_Type, &sync))
return 0;
leveldb::Slice key_slice((const char*)key.buf, (size_t)key.len);
leveldb::WriteOptions options;
options.sync = (sync == Py_True) ? true : false;
leveldb::Status status;
Py_BEGIN_ALLOW_THREADS
status = self->db->Delete(options, key_slice);
Py_END_ALLOW_THREADS
PyBuffer_Release(&key);
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef PyLevelDB_methods[] = {
{"Put", (PyCFunction)PyLevelDB_Put, METH_KEYWORDS, "add a key/value pair to database, with an optional synchronous disk write" },
{"Get", (PyCFunction)PyLevelDB_Get, METH_KEYWORDS, "get a value from the database" },
{"Delete", (PyCFunction)PyLevelDB_Delete, METH_KEYWORDS, "delete a value in the database" },
{NULL}
};
static int PyLevelDB_init(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
if (self->db) {
Py_BEGIN_ALLOW_THREADS
delete self->db;
Py_END_ALLOW_THREADS
self->db = 0;
}
const char* db_dir = 0;
PyObject* create_if_missing = Py_True;
PyObject* error_if_exists = Py_False;
PyObject* paranoid_checks = Py_False;
int write_buffer_size = 4<<20;
int block_size = 4096;
int max_open_files = 1000;
int block_restart_interval = 16;
static char* kwargs[] = {"filename", "create_if_missing", "error_if_exists", "paranoid_checks", "write_buffer_size", "block_size", "max_open_files", "block_restart_interval", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O!O!O!iiii", kwargs,
&db_dir,
&PyBool_Type, &create_if_missing,
&PyBool_Type, &error_if_exists,
&PyBool_Type, ¶noid_checks,
&write_buffer_size,
&block_size,
&max_open_files,
&block_restart_interval))
return -1;
if (write_buffer_size < 0 || block_size < 0 || max_open_files < 0 || block_restart_interval < 0) {
PyErr_SetString(PyExc_ValueError, "negative write_buffer_size/block_size/max_open_files/block_restart_interval");
return -1;
}
leveldb::Options options;
options.create_if_missing = (create_if_missing == Py_True) ? true : false;
options.error_if_exists = (error_if_exists == Py_True) ? true : false;
options.paranoid_checks = (paranoid_checks == Py_True) ? true : false;
options.write_buffer_size = write_buffer_size;
options.block_size = block_size;
options.max_open_files = max_open_files;
options.block_restart_interval = block_restart_interval;
options.compression = leveldb::kSnappyCompression;
leveldb::Status status;
// copy string parameter, since we might lose when we release the GIL
std::string _db_dir(db_dir);
Py_BEGIN_ALLOW_THREADS
status = leveldb::DB::Open(options, _db_dir, &self->db);
Py_END_ALLOW_THREADS
if (!status.ok()) {
PyLevelDB_set_error(status);
return -1;
}
return 0;
}
PyTypeObject PyLevelDBType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"leveldb.LevelDB", /*tp_name*/
sizeof(PyLevelDB), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)PyLevelDB_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
"PyLevelDB wrapper", /*tp_doc */
0, /*tp_traverse */
0, /*tp_clear */
0, /*tp_richcompare */
0, /*tp_weaklistoffset */
0, /*tp_iter */
0, /*tp_iternext */
PyLevelDB_methods, /*tp_methods */
0, /*tp_members */
0, /*tp_getset */
0, /*tp_base */
0, /*tp_dict */
0, /*tp_descr_get */
0, /*tp_descr_set */
0, /*tp_dictoffset */
(initproc)PyLevelDB_init, /*tp_init */
0, /*tp_alloc */
PyLevelDB_new, /*tp_new */
};
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
#include "sitkImageRegistrationMethod.h"
#include "itkConjugateGradientLineSearchOptimizerv4.h"
#include "itkGradientDescentOptimizerv4.h"
#include "itkRegularStepGradientDescentOptimizerv4.h"
#include "itkLBFGSBOptimizerv4.h"
#include "itkExhaustiveOptimizerv4.h"
#include "itkAmoebaOptimizerv4.h"
#include <itkPowellOptimizerv4.h>
#include "itkOnePlusOneEvolutionaryOptimizerv4.h"
#include "itkNormalVariateGenerator.h"
namespace {
template <typename T>
void UpdateWithBestValueExhaustive(itk::ExhaustiveOptimizerv4<T> *exhaustiveOptimizer,
double &outValue,
itk::TransformBase *outTransform)
{
outValue = exhaustiveOptimizer->GetMinimumMetricValue();
if (outTransform)
{
outTransform->SetParameters(exhaustiveOptimizer->GetMinimumMetricValuePosition());
}
}
struct PositionOptimizerCustomCast
{
template <typename T>
static std::vector<double> Helper(const T &value)
{ return std::vector<double>(value.begin(),value.end()); }
static std::vector<double> CustomCast(const itk::ObjectToObjectOptimizerBaseTemplate<double> *opt)
{
return Helper(opt->GetCurrentPosition());
}
};
}
namespace itk
{
namespace simple
{
template< typename TValue, typename TType>
itk::Array<TValue> sitkSTLVectorToITKArray( const std::vector< TType > & in )
{
itk::Array<TValue> out(in.size());
std::copy(in.begin(), in.end(), out.begin());
return out;
}
itk::ObjectToObjectOptimizerBaseTemplate<double>*
ImageRegistrationMethod::CreateOptimizer( unsigned int numberOfTransformParameters )
{
typedef double InternalComputationValueType;
if ( m_OptimizerType == ConjugateGradientLineSearch )
{
typedef itk::ConjugateGradientLineSearchOptimizerv4Template<InternalComputationValueType> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetLearningRate( this->m_OptimizerLearningRate );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetMinimumConvergenceValue( this->m_OptimizerConvergenceMinimumValue );
optimizer->SetConvergenceWindowSize( this->m_OptimizerConvergenceWindowSize );
optimizer->SetLowerLimit( this->m_OptimizerLineSearchLowerLimit);
optimizer->SetUpperLimit( this->m_OptimizerLineSearchUpperLimit);
optimizer->SetEpsilon( this->m_OptimizerLineSearchEpsilon);
optimizer->SetMaximumLineSearchIterations( this->m_OptimizerLineSearchMaximumIterations);
optimizer->SetDoEstimateLearningRateAtEachIteration( this->m_OptimizerEstimateLearningRate==EachIteration );
optimizer->SetDoEstimateLearningRateOnce( this->m_OptimizerEstimateLearningRate==Once );
optimizer->SetMaximumStepSizeInPhysicalUnits( this->m_OptimizerMaximumStepSizeInPhysicalUnits );
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetCurrentMetricValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
this->m_pfGetOptimizerLearningRate = nsstd::bind(&_OptimizerType::GetLearningRate,optimizer.GetPointer());
this->m_pfGetOptimizerConvergenceValue = nsstd::bind(&_OptimizerType::GetConvergenceValue,optimizer.GetPointer());
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
optimizer->Register();
return optimizer.GetPointer();
}
else if ( m_OptimizerType == GradientDescent )
{
typedef itk::GradientDescentOptimizerv4Template<InternalComputationValueType> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetLearningRate( this->m_OptimizerLearningRate );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetMinimumConvergenceValue( this->m_OptimizerConvergenceMinimumValue );
optimizer->SetConvergenceWindowSize( this->m_OptimizerConvergenceWindowSize );
optimizer->SetDoEstimateLearningRateAtEachIteration( this->m_OptimizerEstimateLearningRate==EachIteration );
optimizer->SetDoEstimateLearningRateOnce( this->m_OptimizerEstimateLearningRate==Once );
optimizer->SetMaximumStepSizeInPhysicalUnits( this->m_OptimizerMaximumStepSizeInPhysicalUnits );
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetCurrentMetricValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
this->m_pfGetOptimizerLearningRate = nsstd::bind(&_OptimizerType::GetLearningRate,optimizer.GetPointer());
this->m_pfGetOptimizerConvergenceValue = nsstd::bind(&_OptimizerType::GetConvergenceValue,optimizer.GetPointer());
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
optimizer->Register();
return optimizer.GetPointer();
}
else if ( m_OptimizerType == GradientDescentLineSearch )
{
typedef itk::GradientDescentLineSearchOptimizerv4Template<InternalComputationValueType> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetLearningRate( this->m_OptimizerLearningRate );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetMinimumConvergenceValue( this->m_OptimizerConvergenceMinimumValue );
optimizer->SetConvergenceWindowSize( this->m_OptimizerConvergenceWindowSize );
optimizer->SetLowerLimit( this->m_OptimizerLineSearchLowerLimit);
optimizer->SetUpperLimit( this->m_OptimizerLineSearchUpperLimit);
optimizer->SetEpsilon( this->m_OptimizerLineSearchEpsilon);
optimizer->SetMaximumLineSearchIterations( this->m_OptimizerLineSearchMaximumIterations);
optimizer->SetDoEstimateLearningRateAtEachIteration( this->m_OptimizerEstimateLearningRate==EachIteration );
optimizer->SetDoEstimateLearningRateOnce( this->m_OptimizerEstimateLearningRate==Once );
optimizer->SetMaximumStepSizeInPhysicalUnits( this->m_OptimizerMaximumStepSizeInPhysicalUnits );
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetCurrentMetricValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
this->m_pfGetOptimizerLearningRate = nsstd::bind(&_OptimizerType::GetLearningRate,optimizer.GetPointer());
this->m_pfGetOptimizerConvergenceValue = nsstd::bind(&_OptimizerType::GetConvergenceValue,optimizer.GetPointer());
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
optimizer->Register();
return optimizer.GetPointer();
}
else if ( m_OptimizerType == RegularStepGradientDescent )
{
typedef itk::RegularStepGradientDescentOptimizerv4<InternalComputationValueType> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetLearningRate( this->m_OptimizerLearningRate );
optimizer->SetMinimumStepLength( this->m_OptimizerMinimumStepLength );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetRelaxationFactor( this->m_OptimizerRelaxationFactor );
optimizer->SetGradientMagnitudeTolerance( this->m_OptimizerGradientMagnitudeTolerance );
optimizer->SetDoEstimateLearningRateAtEachIteration( this->m_OptimizerEstimateLearningRate==EachIteration );
optimizer->SetDoEstimateLearningRateOnce( this->m_OptimizerEstimateLearningRate==Once );
optimizer->SetMaximumStepSizeInPhysicalUnits( this->m_OptimizerMaximumStepSizeInPhysicalUnits );
optimizer->Register();
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetValue,optimizer);
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
this->m_pfGetOptimizerLearningRate = nsstd::bind(&_OptimizerType::GetLearningRate,optimizer.GetPointer());
this->m_pfGetOptimizerConvergenceValue = nsstd::bind(&_OptimizerType::GetConvergenceValue,optimizer.GetPointer());
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
return optimizer.GetPointer();
}
else if ( m_OptimizerType == LBFGSB )
{
typedef itk::LBFGSBOptimizerv4 _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetGradientConvergenceTolerance( this->m_OptimizerGradientConvergenceTolerance );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetMaximumNumberOfCorrections( this->m_OptimizerMaximumNumberOfCorrections );
optimizer->SetMaximumNumberOfFunctionEvaluations( this->m_OptimizerMaximumNumberOfFunctionEvaluations );
optimizer->SetCostFunctionConvergenceFactor( this->m_OptimizerCostFunctionConvergenceFactor );
#define NOBOUND 0 // 00
#define LOWERBOUND 1 // 01
#define UPPERBOUND 2 // 10
#define BOTHBOUND 3 // 11
unsigned char flag = NOBOUND;
const unsigned int sitkToITK[] = {0,1,3,2};
if ( this->m_OptimizerLowerBound != std::numeric_limits<double>::min() )
{
flag |= LOWERBOUND;
}
if ( this->m_OptimizerUpperBound != std::numeric_limits<double>::max() )
{
flag |= UPPERBOUND;
}
_OptimizerType::BoundSelectionType boundSelection( numberOfTransformParameters );
_OptimizerType::BoundValueType lowerBound( numberOfTransformParameters );
_OptimizerType::BoundValueType upperBound( numberOfTransformParameters );
boundSelection.Fill( sitkToITK[flag] );
lowerBound.Fill( this->m_OptimizerUpperBound );
upperBound.Fill( this->m_OptimizerUpperBound );
optimizer->SetBoundSelection( boundSelection );
optimizer->SetLowerBound( lowerBound );
optimizer->SetUpperBound( upperBound );
optimizer->SetTrace( m_OptimizerTrace );
optimizer->Register();
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
return optimizer.GetPointer();
}
else if ( m_OptimizerType == Exhaustive )
{
typedef itk::ExhaustiveOptimizerv4<double> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetStepLength( this->m_OptimizerStepLength );
optimizer->SetNumberOfSteps( sitkSTLVectorToITKArray<_OptimizerType::StepsType::ValueType>(this->m_OptimizerNumberOfSteps));
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetCurrentValue,optimizer);
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer);
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer);
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
this->m_pfUpdateWithBestValue = nsstd::bind(&UpdateWithBestValueExhaustive<double>,
optimizer,
this->m_MetricValue,
nsstd::placeholders::_1);
optimizer->Register();
return optimizer.GetPointer();
}
else if( m_OptimizerType == Amoeba )
{
typedef itk::AmoebaOptimizerv4 _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
_OptimizerType::ParametersType simplexDelta( numberOfTransformParameters );
simplexDelta.Fill( this->m_OptimizerSimplexDelta );
optimizer->SetInitialSimplexDelta( simplexDelta );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetParametersConvergenceTolerance(this->m_OptimizerParametersConvergenceTolerance);
optimizer->SetFunctionConvergenceTolerance(this->m_OptimizerFunctionConvergenceTolerance);
optimizer->SetOptimizeWithRestarts(this->m_OptimizerWithRestarts);
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetValue,optimizer);
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer);
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer);
optimizer->Register();
return optimizer.GetPointer();
}
else if ( m_OptimizerType == Powell )
{
typedef itk::PowellOptimizerv4<double> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetMaximumIteration( this->m_OptimizerNumberOfIterations );
optimizer->SetMaximumLineIteration( this->m_OptimizerMaximumLineIterations );
optimizer->SetStepLength(this->m_OptimizerStepLength );
optimizer->SetStepTolerance( this->m_OptimizerStepTolerance );
optimizer->SetValueTolerance( this->m_OptimizerValueTolerance );
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
optimizer->Register();
return optimizer.GetPointer();
}
else if ( m_OptimizerType == OnePlusOneEvolutionary )
{
typedef itk::OnePlusOneEvolutionaryOptimizerv4<double> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetMaximumIteration( this->m_OptimizerNumberOfIterations );
optimizer->SetEpsilon( this->m_OptimizerEpsilon );
optimizer->Initialize( this->m_OptimizerInitialRadius,
this->m_OptimizerGrowthFactor,
this->m_OptimizerShrinkFactor);
typedef itk::Statistics::NormalVariateGenerator GeneratorType;
GeneratorType::Pointer generator = GeneratorType::New();
generator->Initialize(12345);
optimizer->SetNormalVariateGenerator( generator );
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
this->m_pfGetOptimizerConvergenceValue = nsstd::bind(&_OptimizerType::GetFrobeniusNorm,optimizer.GetPointer());
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
optimizer->Register();
return optimizer.GetPointer();
}
else
{
sitkExceptionMacro("LogicError: Unexpected case!");
}
}
}
}
<commit_msg>Adding change in header order.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
#include "sitkImageRegistrationMethod.h"
#include "itkConjugateGradientLineSearchOptimizerv4.h"
#include "itkGradientDescentOptimizerv4.h"
#include "itkRegularStepGradientDescentOptimizerv4.h"
#include "itkLBFGSBOptimizerv4.h"
#include "itkOnePlusOneEvolutionaryOptimizerv4.h"
#include "itkNormalVariateGenerator.h"
#include "itkExhaustiveOptimizerv4.h"
#include "itkAmoebaOptimizerv4.h"
#include <itkPowellOptimizerv4.h>
namespace {
template <typename T>
void UpdateWithBestValueExhaustive(itk::ExhaustiveOptimizerv4<T> *exhaustiveOptimizer,
double &outValue,
itk::TransformBase *outTransform)
{
outValue = exhaustiveOptimizer->GetMinimumMetricValue();
if (outTransform)
{
outTransform->SetParameters(exhaustiveOptimizer->GetMinimumMetricValuePosition());
}
}
struct PositionOptimizerCustomCast
{
template <typename T>
static std::vector<double> Helper(const T &value)
{ return std::vector<double>(value.begin(),value.end()); }
static std::vector<double> CustomCast(const itk::ObjectToObjectOptimizerBaseTemplate<double> *opt)
{
return Helper(opt->GetCurrentPosition());
}
};
}
namespace itk
{
namespace simple
{
template< typename TValue, typename TType>
itk::Array<TValue> sitkSTLVectorToITKArray( const std::vector< TType > & in )
{
itk::Array<TValue> out(in.size());
std::copy(in.begin(), in.end(), out.begin());
return out;
}
itk::ObjectToObjectOptimizerBaseTemplate<double>*
ImageRegistrationMethod::CreateOptimizer( unsigned int numberOfTransformParameters )
{
typedef double InternalComputationValueType;
if ( m_OptimizerType == ConjugateGradientLineSearch )
{
typedef itk::ConjugateGradientLineSearchOptimizerv4Template<InternalComputationValueType> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetLearningRate( this->m_OptimizerLearningRate );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetMinimumConvergenceValue( this->m_OptimizerConvergenceMinimumValue );
optimizer->SetConvergenceWindowSize( this->m_OptimizerConvergenceWindowSize );
optimizer->SetLowerLimit( this->m_OptimizerLineSearchLowerLimit);
optimizer->SetUpperLimit( this->m_OptimizerLineSearchUpperLimit);
optimizer->SetEpsilon( this->m_OptimizerLineSearchEpsilon);
optimizer->SetMaximumLineSearchIterations( this->m_OptimizerLineSearchMaximumIterations);
optimizer->SetDoEstimateLearningRateAtEachIteration( this->m_OptimizerEstimateLearningRate==EachIteration );
optimizer->SetDoEstimateLearningRateOnce( this->m_OptimizerEstimateLearningRate==Once );
optimizer->SetMaximumStepSizeInPhysicalUnits( this->m_OptimizerMaximumStepSizeInPhysicalUnits );
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetCurrentMetricValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
this->m_pfGetOptimizerLearningRate = nsstd::bind(&_OptimizerType::GetLearningRate,optimizer.GetPointer());
this->m_pfGetOptimizerConvergenceValue = nsstd::bind(&_OptimizerType::GetConvergenceValue,optimizer.GetPointer());
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
optimizer->Register();
return optimizer.GetPointer();
}
else if ( m_OptimizerType == GradientDescent )
{
typedef itk::GradientDescentOptimizerv4Template<InternalComputationValueType> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetLearningRate( this->m_OptimizerLearningRate );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetMinimumConvergenceValue( this->m_OptimizerConvergenceMinimumValue );
optimizer->SetConvergenceWindowSize( this->m_OptimizerConvergenceWindowSize );
optimizer->SetDoEstimateLearningRateAtEachIteration( this->m_OptimizerEstimateLearningRate==EachIteration );
optimizer->SetDoEstimateLearningRateOnce( this->m_OptimizerEstimateLearningRate==Once );
optimizer->SetMaximumStepSizeInPhysicalUnits( this->m_OptimizerMaximumStepSizeInPhysicalUnits );
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetCurrentMetricValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
this->m_pfGetOptimizerLearningRate = nsstd::bind(&_OptimizerType::GetLearningRate,optimizer.GetPointer());
this->m_pfGetOptimizerConvergenceValue = nsstd::bind(&_OptimizerType::GetConvergenceValue,optimizer.GetPointer());
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
optimizer->Register();
return optimizer.GetPointer();
}
else if ( m_OptimizerType == GradientDescentLineSearch )
{
typedef itk::GradientDescentLineSearchOptimizerv4Template<InternalComputationValueType> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetLearningRate( this->m_OptimizerLearningRate );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetMinimumConvergenceValue( this->m_OptimizerConvergenceMinimumValue );
optimizer->SetConvergenceWindowSize( this->m_OptimizerConvergenceWindowSize );
optimizer->SetLowerLimit( this->m_OptimizerLineSearchLowerLimit);
optimizer->SetUpperLimit( this->m_OptimizerLineSearchUpperLimit);
optimizer->SetEpsilon( this->m_OptimizerLineSearchEpsilon);
optimizer->SetMaximumLineSearchIterations( this->m_OptimizerLineSearchMaximumIterations);
optimizer->SetDoEstimateLearningRateAtEachIteration( this->m_OptimizerEstimateLearningRate==EachIteration );
optimizer->SetDoEstimateLearningRateOnce( this->m_OptimizerEstimateLearningRate==Once );
optimizer->SetMaximumStepSizeInPhysicalUnits( this->m_OptimizerMaximumStepSizeInPhysicalUnits );
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetCurrentMetricValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
this->m_pfGetOptimizerLearningRate = nsstd::bind(&_OptimizerType::GetLearningRate,optimizer.GetPointer());
this->m_pfGetOptimizerConvergenceValue = nsstd::bind(&_OptimizerType::GetConvergenceValue,optimizer.GetPointer());
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
optimizer->Register();
return optimizer.GetPointer();
}
else if ( m_OptimizerType == RegularStepGradientDescent )
{
typedef itk::RegularStepGradientDescentOptimizerv4<InternalComputationValueType> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetLearningRate( this->m_OptimizerLearningRate );
optimizer->SetMinimumStepLength( this->m_OptimizerMinimumStepLength );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetRelaxationFactor( this->m_OptimizerRelaxationFactor );
optimizer->SetGradientMagnitudeTolerance( this->m_OptimizerGradientMagnitudeTolerance );
optimizer->SetDoEstimateLearningRateAtEachIteration( this->m_OptimizerEstimateLearningRate==EachIteration );
optimizer->SetDoEstimateLearningRateOnce( this->m_OptimizerEstimateLearningRate==Once );
optimizer->SetMaximumStepSizeInPhysicalUnits( this->m_OptimizerMaximumStepSizeInPhysicalUnits );
optimizer->Register();
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetValue,optimizer);
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
this->m_pfGetOptimizerLearningRate = nsstd::bind(&_OptimizerType::GetLearningRate,optimizer.GetPointer());
this->m_pfGetOptimizerConvergenceValue = nsstd::bind(&_OptimizerType::GetConvergenceValue,optimizer.GetPointer());
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
return optimizer.GetPointer();
}
else if ( m_OptimizerType == LBFGSB )
{
typedef itk::LBFGSBOptimizerv4 _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetGradientConvergenceTolerance( this->m_OptimizerGradientConvergenceTolerance );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetMaximumNumberOfCorrections( this->m_OptimizerMaximumNumberOfCorrections );
optimizer->SetMaximumNumberOfFunctionEvaluations( this->m_OptimizerMaximumNumberOfFunctionEvaluations );
optimizer->SetCostFunctionConvergenceFactor( this->m_OptimizerCostFunctionConvergenceFactor );
#define NOBOUND 0 // 00
#define LOWERBOUND 1 // 01
#define UPPERBOUND 2 // 10
#define BOTHBOUND 3 // 11
unsigned char flag = NOBOUND;
const unsigned int sitkToITK[] = {0,1,3,2};
if ( this->m_OptimizerLowerBound != std::numeric_limits<double>::min() )
{
flag |= LOWERBOUND;
}
if ( this->m_OptimizerUpperBound != std::numeric_limits<double>::max() )
{
flag |= UPPERBOUND;
}
_OptimizerType::BoundSelectionType boundSelection( numberOfTransformParameters );
_OptimizerType::BoundValueType lowerBound( numberOfTransformParameters );
_OptimizerType::BoundValueType upperBound( numberOfTransformParameters );
boundSelection.Fill( sitkToITK[flag] );
lowerBound.Fill( this->m_OptimizerUpperBound );
upperBound.Fill( this->m_OptimizerUpperBound );
optimizer->SetBoundSelection( boundSelection );
optimizer->SetLowerBound( lowerBound );
optimizer->SetUpperBound( upperBound );
optimizer->SetTrace( m_OptimizerTrace );
optimizer->Register();
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
return optimizer.GetPointer();
}
else if ( m_OptimizerType == Exhaustive )
{
typedef itk::ExhaustiveOptimizerv4<double> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetStepLength( this->m_OptimizerStepLength );
optimizer->SetNumberOfSteps( sitkSTLVectorToITKArray<_OptimizerType::StepsType::ValueType>(this->m_OptimizerNumberOfSteps));
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetCurrentValue,optimizer);
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer);
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer);
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
this->m_pfUpdateWithBestValue = nsstd::bind(&UpdateWithBestValueExhaustive<double>,
optimizer,
this->m_MetricValue,
nsstd::placeholders::_1);
optimizer->Register();
return optimizer.GetPointer();
}
else if( m_OptimizerType == Amoeba )
{
typedef itk::AmoebaOptimizerv4 _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
_OptimizerType::ParametersType simplexDelta( numberOfTransformParameters );
simplexDelta.Fill( this->m_OptimizerSimplexDelta );
optimizer->SetInitialSimplexDelta( simplexDelta );
optimizer->SetNumberOfIterations( this->m_OptimizerNumberOfIterations );
optimizer->SetParametersConvergenceTolerance(this->m_OptimizerParametersConvergenceTolerance);
optimizer->SetFunctionConvergenceTolerance(this->m_OptimizerFunctionConvergenceTolerance);
optimizer->SetOptimizeWithRestarts(this->m_OptimizerWithRestarts);
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetValue,optimizer);
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer);
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer);
optimizer->Register();
return optimizer.GetPointer();
}
else if ( m_OptimizerType == Powell )
{
typedef itk::PowellOptimizerv4<double> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetMaximumIteration( this->m_OptimizerNumberOfIterations );
optimizer->SetMaximumLineIteration( this->m_OptimizerMaximumLineIterations );
optimizer->SetStepLength(this->m_OptimizerStepLength );
optimizer->SetStepTolerance( this->m_OptimizerStepTolerance );
optimizer->SetValueTolerance( this->m_OptimizerValueTolerance );
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
optimizer->Register();
return optimizer.GetPointer();
}
else if ( m_OptimizerType == OnePlusOneEvolutionary )
{
typedef itk::OnePlusOneEvolutionaryOptimizerv4<double> _OptimizerType;
_OptimizerType::Pointer optimizer = _OptimizerType::New();
optimizer->SetMaximumIteration( this->m_OptimizerNumberOfIterations );
optimizer->SetEpsilon( this->m_OptimizerEpsilon );
optimizer->Initialize( this->m_OptimizerInitialRadius,
this->m_OptimizerGrowthFactor,
this->m_OptimizerShrinkFactor);
typedef itk::Statistics::NormalVariateGenerator GeneratorType;
GeneratorType::Pointer generator = GeneratorType::New();
generator->Initialize(12345);
optimizer->SetNormalVariateGenerator( generator );
this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetValue,optimizer.GetPointer());
this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer());
this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer());
this->m_pfGetOptimizerConvergenceValue = nsstd::bind(&_OptimizerType::GetFrobeniusNorm,optimizer.GetPointer());
this->m_pfGetOptimizerScales = nsstd::bind(&PositionOptimizerCustomCast::Helper<_OptimizerType::ScalesType>, nsstd::bind(&_OptimizerType::GetScales, optimizer.GetPointer()));
optimizer->Register();
return optimizer.GetPointer();
}
else
{
sitkExceptionMacro("LogicError: Unexpected case!");
}
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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.
*/
#ifndef KADEMLIA_NODE_ENTRY_HPP
#define KADEMLIA_NODE_ENTRY_HPP
#include "libtorrent/kademlia/node_id.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/union_endpoint.hpp"
#include "libtorrent/time.hpp" // for time_point
namespace libtorrent { namespace dht
{
struct node_entry
{
node_entry(node_id const& id_, udp::endpoint ep, int roundtriptime = 0xffff
, bool pinged = false);
node_entry(udp::endpoint ep);
node_entry();
void update_rtt(int new_rtt);
bool pinged() const { return timeout_count != 0xff; }
void set_pinged() { if (timeout_count == 0xff) timeout_count = 0; }
void timed_out() { if (pinged() && timeout_count < 0xfe) ++timeout_count; }
int fail_count() const { return pinged() ? timeout_count : 0; }
void reset_fail_count() { if (pinged()) timeout_count = 0; }
udp::endpoint ep() const { return udp::endpoint(address_v4(a), p); }
bool confirmed() const { return timeout_count == 0; }
address addr() const { return address_v4(a); }
int port() const { return p; }
#ifdef TORRENT_DHT_VERBOSE_LOGGING
time_point first_seen;
#endif
// the time we last received a response for a request to this peer
time_point last_queried;
node_id id;
address_v4::bytes_type a;
boost::uint16_t p;
// the average RTT of this node
boost::uint16_t rtt;
// the number of times this node has failed to
// respond in a row
boost::uint8_t timeout_count;
};
} } // namespace libtorrent::dht
#endif
<commit_msg>fix test_dht build<commit_after>/*
Copyright (c) 2006-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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.
*/
#ifndef KADEMLIA_NODE_ENTRY_HPP
#define KADEMLIA_NODE_ENTRY_HPP
#include "libtorrent/kademlia/node_id.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/union_endpoint.hpp"
#include "libtorrent/time.hpp" // for time_point
namespace libtorrent { namespace dht
{
struct TORRENT_EXTRA_EXPORT node_entry
{
node_entry(node_id const& id_, udp::endpoint ep, int roundtriptime = 0xffff
, bool pinged = false);
node_entry(udp::endpoint ep);
node_entry();
void update_rtt(int new_rtt);
bool pinged() const { return timeout_count != 0xff; }
void set_pinged() { if (timeout_count == 0xff) timeout_count = 0; }
void timed_out() { if (pinged() && timeout_count < 0xfe) ++timeout_count; }
int fail_count() const { return pinged() ? timeout_count : 0; }
void reset_fail_count() { if (pinged()) timeout_count = 0; }
udp::endpoint ep() const { return udp::endpoint(address_v4(a), p); }
bool confirmed() const { return timeout_count == 0; }
address addr() const { return address_v4(a); }
int port() const { return p; }
#ifdef TORRENT_DHT_VERBOSE_LOGGING
time_point first_seen;
#endif
// the time we last received a response for a request to this peer
time_point last_queried;
node_id id;
address_v4::bytes_type a;
boost::uint16_t p;
// the average RTT of this node
boost::uint16_t rtt;
// the number of times this node has failed to
// respond in a row
boost::uint8_t timeout_count;
};
} } // namespace libtorrent::dht
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/audio_coding/neteq4/tools/neteq_performance_test.h"
#include "webrtc/test/testsupport/perf_test.h"
#include "webrtc/typedefs.h"
TEST(NetEqPerformanceTest, Run) {
const int kSimulationTimeMs = 10000000;
const int kLossPeriod = 10; // Drop every 10th packet.
const double kDriftFactor = 0.1;
int64_t runtime = webrtc::test::NetEqPerformanceTest::Run(
kSimulationTimeMs, kLossPeriod, kDriftFactor);
ASSERT_GT(runtime, 0);
webrtc::test::PrintResult(
"neteq4-runtime", "", "", runtime, "ms", true);
}
<commit_msg>Add clean test to NetEq perf test<commit_after>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/audio_coding/neteq4/tools/neteq_performance_test.h"
#include "webrtc/test/testsupport/perf_test.h"
#include "webrtc/typedefs.h"
// Runs a test with 10% packet losses and 10% clock drift, to exercise
// both loss concealment and time-stretching code.
TEST(NetEqPerformanceTest, Run) {
const int kSimulationTimeMs = 10000000;
const int kLossPeriod = 10; // Drop every 10th packet.
const double kDriftFactor = 0.1;
int64_t runtime = webrtc::test::NetEqPerformanceTest::Run(
kSimulationTimeMs, kLossPeriod, kDriftFactor);
ASSERT_GT(runtime, 0);
webrtc::test::PrintResult(
"NetEq-performance", "", "10_pl_10_drift", runtime, "ms", true);
}
// Runs a test with neither packet losses nor clock drift, to put
// emphasis on the "good-weather" code path, which is presumably much
// more lightweight.
TEST(NetEqPerformanceTest, RunClean) {
const int kSimulationTimeMs = 10000000;
const int kLossPeriod = 0; // No losses.
const double kDriftFactor = 0.0; // No clock drift.
int64_t runtime = webrtc::test::NetEqPerformanceTest::Run(
kSimulationTimeMs, kLossPeriod, kDriftFactor);
ASSERT_GT(runtime, 0);
webrtc::test::PrintResult(
"NetEq-performance", "", "0_pl_0_drift", runtime, "ms", true);
}
<|endoftext|> |
<commit_before>//============================================================================
// vSMC/include/vsmc/rng/discrete_distribution.hpp
//----------------------------------------------------------------------------
// vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013-2015, Yan Zhou
// 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.
//
// 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 VSMC_RNG_DISCRETE_DISTRIBUTION_HPP
#define VSMC_RNG_DISCRETE_DISTRIBUTION_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/math/cblas.hpp>
#define VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param) \
VSMC_RUNTIME_ASSERT(is_positive(param), \
("**DiscreteDistribution** WEIGHTS ARE NOT NON-NEGATIVE"));
namespace vsmc {
/// \brief Draw a single sample given weights
/// \ingroup Distribution
template <typename IntType = int>
class DiscreteDistribution
{
public :
typedef IntType result_type;
typedef std::vector<double> param_type;
DiscreteDistribution () {}
template <typename InputIter>
DiscreteDistribution (InputIter first, InputIter last) :
param_(first, last)
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param_);
normalize();
}
#if VSMC_HAS_CXX11LIB_INITIALIZER_LIST
DiscreteDistribution (std::initializer_list<double> weights) :
param_(weights.begin(), weights.end())
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param_);
normalize();
}
#endif
template <typename UnaryOperation>
DiscreteDistribution (std::size_t count, double xmin, double xmax,
UnaryOperation unary_op)
{
param_.reserve(count);
double delta = (xmax - xmin) / static_cast<double>(count);
xmin += 0.5 * delta;
for (std::size_t i = 0; i != count; ++i)
param_.push_back(unary_op(xmin + static_cast<double>(i) * delta));
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param_);
normalize();
}
explicit DiscreteDistribution (const param_type ¶m)
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param);
param_ = param;
normalize();
}
#if VSMC_HAS_CXX11_RVALUE_REFERENCES
explicit DiscreteDistribution (param_type &¶m)
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param);
param_ = cxx11::move(param);
normalize();
}
#endif
param_type param () const {return param_;}
void param (const param_type ¶m)
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param);
param_ = param;
normalize();
}
#if VSMC_HAS_CXX11_RVALUE_REFERENCES
void param (param_type &¶m)
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param);
param_ = cxx11::move(param);
normalize();
}
#endif
void reset () {}
result_type min VSMC_MNE () const {return 0;}
result_type max VSMC_MNE () const
{return param_.size() == 0 ? 0 : param_.size() - 1;}
std::vector<double> probability () const {return param_;}
template <typename URNG>
result_type operator() (URNG &eng) const
{return operator()(eng, param_.begin(), param_.end(), true);}
/// \brief Draw sample with external probabilities
///
/// \param eng A uniform random number generator
/// \param first The first iterator of the weights sequence.
/// \param last The one past the end iterator of the weights sequence.
/// \param normalized If the weights are already normalized
///
/// \details
/// Given weights \f$(W_1,\dots,\W_N)\f$, it is possible to draw the index
/// \f$i\f$ using the `std::discrete_distribuiton` template. However, there
/// are two drawbacks with this approach. First, if the weightsa are
/// already normalized, this template does uncessary extra work to
/// normalized the weights. Second, whenever the weights change, a new
/// distribution need to be constructed (the `param_type` of the
/// distribution is implementation defined and cannot be used to write
/// portable code), which will lead to uncessary
/// dynamic memory allocation.
///
/// This function requires the *normalized* weights, specified using the
/// iterators `first` and `last`, and return the index (counting from zero)
/// of the random draw. No dynamic memory allocaiton will be invovled by
/// calling this function.
template <typename URNG, typename InputIter>
result_type operator() (URNG &eng, InputIter first, InputIter last,
bool normalized = false) const
{
typedef typename std::iterator_traits<InputIter>::value_type
value_type;
cxx11::uniform_real_distribution<value_type> runif(0, 1);
value_type u = runif(eng);
if (!normalized) {
value_type mulw = 1 / std::accumulate(first, last,
static_cast<value_type>(0));
value_type accw = 0;
result_type index = 0;
while (first != last) {
accw += *first * mulw;
if (u <= accw)
return index;
++first;
++index;
}
return index - 1;
}
value_type accw = 0;
result_type index = 0;
while (first != last) {
accw += *first;
if (u <= accw)
return index;
++first;
++index;
}
return index - 1;
}
friend inline bool operator== (
const DiscreteDistribution<IntType> &rdisc1,
const DiscreteDistribution<IntType> &rdisc2)
{return rdisc1.param_ == rdisc2.param_;}
friend inline bool operator!= (
const DiscreteDistribution<IntType> &rdisc1,
const DiscreteDistribution<IntType> &rdisc2)
{return rdisc1.param_ != rdisc2.param_;}
template <typename CharT, typename Traits>
friend inline std::basic_ostream<CharT, Traits> &operator<< (
std::basic_ostream<CharT, Traits> &os,
const DiscreteDistribution<IntType> &rdisc)
{
if (!os.good())
return os;
os << rdisc.param_.size() << ' ';
if (rdisc.param_.size() == 0)
return os;
if (rdisc.param_.size() == 1) {
os << rdisc.param_[0];
return os;
}
for (std::size_t i = 0; i != rdisc.param_.size() - 1; ++i)
os << rdisc.param_[i] << ' ';
os << rdisc.param_.back();
return os;
}
template <typename CharT, typename Traits>
friend inline std::basic_istream<CharT, Traits> &operator>> (
std::basic_istream<CharT, Traits> &is,
DiscreteDistribution<IntType> &rdisc)
{
if (!is.good())
return is;
std::size_t n;
is >> std::ws >> n;
std::vector<double> param(n);
for (std::size_t i = 0; i != n; ++i)
is >> std::ws >> param[i];
if (is.good()) {
if (rdisc.is_positive(param)) {
std::swap(rdisc.param_, param);
rdisc.normalize();
} else {
is.setstate(std::ios_base::failbit);
}
}
return is;
}
private :
param_type param_;
void normalize ()
{
if (param_.size() == 0)
return;
double sumw = std::accumulate(param_.begin(), param_.end(), 0.0);
math::scal(param_.size(), 1 / sumw, ¶m_[0]);
}
bool is_positive (const param_type ¶m)
{
for (std::size_t i = 0; i != param.size(); ++i)
if (param[i] < 0)
return false;
if (param.size() == 0)
return true;
if (std::accumulate(param.begin(), param.end(), 0.0) <= 0)
return false;
return true;
}
}; // class DiscreteDistribution
} // namespace vsmc
#endif // VSMC_RNG_DISCRETE_DISTRIBUTION_HPP
<commit_msg>Update documents<commit_after>//============================================================================
// vSMC/include/vsmc/rng/discrete_distribution.hpp
//----------------------------------------------------------------------------
// vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013-2015, Yan Zhou
// 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.
//
// 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 VSMC_RNG_DISCRETE_DISTRIBUTION_HPP
#define VSMC_RNG_DISCRETE_DISTRIBUTION_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/math/cblas.hpp>
#define VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param) \
VSMC_RUNTIME_ASSERT(is_positive(param), \
("**DiscreteDistribution** WEIGHTS ARE NOT NON-NEGATIVE"));
namespace vsmc {
/// \brief Draw a single sample given weights
/// \ingroup Distribution
template <typename IntType = int>
class DiscreteDistribution
{
public :
typedef IntType result_type;
typedef std::vector<double> param_type;
DiscreteDistribution () {}
template <typename InputIter>
DiscreteDistribution (InputIter first, InputIter last) :
param_(first, last)
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param_);
normalize();
}
#if VSMC_HAS_CXX11LIB_INITIALIZER_LIST
DiscreteDistribution (std::initializer_list<double> weights) :
param_(weights.begin(), weights.end())
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param_);
normalize();
}
#endif
template <typename UnaryOperation>
DiscreteDistribution (std::size_t count, double xmin, double xmax,
UnaryOperation unary_op)
{
param_.reserve(count);
double delta = (xmax - xmin) / static_cast<double>(count);
xmin += 0.5 * delta;
for (std::size_t i = 0; i != count; ++i)
param_.push_back(unary_op(xmin + static_cast<double>(i) * delta));
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param_);
normalize();
}
explicit DiscreteDistribution (const param_type ¶m)
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param);
param_ = param;
normalize();
}
#if VSMC_HAS_CXX11_RVALUE_REFERENCES
explicit DiscreteDistribution (param_type &¶m)
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param);
param_ = cxx11::move(param);
normalize();
}
#endif
param_type param () const {return param_;}
void param (const param_type ¶m)
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param);
param_ = param;
normalize();
}
#if VSMC_HAS_CXX11_RVALUE_REFERENCES
void param (param_type &¶m)
{
VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(param);
param_ = cxx11::move(param);
normalize();
}
#endif
void reset () {}
result_type min VSMC_MNE () const {return 0;}
result_type max VSMC_MNE () const
{return param_.size() == 0 ? 0 : param_.size() - 1;}
std::vector<double> probability () const {return param_;}
template <typename URNG>
result_type operator() (URNG &eng) const
{return operator()(eng, param_.begin(), param_.end(), true);}
/// \brief Draw sample with external probabilities
///
/// \param eng A uniform random number generator
/// \param first The first iterator of the weights sequence.
/// \param last The one past the end iterator of the weights sequence.
/// \param normalized If the weights are already normalized
///
/// \details
/// Given weights \f$(W_1,\dots,\W_N)\f$, it is possible to draw the index
/// \f$i\f$ using the `std::discrete_distribuiton` template. However, there
/// are two drawbacks with this approach. First, if the weights are
/// already normalized, this template does uncessary extra work to
/// normalized the weights. Second, whenever the weights change, a new
/// distribution need to be constructed (the `param_type` of the
/// distribution is implementation defined and cannot be used to write
/// portable code), which will lead to uncessary
/// dynamic memory allocation. This function does not use dynamic memory
/// and improve performance for normalized weights.
template <typename URNG, typename InputIter>
result_type operator() (URNG &eng, InputIter first, InputIter last,
bool normalized = false) const
{
typedef typename std::iterator_traits<InputIter>::value_type
value_type;
cxx11::uniform_real_distribution<value_type> runif(0, 1);
value_type u = runif(eng);
if (!normalized) {
value_type mulw = 1 / std::accumulate(first, last,
static_cast<value_type>(0));
value_type accw = 0;
result_type index = 0;
while (first != last) {
accw += *first * mulw;
if (u <= accw)
return index;
++first;
++index;
}
return index - 1;
}
value_type accw = 0;
result_type index = 0;
while (first != last) {
accw += *first;
if (u <= accw)
return index;
++first;
++index;
}
return index - 1;
}
friend inline bool operator== (
const DiscreteDistribution<IntType> &rdisc1,
const DiscreteDistribution<IntType> &rdisc2)
{return rdisc1.param_ == rdisc2.param_;}
friend inline bool operator!= (
const DiscreteDistribution<IntType> &rdisc1,
const DiscreteDistribution<IntType> &rdisc2)
{return rdisc1.param_ != rdisc2.param_;}
template <typename CharT, typename Traits>
friend inline std::basic_ostream<CharT, Traits> &operator<< (
std::basic_ostream<CharT, Traits> &os,
const DiscreteDistribution<IntType> &rdisc)
{
if (!os.good())
return os;
os << rdisc.param_.size() << ' ';
if (rdisc.param_.size() == 0)
return os;
if (rdisc.param_.size() == 1) {
os << rdisc.param_[0];
return os;
}
for (std::size_t i = 0; i != rdisc.param_.size() - 1; ++i)
os << rdisc.param_[i] << ' ';
os << rdisc.param_.back();
return os;
}
template <typename CharT, typename Traits>
friend inline std::basic_istream<CharT, Traits> &operator>> (
std::basic_istream<CharT, Traits> &is,
DiscreteDistribution<IntType> &rdisc)
{
if (!is.good())
return is;
std::size_t n;
is >> std::ws >> n;
std::vector<double> param(n);
for (std::size_t i = 0; i != n; ++i)
is >> std::ws >> param[i];
if (is.good()) {
if (rdisc.is_positive(param)) {
std::swap(rdisc.param_, param);
rdisc.normalize();
} else {
is.setstate(std::ios_base::failbit);
}
}
return is;
}
private :
param_type param_;
void normalize ()
{
if (param_.size() == 0)
return;
double sumw = std::accumulate(param_.begin(), param_.end(), 0.0);
math::scal(param_.size(), 1 / sumw, ¶m_[0]);
}
bool is_positive (const param_type ¶m)
{
for (std::size_t i = 0; i != param.size(); ++i)
if (param[i] < 0)
return false;
if (param.size() == 0)
return true;
if (std::accumulate(param.begin(), param.end(), 0.0) <= 0)
return false;
return true;
}
}; // class DiscreteDistribution
} // namespace vsmc
#endif // VSMC_RNG_DISCRETE_DISTRIBUTION_HPP
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/audio_coding/neteq4/tools/neteq_performance_test.h"
#include "webrtc/test/testsupport/perf_test.h"
#include "webrtc/typedefs.h"
// Runs a test with 10% packet losses and 10% clock drift, to exercise
// both loss concealment and time-stretching code.
TEST(NetEqPerformanceTest, Run) {
const int kSimulationTimeMs = 10000000;
const int kLossPeriod = 10; // Drop every 10th packet.
const double kDriftFactor = 0.1;
int64_t runtime = webrtc::test::NetEqPerformanceTest::Run(
kSimulationTimeMs, kLossPeriod, kDriftFactor);
ASSERT_GT(runtime, 0);
webrtc::test::PrintResult(
"NetEq-performance", "", "10_pl_10_drift", runtime, "ms", true);
}
// Runs a test with neither packet losses nor clock drift, to put
// emphasis on the "good-weather" code path, which is presumably much
// more lightweight.
TEST(NetEqPerformanceTest, RunClean) {
const int kSimulationTimeMs = 10000000;
const int kLossPeriod = 0; // No losses.
const double kDriftFactor = 0.0; // No clock drift.
int64_t runtime = webrtc::test::NetEqPerformanceTest::Run(
kSimulationTimeMs, kLossPeriod, kDriftFactor);
ASSERT_GT(runtime, 0);
webrtc::test::PrintResult(
"NetEq-performance", "", "0_pl_0_drift", runtime, "ms", true);
}
<commit_msg>Fixing test name for NetEqPerformanceTest<commit_after>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/audio_coding/neteq4/tools/neteq_performance_test.h"
#include "webrtc/test/testsupport/perf_test.h"
#include "webrtc/typedefs.h"
// Runs a test with 10% packet losses and 10% clock drift, to exercise
// both loss concealment and time-stretching code.
TEST(NetEqPerformanceTest, Run) {
const int kSimulationTimeMs = 10000000;
const int kLossPeriod = 10; // Drop every 10th packet.
const double kDriftFactor = 0.1;
int64_t runtime = webrtc::test::NetEqPerformanceTest::Run(
kSimulationTimeMs, kLossPeriod, kDriftFactor);
ASSERT_GT(runtime, 0);
webrtc::test::PrintResult(
"neteq_performance", "", "10_pl_10_drift", runtime, "ms", true);
}
// Runs a test with neither packet losses nor clock drift, to put
// emphasis on the "good-weather" code path, which is presumably much
// more lightweight.
TEST(NetEqPerformanceTest, RunClean) {
const int kSimulationTimeMs = 10000000;
const int kLossPeriod = 0; // No losses.
const double kDriftFactor = 0.0; // No clock drift.
int64_t runtime = webrtc::test::NetEqPerformanceTest::Run(
kSimulationTimeMs, kLossPeriod, kDriftFactor);
ASSERT_GT(runtime, 0);
webrtc::test::PrintResult(
"neteq_performance", "", "0_pl_0_drift", runtime, "ms", true);
}
<|endoftext|> |
<commit_before>#include "VRDataQueue.h"
#include <main/VRError.h>
namespace MinVR {
// Use this when the client has no new data to offer.
const VRDataQueue::serialData VRDataQueue::noData = "";
VRDataQueue::VRDataQueue(const VRDataQueue::serialData serializedQueue) {
addSerializedQueue(serializedQueue);
}
// This function does *not* process arbitrary XML, but it *does* process XML
// that was produced by the serialize() method below. This is why it looks a
// bit hacky, with mysterious constants like the number 18. This
// serialization is only intended to transmit from one instance of this class
// to another, even if it more or less honors the look and feel of XML.
void VRDataQueue::addSerializedQueue(const VRDataQueue::serialData serializedQueue) {
// Looking for the number in <VRDataQueue num="X">
if (serializedQueue.size() < 18) return;
std::size_t start, end;
start = 18;
end = serializedQueue.find("\"", start);
//std::cout << serializedQueue.substr(start, end - start) << std::endl;
int numIncluded;
std::istringstream( serializedQueue.substr(start,end)) >> numIncluded;
start = serializedQueue.find(">", end);
// Found the number of items. Now parse the items, making sure to
// record the timeStamp of each one.
int numReceived = 0;
long long timeStamp;
start = serializedQueue.find("<VRDataQueueItem timeStamp=\"", start);
while (start != std::string::npos) {
end = serializedQueue.find("\">", start);
// These constants have to do with the length of the tags used to
// encode a queue.
std::istringstream(serializedQueue.substr(start + 28, end - start - 28)) >>
timeStamp;
start = serializedQueue.find("</VRDataQueueItem>", end);
push(timeStamp, serializedQueue.substr(end + 2, start - end - 2) );
numReceived++;
start = serializedQueue.find("<VRDataQueueItem timeStamp=\"", end);
}
if (numReceived != numIncluded) {
VRERRORNOADV("Serialized queue appears corrupted.");
}
}
void VRDataQueue::addQueue(const VRDataQueue newQueue) {
if (newQueue.notEmpty()) {
for (VRDataQueue::const_iterator it = newQueue.begin();
it != newQueue.end(); it++) {
// We only want the time value of the timestamp, not the disambiguation
// value.
push(it->first.first, it->second);
}
}
}
VRDataIndex VRDataQueue::getFirst() const {
if (_dataMap.empty()) {
return VRDataIndex();
} else {
return _dataMap.begin()->second.getData();
}
}
void VRDataQueue::pop() {
_dataMap.erase(_dataMap.begin());
}
void VRDataQueue::clear() {
_dataMap.clear();
}
// Suggested on Stackoverflow:
//
// inline uint64_t rdtsc() {
// uint32_t lo, hi;
// __asm__ __volatile__ (
// "xorl %%eax, %%eax\n"
// "cpuid\n"
// "rdtsc\n"
// : "=a" (lo), "=d" (hi)
// :
// : "%ebx", "%ecx");
// return (uint64_t)hi << 32 | lo;
// }
//
// http://stackoverflow.com/questions/88/is-gettimeofday-guaranteed-to-be-of-microsecond-resolution
//
// Possibly this is a better way to do the timestamps in the push() method
// below. There seems to be a resolution issue on some Windows machines that
// makes lots of events have the same time stamp.
long long VRDataQueue::makeTimeStamp() {
#ifdef WIN32
LARGE_INTEGER t1;
FILETIME ft;
GetSystemTimePreciseAsFileTime(&ft); // Requires windows 8 and above. Should give microsecond resolution and be consistent across different machines if they are using a time server.
t1.LowPart = ft.dwLowDateTime;
t1.HighPart = ft.dwHighDateTime;
long long timeStamp = t1.QuadPart;
#else
struct timeval tp;
gettimeofday(&tp, NULL);
// Get current timestamp in milliseconds.
long long timeStamp = (long long) tp.tv_sec * 1000000L + tp.tv_usec;
#endif
return timeStamp;
}
void VRDataQueue::push(const VRDataQueue::serialData serializedData) {
push(makeTimeStamp(), serializedData);
}
void VRDataQueue::push(const VRDataIndex event) {
VRDataIndex* eventPtr = new VRDataIndex(event);
push(makeTimeStamp(), VRDataQueueItem(eventPtr));
}
void VRDataQueue::push(const long long timeStamp,
const VRDataQueue::serialData serializedData) {
push(timeStamp, VRDataQueueItem(serializedData));
}
void VRDataQueue::push(const long long timeStamp,
const VRDataQueueItem queueItem) {
VRTimeStamp testStamp = VRTimeStamp(timeStamp, 0);
while (_dataMap.find(testStamp) != _dataMap.end()) {
testStamp = VRTimeStamp(timeStamp, testStamp.second + 1);
}
_dataMap.insert(VRDataListItem(testStamp, queueItem));
}
VRDataQueue::serialData VRDataQueue::serialize() {
std::ostringstream lenStr;
lenStr << _dataMap.size();
VRDataQueue::serialData out;
out = "<VRDataQueue num=\"" + lenStr.str() + "\">";
for (VRDataList::iterator it = _dataMap.begin(); it != _dataMap.end(); ++it) {
std::ostringstream timeStamp;
timeStamp << it->first.first << "-" << std::setfill('0') << std::setw(3) << it->first.second;
out += "<VRDataQueueItem timeStamp=\"" + timeStamp.str() + "\">" +
it->second.serialize() + "</VRDataQueueItem>";
}
out += "</VRDataQueue>";
return out;
}
// DEBUG only
std::string VRDataQueue::printQueue() const {
std::string out;
char buf[6]; // No queues more than a million entries long.
int i = 0;
for (VRDataList::const_iterator it = _dataMap.begin();
it != _dataMap.end(); ++it) {
sprintf(buf, "%d", ++i);
std::string identifier = "element";
if (it->second.isSerialized()) {
identifier += "*";
} else {
identifier += " ";
}
out += identifier + std::string(buf) + ": " + it->second.serialize() + "\n";
}
return out;
}
} // end namespace MinVR
<commit_msg>fixes timestamps for windows 7, although with lower resolution<commit_after>#include "VRDataQueue.h"
#include <main/VRError.h>
namespace MinVR {
// Use this when the client has no new data to offer.
const VRDataQueue::serialData VRDataQueue::noData = "";
VRDataQueue::VRDataQueue(const VRDataQueue::serialData serializedQueue) {
addSerializedQueue(serializedQueue);
}
// This function does *not* process arbitrary XML, but it *does* process XML
// that was produced by the serialize() method below. This is why it looks a
// bit hacky, with mysterious constants like the number 18. This
// serialization is only intended to transmit from one instance of this class
// to another, even if it more or less honors the look and feel of XML.
void VRDataQueue::addSerializedQueue(const VRDataQueue::serialData serializedQueue) {
// Looking for the number in <VRDataQueue num="X">
if (serializedQueue.size() < 18) return;
std::size_t start, end;
start = 18;
end = serializedQueue.find("\"", start);
//std::cout << serializedQueue.substr(start, end - start) << std::endl;
int numIncluded;
std::istringstream( serializedQueue.substr(start,end)) >> numIncluded;
start = serializedQueue.find(">", end);
// Found the number of items. Now parse the items, making sure to
// record the timeStamp of each one.
int numReceived = 0;
long long timeStamp;
start = serializedQueue.find("<VRDataQueueItem timeStamp=\"", start);
while (start != std::string::npos) {
end = serializedQueue.find("\">", start);
// These constants have to do with the length of the tags used to
// encode a queue.
std::istringstream(serializedQueue.substr(start + 28, end - start - 28)) >>
timeStamp;
start = serializedQueue.find("</VRDataQueueItem>", end);
push(timeStamp, serializedQueue.substr(end + 2, start - end - 2) );
numReceived++;
start = serializedQueue.find("<VRDataQueueItem timeStamp=\"", end);
}
if (numReceived != numIncluded) {
VRERRORNOADV("Serialized queue appears corrupted.");
}
}
void VRDataQueue::addQueue(const VRDataQueue newQueue) {
if (newQueue.notEmpty()) {
for (VRDataQueue::const_iterator it = newQueue.begin();
it != newQueue.end(); it++) {
// We only want the time value of the timestamp, not the disambiguation
// value.
push(it->first.first, it->second);
}
}
}
VRDataIndex VRDataQueue::getFirst() const {
if (_dataMap.empty()) {
return VRDataIndex();
} else {
return _dataMap.begin()->second.getData();
}
}
void VRDataQueue::pop() {
_dataMap.erase(_dataMap.begin());
}
void VRDataQueue::clear() {
_dataMap.clear();
}
// Suggested on Stackoverflow:
//
// inline uint64_t rdtsc() {
// uint32_t lo, hi;
// __asm__ __volatile__ (
// "xorl %%eax, %%eax\n"
// "cpuid\n"
// "rdtsc\n"
// : "=a" (lo), "=d" (hi)
// :
// : "%ebx", "%ecx");
// return (uint64_t)hi << 32 | lo;
// }
//
// http://stackoverflow.com/questions/88/is-gettimeofday-guaranteed-to-be-of-microsecond-resolution
//
// Possibly this is a better way to do the timestamps in the push() method
// below. There seems to be a resolution issue on some Windows machines that
// makes lots of events have the same time stamp.
long long VRDataQueue::makeTimeStamp() {
#ifdef WIN32
LARGE_INTEGER t1;
FILETIME ft;
// Determine if windows 8 or greater
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
//https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions
if (osvi.dwMajorVersion > 6 || (osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion >= 2)) {
GetSystemTimePreciseAsFileTime(&ft); // Requires windows 8 and above. Should give microsecond resolution and be consistent across different machines if they are using a time server.
}
else {
GetSystemTimeAsFileTime(&ft);
}
t1.LowPart = ft.dwLowDateTime;
t1.HighPart = ft.dwHighDateTime;
long long timeStamp = t1.QuadPart;
#else
struct timeval tp;
gettimeofday(&tp, NULL);
// Get current timestamp in milliseconds.
long long timeStamp = (long long) tp.tv_sec * 1000000L + tp.tv_usec;
#endif
return timeStamp;
}
void VRDataQueue::push(const VRDataQueue::serialData serializedData) {
push(makeTimeStamp(), serializedData);
}
void VRDataQueue::push(const VRDataIndex event) {
VRDataIndex* eventPtr = new VRDataIndex(event);
push(makeTimeStamp(), VRDataQueueItem(eventPtr));
}
void VRDataQueue::push(const long long timeStamp,
const VRDataQueue::serialData serializedData) {
push(timeStamp, VRDataQueueItem(serializedData));
}
void VRDataQueue::push(const long long timeStamp,
const VRDataQueueItem queueItem) {
VRTimeStamp testStamp = VRTimeStamp(timeStamp, 0);
while (_dataMap.find(testStamp) != _dataMap.end()) {
testStamp = VRTimeStamp(timeStamp, testStamp.second + 1);
}
_dataMap.insert(VRDataListItem(testStamp, queueItem));
}
VRDataQueue::serialData VRDataQueue::serialize() {
std::ostringstream lenStr;
lenStr << _dataMap.size();
VRDataQueue::serialData out;
out = "<VRDataQueue num=\"" + lenStr.str() + "\">";
for (VRDataList::iterator it = _dataMap.begin(); it != _dataMap.end(); ++it) {
std::ostringstream timeStamp;
timeStamp << it->first.first << "-" << std::setfill('0') << std::setw(3) << it->first.second;
out += "<VRDataQueueItem timeStamp=\"" + timeStamp.str() + "\">" +
it->second.serialize() + "</VRDataQueueItem>";
}
out += "</VRDataQueue>";
return out;
}
// DEBUG only
std::string VRDataQueue::printQueue() const {
std::string out;
char buf[6]; // No queues more than a million entries long.
int i = 0;
for (VRDataList::const_iterator it = _dataMap.begin();
it != _dataMap.end(); ++it) {
sprintf(buf, "%d", ++i);
std::string identifier = "element";
if (it->second.isSerialized()) {
identifier += "*";
} else {
identifier += " ";
}
out += identifier + std::string(buf) + ": " + it->second.serialize() + "\n";
}
return out;
}
} // end namespace MinVR
<|endoftext|> |
<commit_before>// v8
#include <v8.h>
// node
#include <node.h>
#include <node_version.h>
// stl
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
// osr
#include "ogr_spatialref.h"
//#include "ogr_core.h"
//#include "cpl_conv.h"
#include "cpl_string.h"
//#include "ogr_p.h"
//#include "cpl_multiproc.h"
//#include "ogr_srs_api.h"
using namespace node;
using namespace v8;
#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))
/*
OGRERR_DICT = { 1 : (OGRException, "Not enough data."),
2 : (OGRException, "Not enough memory."),
3 : (OGRException, "Unsupported geometry type."),
4 : (OGRException, "Unsupported operation."),
5 : (OGRException, "Corrupt data."),
6 : (OGRException, "OGR failure."),
7 : (SRSException, "Unsupported SRS."),
8 : (OGRException, "Invalid handle."),
}
*/
static Handle<Value> parse(const Arguments& args)
{
HandleScope scope;
if (args.Length() != 1 || !args[0]->IsString())
return ThrowException(Exception::TypeError(
String::New("first argument must be srs string in any form readable by OGR, like WKT (.prj file) or a proj4 string")));
OGRSpatialReference oSRS;
Local<Object> result = Object::New();
result->Set(String::NewSymbol("input"), args[0]->ToString());
// intialize as undefined
result->Set(String::NewSymbol("proj4"), Undefined());
result->Set(String::NewSymbol("srid"), Undefined());
result->Set(String::NewSymbol("auth"), Undefined());
result->Set(String::NewSymbol("pretty_wkt"), Undefined());
result->Set(String::NewSymbol("esri"), Undefined());
result->Set(String::NewSymbol("name"), Undefined());
std::string wkt_string = TOSTR(args[0]->ToString());
//std::string wkt_string = std::string("ESRI::") + TOSTR(args[0]->ToString());
const char *wkt_char = wkt_string.data();
bool error = false;
Handle<Value> err;
if( oSRS.SetFromUserInput(wkt_char) != OGRERR_NONE )
{
error = true;
std::ostringstream s;
s << "a: OGR Error type #" << CPLE_AppDefined
<< " problem occured importing from srs wkt: " << wkt_string << ".\n";;
err = ThrowException(Exception::TypeError(String::New(s.str().c_str())));
// try again to import from ESRI
oSRS.Clear();
char **wkt_lines = NULL;
wkt_lines = CSLTokenizeString2( wkt_char, " \t\n",
CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS );
if( oSRS.importFromESRI(wkt_lines) != OGRERR_NONE )
{
error = true;
oSRS.Clear();
//std::ostringstream s;
//s << "b: OGR Error type #" << CPLE_AppDefined
// << " problem occured importing assuming esri wkt " << wkt_string << ".\n";
//err = ThrowException(Exception::TypeError(String::New(s.str().c_str())));
}
else
{
error = false;
std::clog << "imported assuming esri format...\n";
result->Set(String::NewSymbol("esri"), Boolean::New(true));
}
}
else
{
error = false;
result->Set(String::NewSymbol("esri"), Boolean::New(false));
}
if (error)
return err;
char *srs_output = NULL;
if( oSRS.Validate() == OGRERR_NONE)
result->Set(String::NewSymbol("valid"), Boolean::New(true));
else if (oSRS.Validate() == OGRERR_UNSUPPORTED_SRS)
result->Set(String::NewSymbol("valid"), Boolean::New(false));
else
result->Set(String::NewSymbol("valid"), Boolean::New(false));
// TODO - trim output of proj4 result
if (oSRS.exportToProj4( &srs_output ) != OGRERR_NONE )
{
std::ostringstream s;
s << "OGR Error type #" << CPLE_AppDefined
<< " problem occured when converting to proj4 format " << wkt_string << ".\n";
// for now let proj4 errors be non-fatal so that some info can be known...
//std::clog << s.str();
//return ThrowException(Exception::TypeError(String::New(s.str().c_str())));
}
else
{
// proj4 strings from osr have an uneeded trailing slash, so we trim it...
result->Set(String::NewSymbol("proj4"), String::New(CPLString(srs_output).Trim()));
}
CPLFree( srs_output );
if (oSRS.AutoIdentifyEPSG() != OGRERR_NONE )
{
/*std::ostringstream s;
s << "OGR Error type #" << CPLE_AppDefined
<< " problem occured when attempting to auto identify epsg code " << wkt_string << ".\n";
std::clog << s.str();
*/
//return ThrowException(Exception::TypeError(String::New(s.str().c_str())));
}
if (oSRS.IsGeographic())
{
result->Set(String::NewSymbol("is_geographic"), Boolean::New(true));
const char *code = oSRS.GetAuthorityCode("GEOGCS");
if (code)
result->Set(String::NewSymbol("srid"), Integer::New(atoi(code)));
const char *auth = oSRS.GetAuthorityName("GEOGCS");
if (auth)
result->Set(String::NewSymbol("auth"), String::New(auth));
const char *name = oSRS.GetAttrValue("GEOGCS");
if (name)
result->Set(String::NewSymbol("name"), String::New(name));
}
else
{
result->Set(String::NewSymbol("is_geographic"), Boolean::New(false));
const char *code = oSRS.GetAuthorityCode("PROJCS");
if (code)
result->Set(String::NewSymbol("srid"), Integer::New(atoi(code)));
const char *auth = oSRS.GetAuthorityName("PROJCS");
if (auth)
result->Set(String::NewSymbol("auth"), String::New(auth));
const char *name = oSRS.GetAttrValue("PROJCS");
if (name)
result->Set(String::NewSymbol("name"), String::New(name));
}
char *srs_output2 = NULL;
if (oSRS.exportToPrettyWkt( &srs_output2 , 0) != OGRERR_NONE )
{
// this does not yet actually return errors
std::ostringstream s;
s << "OGR Error type #" << CPLE_AppDefined
<< " problem occured when converting to pretty wkt format " << wkt_string << ".\n";
//std::clog << s.str();
//return ThrowException(Exception::TypeError(String::New(s.str().c_str())));
}
else
{
result->Set(String::NewSymbol("pretty_wkt"), String::New(srs_output2));
}
CPLFree( srs_output2 );
//OGRSpatialReference::DestroySpatialReference( &oSRS );
return scope.Close(result);
}
extern "C" {
static void init (Handle<Object> target)
{
// node-srs version
target->Set(String::NewSymbol("version"), String::New("0.2.18"));
NODE_SET_METHOD(target, "_parse", parse);
// versions of deps
Local<Object> versions = Object::New();
versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1));
versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion()));
// ogr/osr ?
target->Set(String::NewSymbol("versions"), versions);
}
NODE_MODULE(_srs, init);
}
<commit_msg>remove 'a:' debug print<commit_after>// v8
#include <v8.h>
// node
#include <node.h>
#include <node_version.h>
// stl
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
// osr
#include "ogr_spatialref.h"
//#include "ogr_core.h"
//#include "cpl_conv.h"
#include "cpl_string.h"
//#include "ogr_p.h"
//#include "cpl_multiproc.h"
//#include "ogr_srs_api.h"
using namespace node;
using namespace v8;
#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))
/*
OGRERR_DICT = { 1 : (OGRException, "Not enough data."),
2 : (OGRException, "Not enough memory."),
3 : (OGRException, "Unsupported geometry type."),
4 : (OGRException, "Unsupported operation."),
5 : (OGRException, "Corrupt data."),
6 : (OGRException, "OGR failure."),
7 : (SRSException, "Unsupported SRS."),
8 : (OGRException, "Invalid handle."),
}
*/
static Handle<Value> parse(const Arguments& args)
{
HandleScope scope;
if (args.Length() != 1 || !args[0]->IsString())
return ThrowException(Exception::TypeError(
String::New("first argument must be srs string in any form readable by OGR, like WKT (.prj file) or a proj4 string")));
OGRSpatialReference oSRS;
Local<Object> result = Object::New();
result->Set(String::NewSymbol("input"), args[0]->ToString());
// intialize as undefined
result->Set(String::NewSymbol("proj4"), Undefined());
result->Set(String::NewSymbol("srid"), Undefined());
result->Set(String::NewSymbol("auth"), Undefined());
result->Set(String::NewSymbol("pretty_wkt"), Undefined());
result->Set(String::NewSymbol("esri"), Undefined());
result->Set(String::NewSymbol("name"), Undefined());
std::string wkt_string = TOSTR(args[0]->ToString());
//std::string wkt_string = std::string("ESRI::") + TOSTR(args[0]->ToString());
const char *wkt_char = wkt_string.data();
bool error = false;
Handle<Value> err;
if( oSRS.SetFromUserInput(wkt_char) != OGRERR_NONE )
{
error = true;
std::ostringstream s;
s << "OGR Error type #" << CPLE_AppDefined
<< " problem occured importing from srs wkt: " << wkt_string << ".\n";;
err = ThrowException(Exception::TypeError(String::New(s.str().c_str())));
// try again to import from ESRI
oSRS.Clear();
char **wkt_lines = NULL;
wkt_lines = CSLTokenizeString2( wkt_char, " \t\n",
CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS );
if( oSRS.importFromESRI(wkt_lines) != OGRERR_NONE )
{
error = true;
oSRS.Clear();
//std::ostringstream s;
//s << "b: OGR Error type #" << CPLE_AppDefined
// << " problem occured importing assuming esri wkt " << wkt_string << ".\n";
//err = ThrowException(Exception::TypeError(String::New(s.str().c_str())));
}
else
{
error = false;
std::clog << "imported assuming esri format...\n";
result->Set(String::NewSymbol("esri"), Boolean::New(true));
}
}
else
{
error = false;
result->Set(String::NewSymbol("esri"), Boolean::New(false));
}
if (error)
return err;
char *srs_output = NULL;
if( oSRS.Validate() == OGRERR_NONE)
result->Set(String::NewSymbol("valid"), Boolean::New(true));
else if (oSRS.Validate() == OGRERR_UNSUPPORTED_SRS)
result->Set(String::NewSymbol("valid"), Boolean::New(false));
else
result->Set(String::NewSymbol("valid"), Boolean::New(false));
// TODO - trim output of proj4 result
if (oSRS.exportToProj4( &srs_output ) != OGRERR_NONE )
{
std::ostringstream s;
s << "OGR Error type #" << CPLE_AppDefined
<< " problem occured when converting to proj4 format " << wkt_string << ".\n";
// for now let proj4 errors be non-fatal so that some info can be known...
//std::clog << s.str();
//return ThrowException(Exception::TypeError(String::New(s.str().c_str())));
}
else
{
// proj4 strings from osr have an uneeded trailing slash, so we trim it...
result->Set(String::NewSymbol("proj4"), String::New(CPLString(srs_output).Trim()));
}
CPLFree( srs_output );
if (oSRS.AutoIdentifyEPSG() != OGRERR_NONE )
{
/*std::ostringstream s;
s << "OGR Error type #" << CPLE_AppDefined
<< " problem occured when attempting to auto identify epsg code " << wkt_string << ".\n";
std::clog << s.str();
*/
//return ThrowException(Exception::TypeError(String::New(s.str().c_str())));
}
if (oSRS.IsGeographic())
{
result->Set(String::NewSymbol("is_geographic"), Boolean::New(true));
const char *code = oSRS.GetAuthorityCode("GEOGCS");
if (code)
result->Set(String::NewSymbol("srid"), Integer::New(atoi(code)));
const char *auth = oSRS.GetAuthorityName("GEOGCS");
if (auth)
result->Set(String::NewSymbol("auth"), String::New(auth));
const char *name = oSRS.GetAttrValue("GEOGCS");
if (name)
result->Set(String::NewSymbol("name"), String::New(name));
}
else
{
result->Set(String::NewSymbol("is_geographic"), Boolean::New(false));
const char *code = oSRS.GetAuthorityCode("PROJCS");
if (code)
result->Set(String::NewSymbol("srid"), Integer::New(atoi(code)));
const char *auth = oSRS.GetAuthorityName("PROJCS");
if (auth)
result->Set(String::NewSymbol("auth"), String::New(auth));
const char *name = oSRS.GetAttrValue("PROJCS");
if (name)
result->Set(String::NewSymbol("name"), String::New(name));
}
char *srs_output2 = NULL;
if (oSRS.exportToPrettyWkt( &srs_output2 , 0) != OGRERR_NONE )
{
// this does not yet actually return errors
std::ostringstream s;
s << "OGR Error type #" << CPLE_AppDefined
<< " problem occured when converting to pretty wkt format " << wkt_string << ".\n";
//std::clog << s.str();
//return ThrowException(Exception::TypeError(String::New(s.str().c_str())));
}
else
{
result->Set(String::NewSymbol("pretty_wkt"), String::New(srs_output2));
}
CPLFree( srs_output2 );
//OGRSpatialReference::DestroySpatialReference( &oSRS );
return scope.Close(result);
}
extern "C" {
static void init (Handle<Object> target)
{
// node-srs version
target->Set(String::NewSymbol("version"), String::New("0.2.18"));
NODE_SET_METHOD(target, "_parse", parse);
// versions of deps
Local<Object> versions = Object::New();
versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1));
versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion()));
// ogr/osr ?
target->Set(String::NewSymbol("versions"), versions);
}
NODE_MODULE(_srs, init);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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 "libtorrent/file.hpp"
#include "libtorrent/utf8.hpp"
#include <sstream>
#include <windows.h>
namespace
{
// must be used to not leak memory in case something would throw
class auto_localfree
{
public:
auto_localfree(HLOCAL memory)
: m_memory(memory)
{
}
~auto_localfree()
{
if (m_memory)
LocalFree(m_memory);
}
private:
HLOCAL m_memory;
};
std::string utf8_native(std::string const& s)
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret(size + 1);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
ret.resize(size - 1);
return ret;
}
void throw_exception(const char* thrower)
{
DWORD err = GetLastError();
#ifdef UNICODE
wchar_t *wbuffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPWSTR)&wbuffer, 0, 0);
auto_localfree auto_free(wbuffer);
std::string tmp_utf8;
libtorrent::wchar_utf8(wbuffer, tmp_utf8);
char const* buffer = tmp_utf8.c_str();
#else
char* buffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPSTR)&buffer, 0, 0);
auto_localfree auto_free(buffer);
#endif
std::stringstream s;
s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL");
throw libtorrent::file_error(s.str());
}
}
namespace libtorrent
{
struct file::impl : boost::noncopyable
{
enum open_flags
{
read_flag = 1,
write_flag = 2
};
enum seek_mode
{
seek_begin = FILE_BEGIN,
seek_from_here = FILE_CURRENT,
seek_end = FILE_END
};
impl()
{
m_file_handle = INVALID_HANDLE_VALUE;
}
void open(const char *file_name, open_flags flags)
{
assert(file_name);
assert(flags & (read_flag | write_flag));
DWORD access_mask = 0;
if (flags & read_flag)
access_mask |= GENERIC_READ;
if (flags & write_flag)
access_mask |= GENERIC_WRITE;
assert(access_mask & (GENERIC_READ | GENERIC_WRITE));
#ifdef UNICODE
std::wstring wfile_name(utf8_wchar(file_name));
HANDLE new_handle = CreateFile(
(LPCWSTR)wfile_name.c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#else
HANDLE new_handle = CreateFile(
utf8_native(file_name).c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#endif
if (new_handle == INVALID_HANDLE_VALUE)
{
std::stringstream s;
throw_exception(file_name);
}
// will only close old file if the open succeeded
close();
m_file_handle = new_handle;
}
void close()
{
if (m_file_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
}
}
~impl()
{
close();
}
size_type write(const char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_written = 0;
if (num_bytes != 0)
{
if (FALSE == WriteFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_written
, 0))
{
throw_exception("file::write");
}
}
return bytes_written;
}
size_type read(char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_read = 0;
if (num_bytes != 0)
{
if (FALSE == ReadFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_read
, 0))
{
throw_exception("file::read");
}
}
return bytes_read;
}
void seek(size_type pos, seek_mode from_where)
{
assert(pos >= 0 || from_where != seek_begin);
assert(pos <= 0 || from_where != seek_end);
LARGE_INTEGER offs;
offs.QuadPart = pos;
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, from_where))
{
throw_exception("file::seek");
}
}
size_type tell()
{
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, FILE_CURRENT))
{
throw_exception("file::tell");
}
size_type pos=offs.QuadPart;
assert(pos>=0);
return pos;
}
/*
size_type size()
{
LARGE_INTEGER s;
if (FALSE == GetFileSizeEx(m_file_handle, &s))
{
throw_exception("file::size");
}
size_type size = s.QuadPart;
assert(size >= 0);
return size;
}
*/
private:
HANDLE m_file_handle;
};
}
namespace libtorrent
{
const file::seek_mode file::begin(file::impl::seek_begin);
const file::seek_mode file::end(file::impl::seek_end);
const file::open_mode file::in(file::impl::read_flag);
const file::open_mode file::out(file::impl::write_flag);
file::file()
: m_impl(new libtorrent::file::impl())
{
}
file::file(boost::filesystem::path const& p, open_mode m)
: m_impl(new libtorrent::file::impl())
{
open(p,m);
}
file::~file()
{
}
void file::open(boost::filesystem::path const& p, open_mode m)
{
assert(p.is_complete());
m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buffer, size_type num_bytes)
{
return m_impl->write(buffer, num_bytes);
}
size_type file::read(char* buffer, size_type num_bytes)
{
return m_impl->read(buffer, num_bytes);
}
void file::seek(size_type pos, seek_mode m)
{
m_impl->seek(pos,impl::seek_mode(m.m_val));
}
size_type file::tell()
{
return m_impl->tell();
}
}
<commit_msg>*** empty log message ***<commit_after>/*
Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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 "libtorrent/file.hpp"
#include "libtorrent/utf8.hpp"
#include <sstream>
#include <windows.h>
namespace
{
// must be used to not leak memory in case something would throw
class auto_localfree
{
public:
auto_localfree(HLOCAL memory)
: m_memory(memory)
{
}
~auto_localfree()
{
if (m_memory)
LocalFree(m_memory);
}
private:
HLOCAL m_memory;
};
std::string utf8_native(std::string const& s)
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
ret.resize(size);
return ret;
}
void throw_exception(const char* thrower)
{
DWORD err = GetLastError();
#ifdef UNICODE
wchar_t *wbuffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPWSTR)&wbuffer, 0, 0);
auto_localfree auto_free(wbuffer);
std::string tmp_utf8;
libtorrent::wchar_utf8(wbuffer, tmp_utf8);
char const* buffer = tmp_utf8.c_str();
#else
char* buffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPSTR)&buffer, 0, 0);
auto_localfree auto_free(buffer);
#endif
std::stringstream s;
s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL");
throw libtorrent::file_error(s.str());
}
}
namespace libtorrent
{
struct file::impl : boost::noncopyable
{
enum open_flags
{
read_flag = 1,
write_flag = 2
};
enum seek_mode
{
seek_begin = FILE_BEGIN,
seek_from_here = FILE_CURRENT,
seek_end = FILE_END
};
impl()
{
m_file_handle = INVALID_HANDLE_VALUE;
}
void open(const char *file_name, open_flags flags)
{
assert(file_name);
assert(flags & (read_flag | write_flag));
DWORD access_mask = 0;
if (flags & read_flag)
access_mask |= GENERIC_READ;
if (flags & write_flag)
access_mask |= GENERIC_WRITE;
assert(access_mask & (GENERIC_READ | GENERIC_WRITE));
#ifdef UNICODE
std::wstring wfile_name(utf8_wchar(file_name));
HANDLE new_handle = CreateFile(
(LPCWSTR)wfile_name.c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#else
HANDLE new_handle = CreateFile(
utf8_native(file_name).c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#endif
if (new_handle == INVALID_HANDLE_VALUE)
{
std::stringstream s;
throw_exception(file_name);
}
// will only close old file if the open succeeded
close();
m_file_handle = new_handle;
}
void close()
{
if (m_file_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
}
}
~impl()
{
close();
}
size_type write(const char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_written = 0;
if (num_bytes != 0)
{
if (FALSE == WriteFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_written
, 0))
{
throw_exception("file::write");
}
}
return bytes_written;
}
size_type read(char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_read = 0;
if (num_bytes != 0)
{
if (FALSE == ReadFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_read
, 0))
{
throw_exception("file::read");
}
}
return bytes_read;
}
void seek(size_type pos, seek_mode from_where)
{
assert(pos >= 0 || from_where != seek_begin);
assert(pos <= 0 || from_where != seek_end);
LARGE_INTEGER offs;
offs.QuadPart = pos;
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, from_where))
{
throw_exception("file::seek");
}
}
size_type tell()
{
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, FILE_CURRENT))
{
throw_exception("file::tell");
}
size_type pos=offs.QuadPart;
assert(pos>=0);
return pos;
}
/*
size_type size()
{
LARGE_INTEGER s;
if (FALSE == GetFileSizeEx(m_file_handle, &s))
{
throw_exception("file::size");
}
size_type size = s.QuadPart;
assert(size >= 0);
return size;
}
*/
private:
HANDLE m_file_handle;
};
}
namespace libtorrent
{
const file::seek_mode file::begin(file::impl::seek_begin);
const file::seek_mode file::end(file::impl::seek_end);
const file::open_mode file::in(file::impl::read_flag);
const file::open_mode file::out(file::impl::write_flag);
file::file()
: m_impl(new libtorrent::file::impl())
{
}
file::file(boost::filesystem::path const& p, open_mode m)
: m_impl(new libtorrent::file::impl())
{
open(p,m);
}
file::~file()
{
}
void file::open(boost::filesystem::path const& p, open_mode m)
{
assert(p.is_complete());
m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buffer, size_type num_bytes)
{
return m_impl->write(buffer, num_bytes);
}
size_type file::read(char* buffer, size_type num_bytes)
{
return m_impl->read(buffer, num_bytes);
}
void file::seek(size_type pos, seek_mode m)
{
m_impl->seek(pos,impl::seek_mode(m.m_val));
}
size_type file::tell()
{
return m_impl->tell();
}
}
<|endoftext|> |
<commit_before>/// \file conn_ts.cpp
/// Contains the main code for the TS Connector
#include <queue>
#include <string>
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <getopt.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <mist/socket.h>
#include <mist/config.h>
#include <mist/stream.h>
#include <mist/ts_packet.h> //TS support
#include <mist/dtsc.h> //DTSC support
#include <mist/mp4.h> //For initdata conversion
///\brief Holds everything unique to the TS Connector
namespace Connector_TS {
///\brief Main function for the TS Connector
///\param conn A socket describing the connection the client.
///\param streamName The stream to connect to.
///\return The exit code of the connector.
int tsConnector(Socket::Connection conn, std::string streamName, std::string trackIDs){
std::string ToPack;
TS::Packet PackData;
std::string DTMIData;
int PacketNumber = 0;
long long unsigned int TimeStamp = 0;
int ThisNaluSize;
char VideoCounter = 0;
char AudioCounter = 0;
bool WritePesHeader;
bool IsKeyFrame;
bool FirstKeyFrame = true;
bool FirstIDRInKeyFrame;
MP4::AVCC avccbox;
bool haveAvcc = false;
DTSC::Stream Strm;
bool inited = false;
Socket::Connection ss;
while (conn.connected()){
if ( !inited){
ss = Util::Stream::getStream(streamName);
if ( !ss.connected()){
#if DEBUG >= 1
fprintf(stderr, "Could not connect to server!\n");
#endif
conn.close();
break;
}
if(trackIDs == ""){
std::stringstream tmpTracks;
// no track ids given? Find the first video and first audio track (if available) and use those!
int videoID = -1;
int audioID = -1;
Strm.waitForMeta(ss);
for (std::map<int,DTSC::Track>::iterator it = Strm.metadata.tracks.begin(); it != Strm.metadata.tracks.end(); it){
if (audioID == -1 && it->second.type == "audio"){
audioID = it->first;
tmpTracks << " " << it->first;
}
if (videoID == -1 && it->second.type == "video"){
videoID = it->first;
tmpTracks << " " << it->first;
}
} // for iterator
trackIDs += tmpTracks.str();
} // if trackIDs == ""
std::string cmd = "t " + trackIDs + "\ns 0\np\n";
ss.SendNow( cmd );
inited = true;
}
if (ss.spool()){
while (Strm.parsePacket(ss.Received())){
std::stringstream TSBuf;
Socket::Buffer ToPack;
//write PAT and PMT TS packets
if (PacketNumber == 0){
PackData.DefaultPAT();
TSBuf.write(PackData.ToString(), 188);
PackData.DefaultPMT();
TSBuf.write(PackData.ToString(), 188);
PacketNumber += 2;
}
int PIDno = 0;
char * ContCounter = 0;
if (Strm.lastType() == DTSC::VIDEO){
if ( !haveAvcc){
avccbox.setPayload(Strm.metadata.tracks[Strm.getPacket()["trackid"].asInt()].init);
haveAvcc = true;
}
IsKeyFrame = Strm.getPacket().isMember("keyframe");
if (IsKeyFrame){
TimeStamp = (Strm.getPacket()["time"].asInt() * 27000);
}
ToPack.append(avccbox.asAnnexB());
while (Strm.lastData().size() > 4){
ThisNaluSize = (Strm.lastData()[0] << 24) + (Strm.lastData()[1] << 16) + (Strm.lastData()[2] << 8) + Strm.lastData()[3];
Strm.lastData().replace(0, 4, TS::NalHeader, 4);
if (ThisNaluSize + 4 == Strm.lastData().size()){
ToPack.append(Strm.lastData());
break;
}else{
ToPack.append(Strm.lastData().c_str(), ThisNaluSize + 4);
Strm.lastData().erase(0, ThisNaluSize + 4);
}
}
ToPack.prepend(TS::Packet::getPESVideoLeadIn(0ul, Strm.getPacket()["time"].asInt() * 90));
PIDno = 0x100 - 1 + Strm.getPacket()["trackid"].asInt();
ContCounter = &VideoCounter;
}else if (Strm.lastType() == DTSC::AUDIO){
ToPack.append(TS::GetAudioHeader(Strm.lastData().size(), Strm.metadata.tracks[Strm.getPacket()["trackid"].asInt()].init));
ToPack.append(Strm.lastData());
ToPack.prepend(TS::Packet::getPESAudioLeadIn(ToPack.bytes(1073741824ul), Strm.getPacket()["time"].asInt() * 90));
PIDno = 0x100 - 1 + Strm.getPacket()["trackid"].asInt();
ContCounter = &AudioCounter;
IsKeyFrame = false;
}
//initial packet
PackData.Clear();
PackData.PID(PIDno);
PackData.ContinuityCounter(( *ContCounter)++);
PackData.UnitStart(1);
if (IsKeyFrame){
PackData.RandomAccess(1);
PackData.PCR(TimeStamp);
}
unsigned int toSend = PackData.AddStuffing(ToPack.bytes(184));
std::string gonnaSend = ToPack.remove(toSend);
PackData.FillFree(gonnaSend);
TSBuf.write(PackData.ToString(), 188);
PacketNumber++;
//rest of packets
while (ToPack.size()){
PackData.Clear();
PackData.PID(PIDno);
PackData.ContinuityCounter(( *ContCounter)++);
toSend = PackData.AddStuffing(ToPack.bytes(184));
gonnaSend = ToPack.remove(toSend);
PackData.FillFree(gonnaSend);
TSBuf.write(PackData.ToString(), 188);
PacketNumber++;
}
TSBuf.flush();
if (TSBuf.str().size()){
conn.SendNow(TSBuf.str().c_str(), TSBuf.str().size());
TSBuf.str("");
}
TSBuf.str("");
PacketNumber = 0;
}
}else{
Util::sleep(1000);
conn.spool();
}
}
return 0;
}
}
int main(int argc, char ** argv){
Util::Config conf(argv[0], PACKAGE_VERSION);
JSON::Value capa;
capa["desc"] = "Enables the raw MPEG Transport Stream protocol over TCP.";
capa["deps"] = "";
capa["required"]["streamname"]["name"] = "Stream";
capa["required"]["streamname"]["help"] = "What streamname to serve. For multiple streams, add this protocol multiple times using different ports.";
capa["required"]["streamname"]["type"] = "str";
capa["required"]["streamname"]["option"] = "--stream";
capa["optional"]["tracks"]["name"] = "Tracks";
capa["optional"]["tracks"]["help"] = "The track IDs of the stream that this connector will transmit separated by spaces";
capa["optional"]["tracks"]["type"] = "str";
capa["optional"]["tracks"]["option"] = "--tracks";
conf.addOption("streamname",
JSON::fromString("{\"arg\":\"string\",\"short\":\"s\",\"long\":\"stream\",\"help\":\"The name of the stream that this connector will transmit.\"}"));
conf.addOption("tracks",
JSON::fromString("{\"arg\":\"string\",\"value\":[\"\"],\"short\": \"t\",\"long\":\"tracks\",\"help\":\"The track IDs of the stream that this connector will transmit separated by spaces.\"}"));
conf.addConnectorOptions(8888, capa);
bool ret = conf.parseArgs(argc, argv);
if (conf.getBool("json")){
std::cout << capa.toString() << std::endl;
return -1;
}
if (!ret){
std::cerr << "Usage error: missing argument(s)." << std::endl;
conf.printHelp(std::cout);
return 1;
}
Socket::Server server_socket = Socket::Server(conf.getInteger("listen_port"), conf.getString("listen_interface"));
if ( !server_socket.connected()){
return 1;
}
conf.activate();
while (server_socket.connected() && conf.is_active){
Socket::Connection S = server_socket.accept();
if (S.connected()){ //check if the new connection is valid
pid_t myid = fork();
if (myid == 0){ //if new child, start MAINHANDLER
return Connector_TS::tsConnector(S, conf.getString("streamname"), conf.getString("tracks"));
}else{ //otherwise, do nothing or output debugging text
#if DEBUG >= 5
fprintf(stderr, "Spawned new process %i for socket %i\n", (int)myid, S.getSocket());
#endif
}
}
} //while connected
server_socket.close();
return 0;
} //main
<commit_msg>Fixing TS<commit_after>/// \file conn_ts.cpp
/// Contains the main code for the TS Connector
#include <queue>
#include <string>
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <getopt.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <mist/socket.h>
#include <mist/config.h>
#include <mist/stream.h>
#include <mist/ts_packet.h> //TS support
#include <mist/dtsc.h> //DTSC support
#include <mist/mp4.h> //For initdata conversion
///\brief Holds everything unique to the TS Connector
namespace Connector_TS {
///\brief Main function for the TS Connector
///\param conn A socket describing the connection the client.
///\param streamName The stream to connect to.
///\return The exit code of the connector.
int tsConnector(Socket::Connection conn, std::string streamName, std::string trackIDs){
std::string ToPack;
TS::Packet PackData;
std::string DTMIData;
int PacketNumber = 0;
long long unsigned int TimeStamp = 0;
int ThisNaluSize;
char VideoCounter = 0;
char AudioCounter = 0;
bool WritePesHeader;
bool IsKeyFrame;
bool FirstKeyFrame = true;
bool FirstIDRInKeyFrame;
MP4::AVCC avccbox;
bool haveAvcc = false;
DTSC::Stream Strm;
bool inited = false;
Socket::Connection ss;
while (conn.connected()){
if ( !inited){
ss = Util::Stream::getStream(streamName);
if ( !ss.connected()){
#if DEBUG >= 1
fprintf(stderr, "Could not connect to server!\n");
#endif
conn.close();
break;
}
if(trackIDs == ""){
std::stringstream tmpTracks;
// no track ids given? Find the first video and first audio track (if available) and use those!
int videoID = -1;
int audioID = -1;
Strm.waitForMeta(ss);
for (std::map<int,DTSC::Track>::iterator it = Strm.metadata.tracks.begin(); it != Strm.metadata.tracks.end(); it++){
if (audioID == -1 && it->second.type == "audio"){
audioID = it->first;
tmpTracks << " " << it->first;
}
if (videoID == -1 && it->second.type == "video"){
videoID = it->first;
tmpTracks << " " << it->first;
}
} // for iterator
trackIDs += tmpTracks.str();
} // if trackIDs == ""
std::string cmd = "t " + trackIDs + "\ns 0\np\n";
ss.SendNow( cmd );
inited = true;
}
if (ss.spool()){
while (Strm.parsePacket(ss.Received())){
std::stringstream TSBuf;
Socket::Buffer ToPack;
//write PAT and PMT TS packets
if (PacketNumber == 0){
PackData.DefaultPAT();
TSBuf.write(PackData.ToString(), 188);
PackData.DefaultPMT();
TSBuf.write(PackData.ToString(), 188);
PacketNumber += 2;
}
int PIDno = 0;
char * ContCounter = 0;
if (Strm.lastType() == DTSC::VIDEO){
if ( !haveAvcc){
avccbox.setPayload(Strm.metadata.tracks[Strm.getPacket()["trackid"].asInt()].init);
haveAvcc = true;
}
IsKeyFrame = Strm.getPacket().isMember("keyframe");
if (IsKeyFrame){
TimeStamp = (Strm.getPacket()["time"].asInt() * 27000);
}
ToPack.append(avccbox.asAnnexB());
while (Strm.lastData().size() > 4){
ThisNaluSize = (Strm.lastData()[0] << 24) + (Strm.lastData()[1] << 16) + (Strm.lastData()[2] << 8) + Strm.lastData()[3];
Strm.lastData().replace(0, 4, TS::NalHeader, 4);
if (ThisNaluSize + 4 == Strm.lastData().size()){
ToPack.append(Strm.lastData());
break;
}else{
ToPack.append(Strm.lastData().c_str(), ThisNaluSize + 4);
Strm.lastData().erase(0, ThisNaluSize + 4);
}
}
ToPack.prepend(TS::Packet::getPESVideoLeadIn(0ul, Strm.getPacket()["time"].asInt() * 90));
PIDno = 0x100 - 1 + Strm.getPacket()["trackid"].asInt();
ContCounter = &VideoCounter;
}else if (Strm.lastType() == DTSC::AUDIO){
ToPack.append(TS::GetAudioHeader(Strm.lastData().size(), Strm.metadata.tracks[Strm.getPacket()["trackid"].asInt()].init));
ToPack.append(Strm.lastData());
ToPack.prepend(TS::Packet::getPESAudioLeadIn(ToPack.bytes(1073741824ul), Strm.getPacket()["time"].asInt() * 90));
PIDno = 0x100 - 1 + Strm.getPacket()["trackid"].asInt();
ContCounter = &AudioCounter;
IsKeyFrame = false;
}
//initial packet
PackData.Clear();
PackData.PID(PIDno);
PackData.ContinuityCounter(( *ContCounter)++);
PackData.UnitStart(1);
if (IsKeyFrame){
PackData.RandomAccess(1);
PackData.PCR(TimeStamp);
}
unsigned int toSend = PackData.AddStuffing(ToPack.bytes(184));
std::string gonnaSend = ToPack.remove(toSend);
PackData.FillFree(gonnaSend);
TSBuf.write(PackData.ToString(), 188);
PacketNumber++;
//rest of packets
while (ToPack.size()){
PackData.Clear();
PackData.PID(PIDno);
PackData.ContinuityCounter(( *ContCounter)++);
toSend = PackData.AddStuffing(ToPack.bytes(184));
gonnaSend = ToPack.remove(toSend);
PackData.FillFree(gonnaSend);
TSBuf.write(PackData.ToString(), 188);
PacketNumber++;
}
TSBuf.flush();
if (TSBuf.str().size()){
conn.SendNow(TSBuf.str().c_str(), TSBuf.str().size());
TSBuf.str("");
}
TSBuf.str("");
PacketNumber = 0;
}
}else{
Util::sleep(1000);
conn.spool();
}
}
return 0;
}
}
int main(int argc, char ** argv){
Util::Config conf(argv[0], PACKAGE_VERSION);
JSON::Value capa;
capa["desc"] = "Enables the raw MPEG Transport Stream protocol over TCP.";
capa["deps"] = "";
capa["required"]["streamname"]["name"] = "Stream";
capa["required"]["streamname"]["help"] = "What streamname to serve. For multiple streams, add this protocol multiple times using different ports.";
capa["required"]["streamname"]["type"] = "str";
capa["required"]["streamname"]["option"] = "--stream";
capa["optional"]["tracks"]["name"] = "Tracks";
capa["optional"]["tracks"]["help"] = "The track IDs of the stream that this connector will transmit separated by spaces";
capa["optional"]["tracks"]["type"] = "str";
capa["optional"]["tracks"]["option"] = "--tracks";
conf.addOption("streamname",
JSON::fromString("{\"arg\":\"string\",\"short\":\"s\",\"long\":\"stream\",\"help\":\"The name of the stream that this connector will transmit.\"}"));
conf.addOption("tracks",
JSON::fromString("{\"arg\":\"string\",\"value\":[\"\"],\"short\": \"t\",\"long\":\"tracks\",\"help\":\"The track IDs of the stream that this connector will transmit separated by spaces.\"}"));
conf.addConnectorOptions(8888, capa);
bool ret = conf.parseArgs(argc, argv);
if (conf.getBool("json")){
std::cout << capa.toString() << std::endl;
return -1;
}
if (!ret){
std::cerr << "Usage error: missing argument(s)." << std::endl;
conf.printHelp(std::cout);
return 1;
}
Socket::Server server_socket = Socket::Server(conf.getInteger("listen_port"), conf.getString("listen_interface"));
if ( !server_socket.connected()){
return 1;
}
conf.activate();
while (server_socket.connected() && conf.is_active){
Socket::Connection S = server_socket.accept();
if (S.connected()){ //check if the new connection is valid
pid_t myid = fork();
if (myid == 0){ //if new child, start MAINHANDLER
return Connector_TS::tsConnector(S, conf.getString("streamname"), conf.getString("tracks"));
}else{ //otherwise, do nothing or output debugging text
#if DEBUG >= 5
fprintf(stderr, "Spawned new process %i for socket %i\n", (int)myid, S.getSocket());
#endif
}
}
} //while connected
server_socket.close();
return 0;
} //main
<|endoftext|> |
<commit_before>#include <QAction>
#include <QApplication>
#include <QBoxLayout>
#include <QDesktopWidget>
#include "base.h"
#include "nedit.h"
#include "note.h"
#include "nmain.h"
#include "nside.h"
#include "ntabs.h"
#include "menu.h"
#include "proj.h"
#include "psel.h"
#include "svr.h"
#include "recent.h"
#include "state.h"
#include "term.h"
#include "tedit.h"
using namespace std;
Note *note=0;
Note *note2=0;
// ---------------------------------------------------------------------
Note::Note()
{
if (!config.ProjInit)
project.init();
setFocusPolicy(Qt::StrongFocus);
sideBarShow=true;
QVBoxLayout *layout=new QVBoxLayout;
layout->setContentsMargins(layout->contentsMargins());
layout->setSpacing(0);
menuBar = new Menu();
split = new QSplitter(0);
sideBar = new Nside();
#ifdef SMALL_SCREEN
sideBar->hide();
sideBarShow=false;
#endif
mainBar = new Nmain(this);
split->addWidget(sideBar);
split->addWidget(mainBar);
split->setStretchFactor(1,1);
QList<int> w;
w << 175 << 175;
split->setSizes(w);
layout->addWidget(menuBar);
layout->addWidget(split);
layout->setStretchFactor(split,1);
setLayout(layout);
setWindowTitle("[*]edit");
setpos();
menuBar->createActions();
menuBar->createMenus("note");
menuBar->createMenus_fini("note");
setWindowIcon(QIcon(":/images/jgreen.png"));
QMetaObject::connectSlotsByName(this);
}
// ---------------------------------------------------------------------
void Note::activate()
{
activateWindow();
raise();
int n=editIndex();
if (n>=0)
tabs->currentWidget()->setFocus();
}
// ---------------------------------------------------------------------
void Note::changeEvent(QEvent *event)
{
if (NoEvents) return;
if (event->type()==QEvent::ActivationChange && isActiveWindow()) {
setnote(this);
projectenable();
QWidget::changeEvent(event);
}
}
// ---------------------------------------------------------------------
void Note::closeEvent(QCloseEvent *event)
{
Q_UNUSED(event);
closeit();
}
// ---------------------------------------------------------------------
void Note::closeit()
{
if (!saveall()) return;
projectsave();
if (note2) {
note=note2;
note2=0;
note->setFocus();
} else
note=0;
close();
}
// ---------------------------------------------------------------------
int Note::editIndex()
{
return tabs->currentIndex();
}
// ---------------------------------------------------------------------
QString Note::editFile()
{
if (tabs->count()==0) return "";
return ((Nedit *)tabs->currentWidget())->fname;
}
// ---------------------------------------------------------------------
Nedit *Note::editPage()
{
return (Nedit *) tabs->currentWidget();
}
// ---------------------------------------------------------------------
QString Note::editText()
{
return ((Nedit *)tabs->currentWidget())->toPlainText();
}
// ---------------------------------------------------------------------
// close tab with file
void Note::fileclose(QString f)
{
tabs->tabclosefile(f);
}
// ---------------------------------------------------------------------
bool Note::fileopen(QString s,int line)
{
return tabs->tabopen(s,line);
}
// ---------------------------------------------------------------------
void Note::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Escape:
closeit();
default:
QWidget::keyPressEvent(event);
}
}
// ---------------------------------------------------------------------
void Note::keyReleaseEvent(QKeyEvent *event)
{
#ifdef QT_OS_ANDROID
if (event->key() == Qt::Key_Back) {
term->activate();
} else QWidget::keyReleaseEvent(event);
#else
QWidget::keyReleaseEvent(event);
#endif
}
// ---------------------------------------------------------------------
void Note::loadscript(QString s,bool show)
{
if (note->saveall())
tedit->loadscript(s,show);
}
// ---------------------------------------------------------------------
void Note::newtemp()
{
QString f=newtempscript();
cfcreate(f);
openfile1(f);
}
// ---------------------------------------------------------------------
void Note::on_lastprojectAct_triggered()
{
projectsave();
project.open(project.LastId);
projectopen(true);
}
// ---------------------------------------------------------------------
void Note::on_openprojectAct_triggered()
{
new Psel();
}
// ---------------------------------------------------------------------
void Note::on_runallAct_triggered()
{
runlines(true);
}
#ifdef QT_OS_ANDROID
// ---------------------------------------------------------------------
void Note::on_xeditAct_triggered()
{
savecurrent();
QString fn=editFile();
if (fn.isEmpty()) return;
android_exec_host((char *)"android.intent.action.VIEW",fn.prepend("file://").toUtf8().constData(),(char *)"text/plain");
}
// ---------------------------------------------------------------------
void Note::on_reloadfileAct_triggered()
{
Nedit *e=editPage();
if (!e) return;
e->text = cfread(e->file);
e->setPlainText(e->text);
}
#endif
// ---------------------------------------------------------------------
void Note::prettyprint()
{
int n,pos,top;
QString r;
savecurrent();
Nedit *e=editPage();
var_cmd("require PPScript_jp_");
var_set("arg_jpp_",editText());
r=var_cmdr("pplintqt_jpp_ arg_jpp_");
if (r.isEmpty()) return;
if (r.at(0)=='0') {
pos=e->readcurpos();
top=e->readtop();
r.remove(0,1);
settext(r);
e->settop(top);
e->setcurpos(pos);
} else {
r.remove(0,1);
n=r.indexOf(' ');
selectline(r.mid(0,n).toInt());
info ("Format Script",r.mid(n+1));
}
}
// ---------------------------------------------------------------------
void Note::projectenable()
{
bool b=project.Id.size()>0;
foreach(QAction *s, menuBar->ProjectEnable)
s->setEnabled(b);
if (config.ifGit) {
b=project.Git;
foreach(QAction *s, menuBar->GitEnable)
s->setEnabled(b);
}
}
// ---------------------------------------------------------------------
void Note::projectopen(bool b)
{
tabs->projectopen(b);
scriptenable();
projectenable();
}
// ---------------------------------------------------------------------
void Note::projectsave()
{
if (tabs->Id.size())
project.save(tabs->gettablist());
}
// ---------------------------------------------------------------------
bool Note::saveall()
{
return tabs->tabsaveall();
}
// ---------------------------------------------------------------------
void Note::savecurrent()
{
tabs->tabsave(editIndex());
}
// ---------------------------------------------------------------------
void Note::scriptenable()
{
bool b=tabs->count();
menuBar->selMenu->setEnabled(b);
foreach(QAction *s, menuBar->ScriptEnable)
s->setEnabled(b);
}
// ---------------------------------------------------------------------
void Note::selectline(int linenum)
{
editPage()->selectline(linenum);
}
// ---------------------------------------------------------------------
void Note::select_line(QString s)
{
int pos,len;
QString com,hdr,ftr,txt;
QStringList mid;
Nedit *e=editPage();
config.filepos_set(e->fname,e->readtop());
txt=e->readselect_line(&pos,&len);
hdr=txt.mid(0,pos);
mid=txt.mid(pos,len).split('\n');
ftr=txt.mid(pos+len);
mid=select_line1(mid,s,&pos,&len);
e->setPlainText(hdr+mid.join("\n")+ftr);
e->settop(config.filepos_get(e->fname));
e->setselect(pos,len);
siderefresh();
}
// ---------------------------------------------------------------------
QStringList Note::select_line1(QStringList mid,QString s,int *pos, int *len)
{
int i;
QString com, comment, p, t;
if (s=="sort") {
mid.sort();
return mid;
}
if (s=="wrap") {
return mid;
}
comment=editPage()->getcomment();
if (comment.isEmpty()) return mid;
com=comment+" ";
if (s=="minus") {
for(i=0; i<mid.size(); i++) {
p=mid.at(i);
if (matchhead(comment,p) && (!matchhead(com+"----",p))
&& (!matchhead(com+"====",p)))
p=p.mid(comment.size());
if (p.size() && (p.at(0)==' '))
p=p.mid(1);
mid.replace(i,p);
}
*len=mid.join("a").size();
return mid;
}
if (s=="plus") {
for(i=0; i<mid.size(); i++) {
p=mid.at(i);
if (p.size())
p=com+p;
else
p=comment;
mid.replace(i,p);
}
*len=mid.join("a").size();
return mid;
}
if (s=="plusline1")
t.fill('-',57);
else
t.fill('=',57);
t=com + t;
mid.prepend(t);
*pos=*pos+1+t.size();
*len=0;
return mid;
}
// ---------------------------------------------------------------------
void Note::select_text(QString s)
{
int i,pos,len;
QString hdr,mid,ftr,txt;
Nedit *e=editPage();
config.filepos_set(e->fname,e->readtop());
txt=e->readselect_text(&pos,&len);
if (len==0) {
info("Note","No text selected") ;
return;
}
hdr=txt.mid(0,pos);
mid=txt.mid(pos,len);
ftr=txt.mid(pos+len);
if (s=="lower")
mid=mid.toLower();
else if (s=="upper")
mid=mid.toUpper();
else if (s=="toggle") {
QString old=mid;
QString lc=mid.toLower();
mid=mid.toUpper();
for (i=0; i<mid.size(); i++)
if(mid[i]==old[i]) mid[i]=lc[i];
}
e->setPlainText(hdr+mid+ftr);
e->settop(config.filepos_get(e->fname));
e->setselect(pos,0);
siderefresh();
}
// ---------------------------------------------------------------------
void Note::setfont(QFont font)
{
tabs->setfont(font);
}
// ---------------------------------------------------------------------
void Note::setindex(int index)
{
tabs->tabsetindex(index);
}
// ---------------------------------------------------------------------
void Note::setlinenos(bool b)
{
menuBar->viewlinenosAct->setChecked(b);
tabs->setlinenos(b);
}
// ---------------------------------------------------------------------
void Note::setlinewrap(bool b)
{
menuBar->viewlinewrapAct->setChecked(b);
tabs->setlinewrap(b);
}
// ---------------------------------------------------------------------
// for new note or second note
void Note::setpos()
{
int x,y,w,h,wid;
if (note==0) {
x=config.EditPos[0];
y=config.EditPos[1];
w=config.EditPos[2];
h=config.EditPos[3];
} else {
QDesktopWidget *d=qApp->desktop();
QRect s=d->screenGeometry();
wid=s.width();
QPoint p=note->pos();
QSize z=note->size();
x=p.x();
y=p.y();
w=z.width();
h=z.height();
x=(wid > w + 2*x) ? wid-w : 0;
}
move(x,y);
resize(w,h);
}
// ---------------------------------------------------------------------
void Note::settext(QString s)
{
tabs->tabsettext(s);
}
// ---------------------------------------------------------------------
void Note::settitle(QString file, bool mod)
{
QString f,n,s;
if (file.isEmpty()) {
s="Edit";
if (project.Id.size())
s="[" + project.Id + "] - " + s;
setWindowTitle(s);
return;
}
s=cfsname(file);
if (project.Id.size()) n="[" + project.Id + "] - ";
if (file == cpath("~" + project.Id + "/" + s))
f = s;
else
f = project.projectname(file);
setWindowTitle ("[*]" + f + " - " + n + "Edit");
setWindowModified(mod);
}
// ---------------------------------------------------------------------
void Note::siderefresh()
{
sideBar->refresh();
}
// ---------------------------------------------------------------------
void Note::tabclose(int index)
{
tabs->tabclose(index);
scriptenable();
}
<commit_msg>recognise EscClose for Edit windows<commit_after>#include <QAction>
#include <QApplication>
#include <QBoxLayout>
#include <QDesktopWidget>
#include "base.h"
#include "nedit.h"
#include "note.h"
#include "nmain.h"
#include "nside.h"
#include "ntabs.h"
#include "menu.h"
#include "proj.h"
#include "psel.h"
#include "svr.h"
#include "recent.h"
#include "state.h"
#include "term.h"
#include "tedit.h"
using namespace std;
Note *note=0;
Note *note2=0;
// ---------------------------------------------------------------------
Note::Note()
{
if (!config.ProjInit)
project.init();
setFocusPolicy(Qt::StrongFocus);
sideBarShow=true;
QVBoxLayout *layout=new QVBoxLayout;
layout->setContentsMargins(layout->contentsMargins());
layout->setSpacing(0);
menuBar = new Menu();
split = new QSplitter(0);
sideBar = new Nside();
#ifdef SMALL_SCREEN
sideBar->hide();
sideBarShow=false;
#endif
mainBar = new Nmain(this);
split->addWidget(sideBar);
split->addWidget(mainBar);
split->setStretchFactor(1,1);
QList<int> w;
w << 175 << 175;
split->setSizes(w);
layout->addWidget(menuBar);
layout->addWidget(split);
layout->setStretchFactor(split,1);
setLayout(layout);
setWindowTitle("[*]edit");
setpos();
menuBar->createActions();
menuBar->createMenus("note");
menuBar->createMenus_fini("note");
setWindowIcon(QIcon(":/images/jgreen.png"));
QMetaObject::connectSlotsByName(this);
}
// ---------------------------------------------------------------------
void Note::activate()
{
activateWindow();
raise();
int n=editIndex();
if (n>=0)
tabs->currentWidget()->setFocus();
}
// ---------------------------------------------------------------------
void Note::changeEvent(QEvent *event)
{
if (NoEvents) return;
if (event->type()==QEvent::ActivationChange && isActiveWindow()) {
setnote(this);
projectenable();
QWidget::changeEvent(event);
}
}
// ---------------------------------------------------------------------
void Note::closeEvent(QCloseEvent *event)
{
Q_UNUSED(event);
closeit();
}
// ---------------------------------------------------------------------
void Note::closeit()
{
if (!saveall()) return;
projectsave();
if (note2) {
note=note2;
note2=0;
note->setFocus();
} else
note=0;
close();
}
// ---------------------------------------------------------------------
int Note::editIndex()
{
return tabs->currentIndex();
}
// ---------------------------------------------------------------------
QString Note::editFile()
{
if (tabs->count()==0) return "";
return ((Nedit *)tabs->currentWidget())->fname;
}
// ---------------------------------------------------------------------
Nedit *Note::editPage()
{
return (Nedit *) tabs->currentWidget();
}
// ---------------------------------------------------------------------
QString Note::editText()
{
return ((Nedit *)tabs->currentWidget())->toPlainText();
}
// ---------------------------------------------------------------------
// close tab with file
void Note::fileclose(QString f)
{
tabs->tabclosefile(f);
}
// ---------------------------------------------------------------------
bool Note::fileopen(QString s,int line)
{
return tabs->tabopen(s,line);
}
// ---------------------------------------------------------------------
void Note::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Escape:
if (config.EscClose) {
closeit();
}
default:
QWidget::keyPressEvent(event);
}
}
// ---------------------------------------------------------------------
void Note::keyReleaseEvent(QKeyEvent *event)
{
#ifdef QT_OS_ANDROID
if (event->key() == Qt::Key_Back) {
term->activate();
} else QWidget::keyReleaseEvent(event);
#else
QWidget::keyReleaseEvent(event);
#endif
}
// ---------------------------------------------------------------------
void Note::loadscript(QString s,bool show)
{
if (note->saveall())
tedit->loadscript(s,show);
}
// ---------------------------------------------------------------------
void Note::newtemp()
{
QString f=newtempscript();
cfcreate(f);
openfile1(f);
}
// ---------------------------------------------------------------------
void Note::on_lastprojectAct_triggered()
{
projectsave();
project.open(project.LastId);
projectopen(true);
}
// ---------------------------------------------------------------------
void Note::on_openprojectAct_triggered()
{
new Psel();
}
// ---------------------------------------------------------------------
void Note::on_runallAct_triggered()
{
runlines(true);
}
#ifdef QT_OS_ANDROID
// ---------------------------------------------------------------------
void Note::on_xeditAct_triggered()
{
savecurrent();
QString fn=editFile();
if (fn.isEmpty()) return;
android_exec_host((char *)"android.intent.action.VIEW",fn.prepend("file://").toUtf8().constData(),(char *)"text/plain");
}
// ---------------------------------------------------------------------
void Note::on_reloadfileAct_triggered()
{
Nedit *e=editPage();
if (!e) return;
e->text = cfread(e->file);
e->setPlainText(e->text);
}
#endif
// ---------------------------------------------------------------------
void Note::prettyprint()
{
int n,pos,top;
QString r;
savecurrent();
Nedit *e=editPage();
var_cmd("require PPScript_jp_");
var_set("arg_jpp_",editText());
r=var_cmdr("pplintqt_jpp_ arg_jpp_");
if (r.isEmpty()) return;
if (r.at(0)=='0') {
pos=e->readcurpos();
top=e->readtop();
r.remove(0,1);
settext(r);
e->settop(top);
e->setcurpos(pos);
} else {
r.remove(0,1);
n=r.indexOf(' ');
selectline(r.mid(0,n).toInt());
info ("Format Script",r.mid(n+1));
}
}
// ---------------------------------------------------------------------
void Note::projectenable()
{
bool b=project.Id.size()>0;
foreach(QAction *s, menuBar->ProjectEnable)
s->setEnabled(b);
if (config.ifGit) {
b=project.Git;
foreach(QAction *s, menuBar->GitEnable)
s->setEnabled(b);
}
}
// ---------------------------------------------------------------------
void Note::projectopen(bool b)
{
tabs->projectopen(b);
scriptenable();
projectenable();
}
// ---------------------------------------------------------------------
void Note::projectsave()
{
if (tabs->Id.size())
project.save(tabs->gettablist());
}
// ---------------------------------------------------------------------
bool Note::saveall()
{
return tabs->tabsaveall();
}
// ---------------------------------------------------------------------
void Note::savecurrent()
{
tabs->tabsave(editIndex());
}
// ---------------------------------------------------------------------
void Note::scriptenable()
{
bool b=tabs->count();
menuBar->selMenu->setEnabled(b);
foreach(QAction *s, menuBar->ScriptEnable)
s->setEnabled(b);
}
// ---------------------------------------------------------------------
void Note::selectline(int linenum)
{
editPage()->selectline(linenum);
}
// ---------------------------------------------------------------------
void Note::select_line(QString s)
{
int pos,len;
QString com,hdr,ftr,txt;
QStringList mid;
Nedit *e=editPage();
config.filepos_set(e->fname,e->readtop());
txt=e->readselect_line(&pos,&len);
hdr=txt.mid(0,pos);
mid=txt.mid(pos,len).split('\n');
ftr=txt.mid(pos+len);
mid=select_line1(mid,s,&pos,&len);
e->setPlainText(hdr+mid.join("\n")+ftr);
e->settop(config.filepos_get(e->fname));
e->setselect(pos,len);
siderefresh();
}
// ---------------------------------------------------------------------
QStringList Note::select_line1(QStringList mid,QString s,int *pos, int *len)
{
int i;
QString com, comment, p, t;
if (s=="sort") {
mid.sort();
return mid;
}
if (s=="wrap") {
return mid;
}
comment=editPage()->getcomment();
if (comment.isEmpty()) return mid;
com=comment+" ";
if (s=="minus") {
for(i=0; i<mid.size(); i++) {
p=mid.at(i);
if (matchhead(comment,p) && (!matchhead(com+"----",p))
&& (!matchhead(com+"====",p)))
p=p.mid(comment.size());
if (p.size() && (p.at(0)==' '))
p=p.mid(1);
mid.replace(i,p);
}
*len=mid.join("a").size();
return mid;
}
if (s=="plus") {
for(i=0; i<mid.size(); i++) {
p=mid.at(i);
if (p.size())
p=com+p;
else
p=comment;
mid.replace(i,p);
}
*len=mid.join("a").size();
return mid;
}
if (s=="plusline1")
t.fill('-',57);
else
t.fill('=',57);
t=com + t;
mid.prepend(t);
*pos=*pos+1+t.size();
*len=0;
return mid;
}
// ---------------------------------------------------------------------
void Note::select_text(QString s)
{
int i,pos,len;
QString hdr,mid,ftr,txt;
Nedit *e=editPage();
config.filepos_set(e->fname,e->readtop());
txt=e->readselect_text(&pos,&len);
if (len==0) {
info("Note","No text selected") ;
return;
}
hdr=txt.mid(0,pos);
mid=txt.mid(pos,len);
ftr=txt.mid(pos+len);
if (s=="lower")
mid=mid.toLower();
else if (s=="upper")
mid=mid.toUpper();
else if (s=="toggle") {
QString old=mid;
QString lc=mid.toLower();
mid=mid.toUpper();
for (i=0; i<mid.size(); i++)
if(mid[i]==old[i]) mid[i]=lc[i];
}
e->setPlainText(hdr+mid+ftr);
e->settop(config.filepos_get(e->fname));
e->setselect(pos,0);
siderefresh();
}
// ---------------------------------------------------------------------
void Note::setfont(QFont font)
{
tabs->setfont(font);
}
// ---------------------------------------------------------------------
void Note::setindex(int index)
{
tabs->tabsetindex(index);
}
// ---------------------------------------------------------------------
void Note::setlinenos(bool b)
{
menuBar->viewlinenosAct->setChecked(b);
tabs->setlinenos(b);
}
// ---------------------------------------------------------------------
void Note::setlinewrap(bool b)
{
menuBar->viewlinewrapAct->setChecked(b);
tabs->setlinewrap(b);
}
// ---------------------------------------------------------------------
// for new note or second note
void Note::setpos()
{
int x,y,w,h,wid;
if (note==0) {
x=config.EditPos[0];
y=config.EditPos[1];
w=config.EditPos[2];
h=config.EditPos[3];
} else {
QDesktopWidget *d=qApp->desktop();
QRect s=d->screenGeometry();
wid=s.width();
QPoint p=note->pos();
QSize z=note->size();
x=p.x();
y=p.y();
w=z.width();
h=z.height();
x=(wid > w + 2*x) ? wid-w : 0;
}
move(x,y);
resize(w,h);
}
// ---------------------------------------------------------------------
void Note::settext(QString s)
{
tabs->tabsettext(s);
}
// ---------------------------------------------------------------------
void Note::settitle(QString file, bool mod)
{
QString f,n,s;
if (file.isEmpty()) {
s="Edit";
if (project.Id.size())
s="[" + project.Id + "] - " + s;
setWindowTitle(s);
return;
}
s=cfsname(file);
if (project.Id.size()) n="[" + project.Id + "] - ";
if (file == cpath("~" + project.Id + "/" + s))
f = s;
else
f = project.projectname(file);
setWindowTitle ("[*]" + f + " - " + n + "Edit");
setWindowModified(mod);
}
// ---------------------------------------------------------------------
void Note::siderefresh()
{
sideBar->refresh();
}
// ---------------------------------------------------------------------
void Note::tabclose(int index)
{
tabs->tabclose(index);
scriptenable();
}
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.