本文整理汇总了C++中boost类的典型用法代码示例。如果您正苦于以下问题:C++ boost类的具体用法?C++ boost怎么用?C++ boost使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了boost类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: integrate_slowpath
long double integrate_slowpath(
boost::function<long double(long double)> const& f
, long double lower_bound
, long double upper_bound
, long double tolerance
, long double increment
) {
long double total_area = 0.0L, temp_increment = increment;
boost::uint64_t count_depth = 0
, last_count = 0
, iterations = 0
, rollbacks = 0
, refinements = 0;
for (long double i = lower_bound; i < upper_bound; ++iterations)
{
const long double fi = f(i);
boost::uint64_t count = 0;
// When the difference between the function value at the middle of the
// increment and the start of the increment is too big, decrease the
// increment by a factor of two and retry.
while ((abs(f(i + (temp_increment / 2.0L)) - fi)) > tolerance)
{
++count;
temp_increment /= 2.0L; // TODO: ensure that I am optimized away,
// as I am computed at the head of the while
// loop.
}
if (count != last_count)
cout << ( format("growth rate of increment changed from 1/2^%1% to "
"1/2^%2% at f(%3%)\n")
% (last_count + count_depth)
% (count + count_depth)
% group(setprecision(ld_precision), i));
refinements += count;
last_count = count;
count_depth += count;
total_area += fi * temp_increment;
i += temp_increment;
// Rollback one level of resolution at the end of each for-loop
// iteration to avoid unneeded resolution, if we were not within the
// tolerance.
if (count)
{
++rollbacks;
--count_depth;
temp_increment *= 2.0L;
}
}
cout << ( format("computation completed in %1% iterations\n"
"%2% refinements occurred\n"
"%3% rollbacks were performed\n")
% iterations
% refinements
% rollbacks);
return total_area;
}
示例2: main
int main(){
using namespace std;
using boost::format;
using boost::io::group;
using boost::io::str;
string s;
stringstream oss;
//------------------------------------------------------------------------
// storing the parsed format-string in a 'formatter' :
// format objects are regular objects that can be copied, assigned,
// fed arguments, dumped to a stream, re-fed arguments, etc...
// So users can use them the way they like.
format fmter("%1% %2% %3% %1% \n");
fmter % 10 % 20 % 30;
cout << fmter;
// prints "10 20 30 10 \n"
// note that once the fmter got all its arguments,
// the formatted string stays available (until next call to '%')
// The result is available via function str() or stream's << :
cout << fmter;
// prints the same string again.
// once you call operator% again, arguments are cleared inside the object
// and it is an error to ask for the conversion string before feeding all arguments :
fmter % 1001;
try { cout << fmter; }
catch (boost::io::too_few_args& exc) {
cout << exc.what() << "***Dont worry, that was planned\n";
}
// we just need to feed the last two arguments, and it will be ready for output again :
cout << fmter % 1002 % 1003;
// prints "1001 1002 1003 1001 \n"
cout << fmter % 10 % 1 % 2;
// prints "10 1 2 10 \n"
//---------------------------------------------------------------
// using format objects
// modify the formatting options for a given directive :
fmter = format("%1% %2% %3% %2% %1% \n");
fmter.modify_item(4, group(setfill('_'), hex, showbase, setw(5)) );
cout << fmter % 1 % 2 % 3;
// prints "1 2 3 __0x2 1 \n"
// bind one of the argumets :
fmter.bind_arg(1, 18);
cout << fmter % group(hex, showbase, 20) % 30; // %2 is 20, and 20 == 0x14
// prints "18 0x14 30 _0x14 18 \n"
fmter.modify_item(4, setw(0)); // cancels previous width-5
fmter.bind_arg(1, 77); // replace 18 with 77 for first argument.
cout << fmter % 10 % 20;
// prints "77 10 20 0xa 77 \n"
try
{
cout << fmter % 6 % 7 % 8; // Aye ! too many args, because arg1 is bound already
}
catch (boost::io::too_many_args& exc)
{
cout << exc.what() << "***Dont worry, that was planned\n";
}
// clear() clears regular arguments, but not bound arguments :
fmter.clear();
cout << fmter % 2 % 3;
// prints "77 2 3 0x2 77 \n"
// use clear_binds() to clear both regular AND bound arguments :
fmter.clear_binds();
cout << fmter % 1 % 2 % 3;
// prints "1 2 3 0x2 1 \n"
// setting desired exceptions :
fmter.exceptions( boost::io::all_error_bits ^( boost::io::too_many_args_bit ) );
cout << fmter % 1 % 2 % 3 % 4 % 5 % 6 ;
// -----------------------------------------------------------
// misc:
// unsupported printf directives %n and asterisk-fields are purely ignored.
// do *NOT* provide an argument for them, it is an error.
cout << format("|%5d| %n") % 7 << endl;
// prints "| 7| "
cout << format("|%*.*d|") % 7 << endl;
// prints "|7|"
//.........这里部分代码省略.........
示例3: log_add
bool Application::init()
{
//
// seed da rand
//
std::srand(static_cast<unsigned int>(timer.get_mms()));
//
// setup new old time
//
oldtime = timer.get_dt_s();
//
// init logger
//
f_log = std::fopen(BIN("planetz.log").c_str(),"w");
log_add(LOG_STREAM(f_log),LOG_PRINTER(std::vfprintf));
#ifdef _RELEASE
log_set_lev(INFO);
#endif
//
// init graphics
//
if( !gfx.window_init(window.getW(),window.getH()) ) return false;
plz.setMaterials( data_mgr.loadMaterials() );
plz.setTextures ( data_mgr.loadTextures () );
//
// init user interface
//
if( !ui.init() ) return false;
// FIXME: where should be this done?
ui.sigVideoResize.
connect( 0 , bind(&Window::reshape_window,&window,_1,_2));
ui.sigVideoResize.
connect( 1 , bind(&GFX::Gfx::reshape_window,&gfx,_1,_2) );
ui.sigVideoResize.
connect( 2 , bind(&UI::PlanetzPicker::resize,&picker,_1,_2) );
ui.add_listener( &setter , 1 );
ui.add_listener( &camera , 2 );
ui.sigKeyDown.
connect( bind(&GFX::Background::on_key_down,&bkg,_1) );
ui.sigMouseMotion.
connect( bind(&GFX::Background::on_mouse_motion,&bkg,_1,_2));
ui.sigMouseButtonUp.
connect( bind(&GFX::Background::on_button_up,&bkg,_1,_2,_3));
ui.sigMouseButtonDown.
connect(1,bind(&GFX::Background::on_button_down,&bkg,_1,_2,_3));
ui.sigMouseButtonDown.
connect( bind(&UI::PlanetzPicker::on_button_down,&picker,_1,_2,_3) );
camera.sigCamChanged.
connect( 2 , bind(&GFX::DeferRender::on_camera_angle_changed,&plz,_1) );
picker.sigPlanetPicked.
connect( bind(&Application::set_picked_planet,this,_1) );
#ifndef _RELEASE
picker.sigPlanetPicked.
connect( bind(&PlanetPrinter::print,&pprnt,_1));
#endif
#ifndef _NOGUI
//
// init graphical user interface
//
try {
pl = new PlanetzLayout( config );
} catch(CEGUI::InvalidRequestException e) {
log_printf(CRITICAL,"CEGUI exception: %s\n",e.getMessage().c_str());
return false;
}
ui.set_layout(pl);
// pl->on_cam_speed_changed.connect(
// bind( &UI::CameraMgr::update,&camera
// ,UI::CameraMgr::FREELOOK,&boost::lambda::_1) );
pl->on_cam_speed_changed.connect( bind(&Application::set_cam_speed,this,_1) );
pl->on_sim_speed_changed.connect( bind(&Application::set_phx_speed,this,_1) );
pl->on_pause_click.connect( bind(&Application::pause_toggle,this) );
pl->on_reset_click.connect( bind(&Application::reset,this) );
pl->on_save.connect( 1, bind(&MEM::DataFlowMgr::save,&data_mgr,_1) );
pl->on_save.connect( 0, bind(&MEM::MISC::PlanetHolderCleaner::forceFilter,&phcleaner) );
pl->on_load.connect( bind(&MEM::DataFlowMgr::load,&data_mgr,_1) );
pl->on_load.connect( bind(&Application::pause_anim,this) );
pl->on_load.connect( bind(&GFX::PlanetsTracer::clear,&trace) );
pl->on_load.connect( bind(&UI::CameraMgr::clear,&camera) );
pl->on_load.connect( bind(&UI::PlanetzSetter::clear,&setter) );
pl->on_load.connect( bind(&PlanetzLayout::hide_show_window,pl) );
pl->on_config_changed.connect(bind(&GFX::Gfx::update_configuration,&gfx,_1));
pl->on_config_changed.connect(bind(&Application::update_configuration,this,_1));
pl->on_planet_changed.connect( bind(&UI::PlanetzSetter::update,&setter,_1) );
pl->on_planet_change.connect( bind(&UI::PlanetzSetter::change,&setter,_1) );
//.........这里部分代码省略.........
示例4: test_main
int test_main(int, char* [])
{
using namespace std;
using boost::format;
using boost::io::group;
using boost::str;
Rational r(16,9);
string s;
s = str(format("%5%. %5$=6s . %1% format %5%, c'%3% %1% %2%.\n")
% "le" % "bonheur" % "est" % "trop" % group(setfill('_'), "bref") );
if(s != "bref. _bref_ . le format bref, c'est le bonheur.\n") {
cerr << s;
BOOST_ERROR("centered alignement : formatting result incorrect");
}
s = str(format("%+8d %-8d\n") % r % r );
if(s != " +16/+9 16/9 \n") {
cerr << s;
BOOST_ERROR("(user-type) formatting result incorrect");
}
s = str(format("[%0+4d %0+8d %-08d]\n") % 8 % r % r);
if(s != "[+008 +0016/+9 16/9 ]\n") {
cerr << s;
BOOST_ERROR("(zero-padded user-type) formatting result incorrect");
}
s = str( format("%1%, %20T_ (%|2$5|,%|3$5|)\n") % "98765" % 1326 % 88 ) ;
if( s != "98765, _____________ ( 1326, 88)\n" )
BOOST_ERROR("(tabulation) formatting result incorrect");
s = str( format("%s, %|20t|=") % 88 ) ;
if( s != "88, =" ) {
cout << s << endl;
BOOST_ERROR("(tabulation) formatting result incorrect");
}
s = str(format("%.2s %8c.\n") % "root" % "user" );
if(s != "ro u.\n") {
cerr << s;
BOOST_ERROR("(truncation) formatting result incorrect");
}
// width in format-string is overridden by setw manipulator :
s = str( format("%|1$4| %|1$|") % group(setfill('0'), setw(6), 1) );
if( s!= "000001 000001")
BOOST_ERROR("width in format VS in argument misbehaved");
s = str( format("%|=s|") % group(setfill('_'), setw(6), r) );
if( s!= "_16/9_") {
cerr << s << endl;
BOOST_ERROR("width in group context is not handled correctly");
}
// options that uses internal alignment : + 0 #
s = str( format("%+6d %0#6x %s\n") % 342 % 33 % "ok" );
if( s !=" +342 0x0021 ok\n")
BOOST_ERROR("(flags +, 0, or #) formatting result incorrect");
// flags in the format string are not sticky
// and hex in argument overrrides type-char d (->decimal) :
s = str( format("%2$#4d %|1$4| %|2$#4| %|3$|")
% 101
% group(setfill('_'), hex, 2)
% 103 );
if(s != "_0x2 101 _0x2 103")
BOOST_ERROR("formatting error. (not-restoring state ?)");
// flag '0' is tricky .
// left-align cancels '0':
s = str( format("%2$0#12X %2$0#-12d %1$0#10d \n") % -20 % 10 );
if( s != "0X000000000A 10 -000000020 \n") {
cerr << s;
BOOST_ERROR("formatting error. (flag 0)");
}
return 0;
}
示例5: test
void test()
{
BOOST_TEST( UDT_use_count == 0 ); // reality check
// test scoped_ptr with a built-in type
long * lp = new long;
boost::scoped_ptr<long> sp ( lp );
BOOST_TEST( sp.get() == lp );
BOOST_TEST( lp == sp.get() );
BOOST_TEST( &*sp == lp );
*sp = 1234568901L;
BOOST_TEST( *sp == 1234568901L );
BOOST_TEST( *lp == 1234568901L );
ck( static_cast<long*>(sp.get()), 1234568901L );
ck( lp, *sp );
sp.reset();
BOOST_TEST( sp.get() == 0 );
// test scoped_ptr with a user defined type
boost::scoped_ptr<UDT> udt_sp ( new UDT( 999888777 ) );
BOOST_TEST( udt_sp->value() == 999888777 );
udt_sp.reset();
udt_sp.reset( new UDT( 111222333 ) );
BOOST_TEST( udt_sp->value() == 111222333 );
udt_sp.reset( new UDT( 333222111 ) );
BOOST_TEST( udt_sp->value() == 333222111 );
// test scoped_array with a build-in type
char * sap = new char [ 100 ];
boost::scoped_array<char> sa ( sap );
BOOST_TEST( sa.get() == sap );
BOOST_TEST( sap == sa.get() );
strcpy( sa.get(), "Hot Dog with mustard and relish" );
BOOST_TEST( strcmp( sa.get(), "Hot Dog with mustard and relish" ) == 0 );
BOOST_TEST( strcmp( sap, "Hot Dog with mustard and relish" ) == 0 );
BOOST_TEST( sa[0] == 'H' );
BOOST_TEST( sa[30] == 'h' );
sa[0] = 'N';
sa[4] = 'd';
BOOST_TEST( strcmp( sap, "Not dog with mustard and relish" ) == 0 );
sa.reset();
BOOST_TEST( sa.get() == 0 );
// test shared_ptr with a built-in type
int * ip = new int;
boost::shared_ptr<int> cp ( ip );
BOOST_TEST( ip == cp.get() );
BOOST_TEST( cp.use_count() == 1 );
*cp = 54321;
BOOST_TEST( *cp == 54321 );
BOOST_TEST( *ip == 54321 );
ck( static_cast<int*>(cp.get()), 54321 );
ck( static_cast<int*>(ip), *cp );
boost::shared_ptr<int> cp2 ( cp );
BOOST_TEST( ip == cp2.get() );
BOOST_TEST( cp.use_count() == 2 );
BOOST_TEST( cp2.use_count() == 2 );
BOOST_TEST( *cp == 54321 );
BOOST_TEST( *cp2 == 54321 );
ck( static_cast<int*>(cp2.get()), 54321 );
ck( static_cast<int*>(ip), *cp2 );
boost::shared_ptr<int> cp3 ( cp );
BOOST_TEST( cp.use_count() == 3 );
BOOST_TEST( cp2.use_count() == 3 );
BOOST_TEST( cp3.use_count() == 3 );
cp.reset();
BOOST_TEST( cp2.use_count() == 2 );
BOOST_TEST( cp3.use_count() == 2 );
cp.reset( new int );
*cp = 98765;
BOOST_TEST( *cp == 98765 );
*cp3 = 87654;
BOOST_TEST( *cp3 == 87654 );
BOOST_TEST( *cp2 == 87654 );
cp.swap( cp3 );
BOOST_TEST( *cp == 87654 );
BOOST_TEST( *cp2 == 87654 );
BOOST_TEST( *cp3 == 98765 );
cp.swap( cp3 );
BOOST_TEST( *cp == 98765 );
BOOST_TEST( *cp2 == 87654 );
BOOST_TEST( *cp3 == 87654 );
cp2 = cp2;
BOOST_TEST( cp2.use_count() == 2 );
BOOST_TEST( *cp2 == 87654 );
cp = cp2;
BOOST_TEST( cp2.use_count() == 3 );
BOOST_TEST( *cp2 == 87654 );
BOOST_TEST( cp.use_count() == 3 );
BOOST_TEST( *cp == 87654 );
//.........这里部分代码省略.........
示例6: BOOST_CHECK
void InputRule::unitTest() {
BOOST_CHECK(true);
sqlite3* db;
// // test Ruleset class
// path dbFileName = initial_path<path>()/"unitTest_InputRule.db3";
//
// if (exists(dbFileName))
// boost::filesystem::remove(dbFileName);
//
// if(sqlite3_open(dbFileName.file_string().c_str(), &db)) {
if(sqlite3_open(":memory:", &db)) {
sqlite3_close(db);
throw std::runtime_error("could not open database file");
}
BOOST_REQUIRE(db!=NULL);
BOOST_CHECKPOINT("create Tables");
InputRule::createTables(db);
Replacement::createTables(db);
Replacements::createTables(db);
Gem::createTables(db);
BOOST_CHECKPOINT("InputRule constructor(regex)");
InputRule ruleAlpha(db, regex("(.*)\\.avi"), -1);
InputRule ruleBeta(db, regex("(.*)\\.mpg"), -1);
InputRule ruleGamma(db, regex("(.*)\\.jpg"), -1);
ruleAlpha.updateGems("$fileName$");
ruleBeta.updateGems("$fileName$");
ruleGamma.updateGems("$fileName$");
BOOST_CHECK(ruleAlpha.getGems().size() == 1);
BOOST_CHECK(ruleBeta.getGems().size() == 1);
BOOST_CHECK(ruleGamma.getGems().size() == 1);
BOOST_CHECKPOINT("get gem");
BOOST_REQUIRE(ruleAlpha.getGems().size() == 1);
BOOST_CHECK(ruleAlpha.getGems()[0]->getName() == "fileName");
BOOST_CHECKPOINT("getRegex(), first time");
BOOST_CHECK( ruleAlpha.getRegex() == "(.*)\\.avi" );
BOOST_CHECK( ruleBeta.getRegex() == "(.*)\\.mpg" );
BOOST_CHECK( ruleGamma.getRegex() == "(.*)\\.jpg" );
BOOST_CHECKPOINT("getRegex(), second time");
BOOST_CHECK( ruleAlpha.getRegex() == "(.*)\\.avi" );
BOOST_CHECK( ruleBeta.getRegex() == "(.*)\\.mpg" );
BOOST_CHECK( ruleGamma.getRegex() == "(.*)\\.jpg" );
vector<GemValue> gems;
BOOST_CHECKPOINT("applyTo()");
BOOST_CHECK(ruleAlpha.getGems().size() == 1);
BOOST_CHECK_NO_THROW(ruleAlpha.applyTo("Test.avi", gems, true));
BOOST_CHECK_NO_THROW(!ruleAlpha.applyTo("Test.mpg", gems, true));
BOOST_CHECK_NO_THROW(!ruleAlpha.applyTo("Test.jpg", gems, true));
BOOST_CHECKPOINT("applyTo() 048f97dc");
BOOST_CHECK(!ruleBeta.applyTo("Test.avi", gems, true));
BOOST_CHECK(ruleBeta.applyTo("Test.mpg", gems, true));
BOOST_CHECK(!ruleBeta.applyTo("Test.jpg", gems, true));
BOOST_CHECKPOINT("applyTo() 092aed5a");
BOOST_CHECK(!ruleGamma.applyTo("Test.avi", gems, true));
BOOST_CHECK(!ruleGamma.applyTo("Test.mpg", gems, true));
BOOST_CHECK(ruleGamma.applyTo("Test.jpg", gems, true));
BOOST_CHECKPOINT("applyTo() 6d984e20");
BOOST_CHECK(ruleAlpha.applyTo("Name mit Blank.avi", gems, true));
BOOST_CHECK(!ruleAlpha.applyTo("Name mit Blank.mpg", gems, true));
BOOST_CHECK(!ruleAlpha.applyTo("Name mit Blank.jpg", gems, true));
BOOST_CHECK(!ruleBeta.applyTo("Name mit Blank.avi", gems, true));
BOOST_CHECK(ruleBeta.applyTo("Name mit Blank.mpg", gems, true));
BOOST_CHECK(!ruleBeta.applyTo("Name mit Blank.jpg", gems, true));
BOOST_CHECK(!ruleGamma.applyTo("Name mit Blank.avi", gems, true));
BOOST_CHECK(!ruleGamma.applyTo("Name mit Blank.mpg", gems, true));
BOOST_CHECK(ruleGamma.applyTo("Name mit Blank.jpg", gems, true));
BOOST_CHECKPOINT("setRegex()");
BOOST_CHECK(ruleAlpha.setRegex("([\\w ]*)\\.avi"));
BOOST_CHECK(!ruleAlpha.setRegex("([\\w ]*)\\.mpg"));
BOOST_CHECK(!ruleAlpha.setRegex("Test\\..*"));
BOOST_CHECK(!ruleBeta.setRegex("([\\w ]*)\\.avi"));
BOOST_CHECK(ruleBeta.setRegex("([\\w ]*)\\.mpg"));
BOOST_CHECK(!ruleBeta.setRegex("Test\\..*"));
BOOST_CHECK(ruleGamma.setRegex("([\\w ]*)\\.jpg"));
BOOST_CHECK(!ruleGamma.setRegex("([\\w ]*)\\.mpg"));
BOOST_CHECK(!ruleGamma.setRegex("Test\\..*"));
BOOST_CHECKPOINT("getRegex(), third time");
BOOST_CHECK( ruleAlpha.getRegex() == "([\\w ]*)\\.avi" );
BOOST_CHECK( ruleBeta.getRegex() == "([\\w ]*)\\.mpg" );
BOOST_CHECK( ruleGamma.getRegex() == "([\\w ]*)\\.jpg" );
//.........这里部分代码省略.........
示例7: initialize
core::Error initialize()
{
git::initialize();
svn::initialize();
// http endpoints
using boost::bind;
using namespace module_context;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(registerRpcMethod, "vcs_clone", vcsClone));
Error error = initBlock.execute();
if (error)
return error;
// If VCS is disabled, or we're not in a project, do nothing
const projects::ProjectContext& projContext = projects::projectContext();
FilePath workingDir = projContext.directory();
if (!session::options().allowVcs() || !userSettings().vcsEnabled() || workingDir.empty())
return Success();
// If Git or SVN was explicitly specified, choose it if valid
projects::RProjectVcsOptions vcsOptions;
if (projContext.hasProject())
{
Error vcsError = projContext.readVcsOptions(&vcsOptions);
if (vcsError)
LOG_ERROR(vcsError);
}
if (vcsOptions.vcsOverride == kVcsIdNone)
{
return Success();
}
else if (vcsOptions.vcsOverride == git::kVcsId)
{
if (git::isGitInstalled() && git::isGitDirectory(workingDir))
return git::initializeGit(workingDir);
return Success();
}
else if (vcsOptions.vcsOverride == svn::kVcsId)
{
if (svn::isSvnInstalled() && svn::isSvnDirectory(workingDir))
return svn::initializeSvn(workingDir);
return Success();
}
if (git::isGitInstalled() && git::isGitDirectory(workingDir))
{
return git::initializeGit(workingDir);
}
else if (svn::isSvnInstalled() && svn::isSvnDirectory(workingDir))
{
return svn::initializeSvn(workingDir);
}
else
{
return Success(); // none specified or detected
}
}
示例8: if
/// \brief Combine a dssp_file and pdb representing the same structure in a sensible protein object
///
/// \relates dssp_file
///
/// \TODO Consider taking an ostream_ref_opt argument rather than assuming cerr
/// (fix all errors, *then* provide default of boost::none)
protein cath::file::protein_from_dssp_and_pdb(const dssp_file &arg_dssp_file, ///< The dssp_file object for a given structure
const pdb &arg_pdb_file, ///< The dssp_file object for a given structure
const dssp_skip_policy &arg_dssp_skip_policy, ///< Whether to exclude residues that are in the PDB but not the DSSP
const string &arg_name, ///< The name to set as the title of the protein
const ostream_ref_opt &arg_ostream ///< An optional reference to an ostream to which any logging should be sent
) {
// Build a rough protein object from the pdb object
const auto pdb_protein = build_protein_of_pdb(
arg_pdb_file,
arg_ostream,
( arg_dssp_skip_policy == dssp_skip_policy::SKIP__BREAK_ANGLES )
? dssp_skip_policy::DONT_SKIP__BREAK_ANGLES
: arg_dssp_skip_policy
);
const auto pdb_skip_indices = get_protein_res_indices_that_dssp_might_skip( arg_pdb_file, arg_ostream );
// Grab the number of residues in the protein and dssp_file objects
const auto num_dssp_residues = arg_dssp_file.get_num_residues();
const auto num_pdb_residues = pdb_protein.get_length();
// Grab the residues names from the DSSP and PDB and then tally them up
const auto pdb_res_names = get_residue_ids ( pdb_protein );
const auto dssp_res_names = get_residue_ids ( arg_dssp_file, false );
const auto alignment = tally_residue_ids(
pdb_res_names,
dssp_res_names,
false,
true,
pdb_skip_indices
);
// Prepare a list of new residue to populate
residue_vec new_residues;
new_residues.reserve( ( arg_dssp_skip_policy == dssp_skip_policy::SKIP__BREAK_ANGLES ) ? num_dssp_residues : num_pdb_residues );
// Loop over the residues
size_t alignment_ctr = 0;
for (const size_t &pdb_residue_ctr : irange( 0_z, num_pdb_residues ) ) {
const residue &the_pdb_residue = pdb_protein.get_residue_ref_of_index( pdb_residue_ctr );
// If this PDB residue is in the alignment then it can be combined with the equivalent DSSP residue
const bool is_in_alignment = ( (alignment_ctr < alignment.size() ) && ( alignment[alignment_ctr].first == pdb_residue_ctr ) );
if ( is_in_alignment ) {
// Combine the two residues and add them to the back
const residue &the_dssp_residue = arg_dssp_file.get_residue_of_index( alignment[alignment_ctr].second );
new_residues.push_back(
combine_residues_from_dssp_and_pdb(
the_dssp_residue,
the_pdb_residue,
angle_skipping_of_dssp_skip_policy( arg_dssp_skip_policy )
)
);
// Increment the alignment counter
++alignment_ctr;
}
else if ( res_skipping_of_dssp_skip_policy( arg_dssp_skip_policy ) == dssp_skip_res_skipping::DONT_SKIP ) {
new_residues.push_back( the_pdb_residue );
}
}
// Construct a new protein from the new list of residues
return { arg_name, new_residues };
}
示例9: readFromMultilineAdjacencyList
void readFromMultilineAdjacencyList( const string& fname, GraphT& G ) {
typedef typename boost::graph_traits< GraphT >::vertex_descriptor Vertex;
typedef typename boost::graph_traits< GraphT >::edge_descriptor Edge;
typedef unordered_map<string,Vertex> svMap;
svMap namePosMap;
bool inserted;
Vertex u,v;
typename unordered_map<string,Vertex>::iterator pos;
bool headLine = false;
size_t remEdgeLine = 0;
string line;
typedef vector< string > splitVectorT;
ifstream gfile(fname);
if ( gfile.is_open() ) {
while( gfile.good() ) {
getline( gfile, line, '\n' );
if ( gfile.eof() ) { break; }
boost::algorithm::trim(line);
auto vline = line.substr( 0, line.find_first_of('#') );
if (vline.length() == 0) { continue; }
splitVectorT splitVec;
split( splitVec, vline, is_any_of(" \t"), token_compress_on );
if ( splitVec.size() > 0 and vline.size() > 0 ) {
auto fromVert = splitVec[0];
remEdgeLine = lexical_cast<size_t>(splitVec[1]);
boost::tie( pos, inserted ) = namePosMap.insert( std::make_pair(fromVert,Vertex()) );
if (inserted) {
u = add_vertex(G);
G[u].name = fromVert;
// This will happen later
// G[u].idx = nameMap[fromVert];
pos->second = u;
} else {
u = pos->second;
}
while ( remEdgeLine > 0 ) {
getline( gfile, line, '\n' );
boost::algorithm::trim(line);
vline = line.substr( 0, line.find_first_of('#') );
split( splitVec, vline, is_any_of(" \t"), token_compress_on );
auto toVert = splitVec[0];
double weight = lexical_cast<double>(splitVec[1]);
boost::tie(pos, inserted) = namePosMap.insert(std::make_pair(toVert, Vertex()));
if (inserted) {
v = add_vertex(G);
G[v].name = toVert;
// This will happen later
// G[v].idx = nameMap[toVert];
pos->second = v;
} else {
v = pos->second;
}
Edge e; bool i;
boost::tie(e,i) = add_edge(u,v,G);
G[e].weight = weight;
remEdgeLine--;
}
}
}
if ( namePosMap.size() != boost::num_vertices(G) ) {
std::cerr << "(namePosMap.size() = " << namePosMap.size() << ") != ("
<< "(order(G) = " << boost::num_vertices(G) << ") : Error building the graph, aborting\n";
std::abort();
}
}
gfile.close();
}
示例10:
locator::locator() :
val_()
{
hash_ = hash_value(val_);
hash1_ = hash_value1(val_);
}
示例11: on_reply
void natpmp::on_reply(asio::error_code const& e
, std::size_t bytes_transferred)
{
using namespace libtorrent::detail;
if (e) return;
try
{
if (m_remote != m_nat_endpoint)
{
m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)
, m_remote, bind(&natpmp::on_reply, this, _1, _2));
return;
}
m_send_timer.cancel();
assert(m_currently_mapping >= 0);
int i = m_currently_mapping;
mapping& m = m_mappings[i];
char* in = m_response_buffer;
int version = read_uint8(in);
int cmd = read_uint8(in);
int result = read_uint16(in);
int time = read_uint32(in);
int private_port = read_uint16(in);
int public_port = read_uint16(in);
int lifetime = read_uint32(in);
(void)time; // to remove warning
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== port map response: " << (cmd - 128 == 1 ? "udp" : "tcp")
<< " local: " << private_port << " external: " << public_port
<< " ttl: " << lifetime << std::endl;
#endif
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
if (version != 0)
{
m_log << "*** unexpected version: " << version << std::endl;
}
#endif
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
if (private_port != m.local_port)
{
m_log << "*** unexpected local port: " << private_port << std::endl;
}
#endif
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
if (cmd != 128 + m.protocol)
{
m_log << "*** unexpected protocol: " << (cmd - 128) << std::endl;
}
#endif
if (public_port == 0 || lifetime == 0)
{
// this means the mapping was
// successfully closed
m.local_port = 0;
}
else
{
m.expires = time_now() + seconds(int(lifetime * 0.7f));
m.external_port = public_port;
}
if (result != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << "*** ERROR: " << result << std::endl;
#endif
std::stringstream errmsg;
errmsg << "NAT router reports error (" << result << ") ";
switch (result)
{
case 1: errmsg << "Unsupported protocol version"; break;
case 2: errmsg << "Not authorized to create port map (enable NAT-PMP on your router)"; break;
case 3: errmsg << "Network failure"; break;
case 4: errmsg << "Out of resources"; break;
case 5: errmsg << "Unsupported opcode"; break;
}
throw std::runtime_error(errmsg.str());
}
// don't report when we remove mappings
if (m.local_port != 0)
{
int tcp_port = 0;
int udp_port = 0;
if (m.protocol == 1) udp_port = m.external_port;
else tcp_port = public_port;
m_callback(tcp_port, udp_port, "");
}
//.........这里部分代码省略.........
示例12: G_h
real Closure::G_h(real k) const {
return k*k/(4*M_PI*M_PI) * 1/12. * Integrate<ExpSub>(bind(B_h, cref(P_i), k, _1), QMIN, QMAX, EPS);
}
示例13: processRow
virtual void processRow() {
if (!garbage.isNull()) {
SINVARIANT(garbage.size() > 0);
cout << garbage.stringval();
return;
}
cout << format("%s %x.%04x %x.%04x %c %c%d %x %x %s")
% timeConv(time.val(), true)
% source_ip.val() % source_port.val()
% dest_ip.val() % dest_port.val()
% (is_udp.val() ? 'U' : 'T')
% (is_call.val() ? 'C' : 'R')
% static_cast<int>(nfs_version.val())
% rpc_transaction_id.val()
% static_cast<int>(rpc_function_id.val())
% rpc_function.stringval();
if (!is_call.val()) {
INVARIANT(!return_value.isNull(), "?");
if (return_value.val() == 0) {
if (rpc_function_id.val() == 0) {
// do nothing, nulls don't print out OK
} else {
cout << " OK";
}
} else {
cout << format(" %x") % return_value.val();
}
}
printany = false;
printMaybe(fh);
if (rpc_function.equal("rename")) {
// rename prints name between fh and fh2; most print it after
printMaybeString(name);
}
if (nfs_version.val() == 2 && rpc_function_id.val() == 11) {
printMaybeString(fn);
}
printMaybe(fh2);
if (nfs_version.val() == 2 && rpc_function_id.val() != 11) {
printMaybeString(fn);
}
printMaybe(pre_size);
printMaybeTime(pre_mtime);
printMaybeTime(pre_ctime);
if (!rpc_function.equal("rename") && !rpc_function.equal("readlink")) {
printMaybeString(name);
}
printMaybeString(name2);
printMaybeChar(how);
printMaybe(tsize);
printMaybe(bsize);
printMaybeString(fn2);
printMaybe(ftype);
printMaybe(mode);
printMaybe(nlink);
printMaybe(uid);
printMaybe(gid);
printMaybe(size);
printMaybe(blksize);
printMaybe(used);
printMaybe(rdev);
printMaybe(blocks);
printMaybe(rdev2);
printMaybe(fsid);
printMaybe(fileid);
printMaybeTime(atime);
printMaybeTime(mtime);
printMaybeTime(ctime);
printMaybe(bfree);
printMaybe(bavail);
if (rpc_function.equal("readlink")) {
printMaybeString(name);
}
printMaybe(ftype_dup);
printMaybe(mode_dup);
printMaybe(nlink_dup);
printMaybe(uid_dup);
printMaybe(gid_dup);
printMaybe(size_dup);
printMaybe(used_dup);
printMaybe(rdev_dup);
printMaybe(rdev2_dup);
printMaybe(fsid_dup);
printMaybe(fileid_dup);
printMaybeTime(atime_dup);
printMaybeTime(mtime_dup);
//.........这里部分代码省略.........
示例14: ContactCondition
void launcher::Launcher::loadSceneFromFile(string fileName, string initialStateGroup)
{
Engine& engine = Engine::getInstance();
// FIXME should we validate task file against xml schema?
auto& ffls = FileFolderLookupService::getInstance();
string fname = ffls.lookupFile(fileName);
LOG_DEBUG("Loading scene from file " << fname);
// parse file
Doc doc = Doc::fromFile(fname);
xml::Node rootNode = doc.getRootElement();
// read task parameters
NodeList taskNodes = rootNode.xpath("/task");
if( taskNodes.size() != 1 )
THROW_INVALID_INPUT("Config file should contain one <task/> element");
for(auto& taskNode: taskNodes)
{
int numberOfSnaps = lexical_cast<int>(taskNode["numberOfSnaps"]);
int stepsPerSnap = lexical_cast<int>(taskNode["stepsPerSnap"]);
engine.setNumberOfSnaps(numberOfSnaps);
engine.setStepsPerSnap(stepsPerSnap);
}
NodeList loadPluginsList = rootNode.xpath("/task/system/loadPlugin");
for (auto& plugin: loadPluginsList){
engine.loadPlugin(plugin["name"]);
}
// reading system properties
NodeList defaultContactCalculatorList = rootNode.xpath("/task/system/defaultContactCalculator");
if( defaultContactCalculatorList.size() > 1 )
THROW_INVALID_INPUT("Config file can contain only one <defaultContactCalculator/> element");
if( defaultContactCalculatorList.size() == 1 )
{
xml::Node defaultContactCalculator = defaultContactCalculatorList.front();
string type = defaultContactCalculator["type"];
if( engine.getContactCalculator(type) == NULL )
{
THROW_INVALID_INPUT("Unknown contact calculator requested: " + type);
}
engine.replaceDefaultContactCondition(
new ContactCondition(NULL, new StepPulseForm(-1, -1), engine.getContactCalculator(type) )
);
LOG_INFO("Default contact calculator set to: " + type);
if (type == "AdhesionContactDestroyCalculator")
{
real adhesionThreshold = lexical_cast<real>(defaultContactCalculator["adhesionThreshold"]);
engine.getContactCondition(0)->setConditionParam(adhesionThreshold);
}
if (type == "ClosedFractureContactCalculator")
{
NodeList areaNodes = defaultContactCalculator.getChildrenByName("area");
if (areaNodes.size() != 1)
THROW_INVALID_INPUT("Exactly one area element can be provided for ClosedFractureCalculator");
Area* area = readArea(areaNodes[0]);
(static_cast<gcm::ClosedFractureContactCalculator*>
(engine.getContactCalculator(type)))->setFracArea(area);
}
if (type == "OpenFractureContactCalculator")
{
NodeList areaNodes = defaultContactCalculator.getChildrenByName("area");
if (areaNodes.size() != 1)
THROW_INVALID_INPUT("Exactly one area element can be provided for ClosedFractureCalculator");
Area* area = readArea(areaNodes[0]);
(static_cast<gcm::OpenFractureContactCalculator*>
(engine.getContactCalculator(type)))->setFracArea(area);
}
}
NodeList defaultBorderCalculatorList = rootNode.xpath("/task/system/defaultBorderCalculator");
if( defaultBorderCalculatorList.size() > 1 )
THROW_INVALID_INPUT("Config file can contain only one <defaultBorderCalculator/> element");
if( defaultBorderCalculatorList.size() == 1 )
{
xml::Node defaultBorderCalculator = defaultBorderCalculatorList.front();
string type = defaultBorderCalculator["type"];
if( engine.getBorderCalculator(type) == NULL )
{
THROW_INVALID_INPUT("Unknown border calculator requested: " + type);
}
engine.replaceDefaultBorderCondition(
new BorderCondition(NULL, new StepPulseForm(-1, -1), engine.getBorderCalculator(type) )
);
LOG_INFO("Default border calculator set to: " + type);
}
NodeList defaultRheoCalculatorList = rootNode.xpath("/task/system/defaultRheologyCalculator");
if( defaultRheoCalculatorList.size() > 1 )
THROW_INVALID_INPUT("Config file can contain only one <defaultRheologyCalculator/> element");
if( defaultRheoCalculatorList.size() == 1 )
{
xml::Node defaultRheoCalculator = defaultRheoCalculatorList.front();
string type = defaultRheoCalculator["type"];
engine.setDefaultRheologyCalculatorType(type);
LOG_INFO("Default rheology calculator set to: " + type);
}
NodeList defaultFailureModelList = rootNode.xpath("/task/system/defaultFailureModel");
if( defaultFailureModelList.size() > 1 )
THROW_INVALID_INPUT("Config file can contain only one <defaultFailureModelList/> element");
//.........这里部分代码省略.........
示例15: update
void HeadFreeCameraEventReceiver::update(int ms)
{
auto cam = this->getCamera();
MoveEvent moveEvt = getMoveEvent();
LookEvent lookEvt = getLookEvent();
horizontalRotate_ += lookEvt.horizontalRotation * rotateSpeed * ms;
if(horizontalRotate_ > 180.0f) {
horizontalRotate_ -= 360.0f;
} else if(horizontalRotate_ < -180.0f) {
horizontalRotate_ += 360.0f;
}
verticalRotate_ += lookEvt.verticalRotation * rotateSpeed * ms;
const float maxVerticalRotation = 80.0f;
if(verticalRotate_ < -maxVerticalRotation) {
verticalRotate_ = -maxVerticalRotation;
} else if(verticalRotate_ > maxVerticalRotation) {
verticalRotate_ = maxVerticalRotation;
}
//그냥 생각없이 카메라를 돌리자. 오큘러스 대응은 렌더리쪽에서 알아서 처리될거다
cam->setRotation(core::vector3df(verticalRotate_, horizontalRotate_, 0));
//카메라 처다보는 방향으로 로직을 구현하면 오큘러스에서 설정한 값하고 꼬인다
//v/h 값으로 따로 계산해야될듯
core::vector3df pos = cam->getPosition();
core::vector3df up(0, 1, 0);
float targetX = -cos(core::degToRad(verticalRotate_)) * sin(core::degToRad(horizontalRotate_));
float targetY = sin(core::degToRad(verticalRotate_));
float targetZ = -cos(core::degToRad(verticalRotate_)) * cos(core::degToRad(horizontalRotate_));
core::vector3df target(targetX, targetY, targetZ);
irr::core::vector3df side = up.crossProduct(target);
up = target.crossProduct(side);
cam->setUpVector(up);
const float moveFactor = moveSpeed * ms;
auto moveDelta = moveFactor * moveEvt.forwardBackward * target;
auto sideDelta = moveFactor * moveEvt.leftRight * side;
auto nextPos = pos + moveDelta + sideDelta;
cam->setPosition(nextPos);
bool displayInfo = false;
if(displayInfo) {
irr::video::SColor white(255, 255, 255, 255);
auto rotateMsg = (wformat(L"rotate : h=%.2f, v=%.2f") % horizontalRotate_ % verticalRotate_).str();
g_debugDrawMgr->addString(core::vector2di(0, 100), rotateMsg, white);
auto evtMsg = (wformat(L"evt : fb=%.2f, lr=%.2f") % moveEvt.forwardBackward % moveEvt.leftRight).str();
g_debugDrawMgr->addString(core::vector2di(0, 100 + 14*1), evtMsg, white);
auto targetMsg = (wformat(L"target : %.2f, %.2f, %.2f") % targetX % targetY % targetZ).str();
g_debugDrawMgr->addString(core::vector2di(0, 100 + 14*2), targetMsg, white);
auto sideMsg = (wformat(L"side : %.2f, %.2f, %.2f") % side.X % side.Y % side.Z).str();
g_debugDrawMgr->addString(core::vector2di(0, 100 + 14*3), sideMsg, white);
auto camPos = cam->getPosition();
auto camPosMsg = (wformat(L"CamPos : %.2f, %.2f, %.2f") % camPos.X % camPos.Y % camPos.Z).str();
g_debugDrawMgr->addString(core::vector2di(0, 100 + 14*4), camPosMsg, white);
auto upVecMsg = (wformat(L"UpVec : %.2f, %.2f, %.2f") % up.X % up.Y % up.Z).str();
g_debugDrawMgr->addString(core::vector2di(0, 100 + 14*5), upVecMsg, white);
}
}