本文整理汇总了C++中parser函数 的典型用法代码示例。如果您正苦于以下问题:C++ parser函数的具体用法?C++ parser怎么用?C++ parser使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parser函数 的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: TEST_F
TEST_F(TConfigParserTest, Parse)
{
TConfigTemplateParser device_parser(GetDataFilePath("../wb-mqtt-serial-templates/"), false);
TConfigParser parser(GetDataFilePath("../config.json"), false,
TSerialDeviceFactory::GetRegisterTypes, device_parser.Parse());
PHandlerConfig config = parser.Parse();
Emit() << "Debug: " << config->Debug;
Emit() << "Ports:";
for (auto port_config: config->PortConfigs) {
TTestLogIndent indent(*this);
ASSERT_EQ(config->Debug, port_config->Debug);
Emit() << "------";
Emit() << "ConnSettings: " << port_config->ConnSettings;
Emit() << "PollInterval: " << port_config->PollInterval.count();
if (port_config->DeviceConfigs.empty()) {
Emit() << "No device configs.";
continue;
}
Emit() << "DeviceConfigs:";
for (auto device_config: port_config->DeviceConfigs) {
TTestLogIndent indent(*this);
Emit() << "------";
Emit() << "Id: " << device_config->Id;
Emit() << "Name: " << device_config->Name;
Emit() << "SlaveId: " << device_config->SlaveId;
if (!device_config->DeviceChannels.empty()) {
Emit() << "DeviceChannels:";
for (auto modbus_channel: device_config->DeviceChannels) {
TTestLogIndent indent(*this);
Emit() << "------";
Emit() << "Name: " << modbus_channel->Name;
Emit() << "Type: " << modbus_channel->Type;
Emit() << "DeviceId: " << modbus_channel->DeviceId;
Emit() << "Order: " << modbus_channel->Order;
Emit() << "OnValue: " << modbus_channel->OnValue;
Emit() << "Max: " << modbus_channel->Max;
Emit() << "ReadOnly: " << modbus_channel->ReadOnly;
std::stringstream s;
bool first = true;
for (auto reg: modbus_channel->Registers) {
if (first)
first = false;
else
s << ", ";
s << reg;
if (reg->PollInterval.count())
s << " (poll_interval=" << reg->PollInterval.count() << ")";
}
Emit() << "Registers: " << s.str();
}
if (device_config->SetupItems.empty())
continue;
Emit() << "SetupItems:";
for (auto setup_item: device_config->SetupItems) {
TTestLogIndent indent(*this);
Emit() << "------";
Emit() << "Name: " << setup_item->Name;
Emit() << "Address: " << setup_item->Reg->Address;
Emit() << "Value: " << setup_item->Value;
}
}
}
}
}
开发者ID:Perfy, 项目名称:wb-homa-drivers, 代码行数:67, 代码来源:modbus_test.cpp
示例2: parser
void SenMLPack::fromCbor(Stream* source, SenMLStreamMethod format)
{
SenMLCborParser parser(this, format);
parser.parse(source);
}
开发者ID:osdomotics, 项目名称:osd-contiki, 代码行数:5, 代码来源:senml_pack.cpp
示例3: frame
void
TextDocumentTest::ReadyToRun()
{
BRect frame(50.0, 50.0, 749.0, 549.0);
BWindow* window = new BWindow(frame, "Text document test",
B_TITLED_WINDOW, B_QUIT_ON_WINDOW_CLOSE | B_AUTO_UPDATE_SIZE_LIMITS);
TextDocumentView* documentView = new TextDocumentView("text document view");
BLayoutBuilder::Group<>(window, B_VERTICAL)
.Add(documentView)
;
CharacterStyle regularStyle;
float fontSize = regularStyle.Font().Size();
ParagraphStyle paragraphStyle;
paragraphStyle.SetJustify(true);
paragraphStyle.SetSpacingTop(ceilf(fontSize * 0.6f));
paragraphStyle.SetLineSpacing(ceilf(fontSize * 0.2f));
// CharacterStyle boldStyle(regularStyle);
// boldStyle.SetBold(true);
//
// CharacterStyle italicStyle(regularStyle);
// italicStyle.SetItalic(true);
//
// CharacterStyle italicAndBoldStyle(boldStyle);
// italicAndBoldStyle.SetItalic(true);
//
// CharacterStyle bigStyle(regularStyle);
// bigStyle.SetFontSize(24);
// bigStyle.SetForegroundColor(255, 50, 50);
//
// TextDocumentRef document(new TextDocument(), true);
//
// Paragraph paragraph(paragraphStyle);
// paragraph.Append(TextSpan("This is a", regularStyle));
// paragraph.Append(TextSpan(" test ", bigStyle));
// paragraph.Append(TextSpan("to see if ", regularStyle));
// paragraph.Append(TextSpan("different", boldStyle));
// paragraph.Append(TextSpan(" character styles already work.", regularStyle));
// document->Append(paragraph);
//
// paragraphStyle.SetSpacingTop(8.0f);
// paragraphStyle.SetAlignment(ALIGN_CENTER);
// paragraphStyle.SetJustify(false);
//
// paragraph = Paragraph(paragraphStyle);
// paragraph.Append(TextSpan("Different alignment styles ", regularStyle));
// paragraph.Append(TextSpan("are", boldStyle));
// paragraph.Append(TextSpan(" supported as of now!", regularStyle));
// document->Append(paragraph);
//
// // Test a bullet list
// paragraphStyle.SetSpacingTop(8.0f);
// paragraphStyle.SetAlignment(ALIGN_LEFT);
// paragraphStyle.SetJustify(true);
// paragraphStyle.SetBullet(Bullet("•", 12.0f));
// paragraphStyle.SetLineInset(10.0f);
//
// paragraph = Paragraph(paragraphStyle);
// paragraph.Append(TextSpan("Even bullet lists are supported.", regularStyle));
// document->Append(paragraph);
//
// paragraph = Paragraph(paragraphStyle);
// paragraph.Append(TextSpan("The wrapping in ", regularStyle));
// paragraph.Append(TextSpan("this", italicStyle));
//
// paragraph.Append(TextSpan(" bullet item should look visually "
// "pleasing. And ", regularStyle));
// paragraph.Append(TextSpan("why", italicAndBoldStyle));
// paragraph.Append(TextSpan(" should it not?", regularStyle));
// document->Append(paragraph);
MarkupParser parser(regularStyle, paragraphStyle);
TextDocumentRef document = parser.CreateDocumentFromMarkup(
"== Text document test ==\n"
"This is a test to see if '''different''' "
"character styles already work.\n"
"Different alignment styles '''are''' supported as of now!\n"
" * Even bullet lists are supported.\n"
" * The wrapping in ''this'' bullet item should look visually "
"pleasing. And ''why'' should it not?\n"
);
documentView->SetTextDocument(document);
window->Show();
}
开发者ID:DonCN, 项目名称:haiku, 代码行数:93, 代码来源:TextDocumentTest.cpp
示例4: input
void MatroskaWrapper::GetSubtitles(agi::fs::path const& filename, AssFile *target) {
MkvStdIO input(filename);
char err[2048];
agi::scoped_holder<MatroskaFile*, decltype(&mkv_Close)> file(mkv_Open(&input, err, sizeof(err)), mkv_Close);
if (!file) throw MatroskaException(err);
// Get info
unsigned tracks = mkv_GetNumTracks(file);
std::vector<unsigned> tracksFound;
std::vector<std::string> tracksNames;
// Find tracks
for (auto track : boost::irange(0u, tracks)) {
auto trackInfo = mkv_GetTrackInfo(file, track);
if (trackInfo->Type != 0x11) continue;
// Known subtitle format
std::string CodecID(trackInfo->CodecID);
if (CodecID == "S_TEXT/SSA" || CodecID == "S_TEXT/ASS" || CodecID == "S_TEXT/UTF8") {
tracksFound.push_back(track);
tracksNames.emplace_back(str(boost::format("%d (%s %s)") % track % CodecID % trackInfo->Language));
if (trackInfo->Name) {
tracksNames.back() += ": ";
tracksNames.back() += trackInfo->Name;
}
}
}
// No tracks found
if (tracksFound.empty())
throw MatroskaException("File has no recognised subtitle tracks.");
unsigned trackToRead;
// Only one track found
if (tracksFound.size() == 1)
trackToRead = tracksFound[0];
// Pick a track
else {
int choice = wxGetSingleChoiceIndex(_("Choose which track to read:"), _("Multiple subtitle tracks found"), to_wx(tracksNames));
if (choice == -1)
throw agi::UserCancelException("canceled");
trackToRead = tracksFound[choice];
}
// Picked track
mkv_SetTrackMask(file, ~(1 << trackToRead));
auto trackInfo = mkv_GetTrackInfo(file, trackToRead);
std::string CodecID(trackInfo->CodecID);
bool srt = CodecID == "S_TEXT/UTF8";
bool ssa = CodecID == "S_TEXT/SSA";
AssParser parser(target, !ssa);
// Read private data if it's ASS/SSA
if (!srt) {
// Read raw data
std::string priv((const char *)trackInfo->CodecPrivate, trackInfo->CodecPrivateSize);
// Load into file
boost::char_separator<char> sep("\r\n");
for (auto const& cur : boost::tokenizer<boost::char_separator<char>>(priv, sep))
parser.AddLine(cur);
}
// Load default if it's SRT
else {
target->LoadDefault(false);
parser.AddLine("[Events]");
}
// Read timecode scale
auto segInfo = mkv_GetFileInfo(file);
longlong timecodeScale = mkv_TruncFloat(trackInfo->TimecodeScale) * segInfo->TimecodeScale;
// Progress bar
auto totalTime = double(segInfo->Duration) / timecodeScale;
DialogProgress progress(nullptr, _("Parsing Matroska"), _("Reading subtitles from Matroska file."));
progress.Run([&](agi::ProgressSink *ps) { read_subtitles(ps, file, &input, srt, totalTime, &parser); });
}
开发者ID:metkaz, 项目名称:Aegisub, 代码行数:79, 代码来源:mkv_wrap.cpp
示例5: loadDataSheet
void loadDataSheet(XMLNode table_node, std::map<string, int> &map, int (*add_func)(TupleParser&)) {
vector<XMLNode> rows;
vector<StringRef> col_names;
XMLNode row_node = table_node.child("table:table-row");
while(row_node) {
rows.emplace_back(row_node);
row_node = row_node.sibling("table:table-row");
}
{
ASSERT(!rows.empty());
XMLNode first_row = rows.front();
XMLNode cell_node = first_row.child("table:table-cell");
while(cell_node) {
col_names.push_back(getText(cell_node));
cell_node = cell_node.sibling("table:table-cell");
}
}
std::map<StringRef, int> column_map;
for(int n = 0; n < (int)col_names.size(); n++)
if(!col_names[n].isEmpty()) {
if(column_map.find(col_names[n]) != column_map.end())
THROW("Duplicate argument: %s", col_names[n]);
column_map.emplace(col_names[n], n);
}
vector<const char*> columns;
columns.reserve(col_names.size());
bool errors = false;
int id_column = 0; {
auto it = column_map.find("id");
if(it == column_map.end())
THROW("Id column must be defined");
id_column = it->second;
}
for(int r = 1; r < (int)rows.size(); r++) {
XMLNode row = rows[r];
int cell_idx = 0;
XMLNode cell = row.child("table:table-cell");
columns.clear();
while(cell && cell_idx < (int)col_names.size()) {
const char *value = getText(cell);
const char *repeat_attrib = cell.hasAttrib("table:number-columns-repeated");
int num_repeat = repeat_attrib? toInt(repeat_attrib) : 1;
for(int i = 0; i < num_repeat; i++)
columns.push_back(value);
cell_idx += num_repeat;
cell = cell.sibling("table:table-cell");
}
int num_columns = (int)min(col_names.size(), columns.size());
bool is_empty = true;
for(int n = 0; n < num_columns; n++)
if(columns[n][0]) {
is_empty = false;
break;
}
if(is_empty)
continue;
TupleParser parser(columns.data(), num_columns, column_map);
try {
string id = columns[id_column];
if(id.empty())
THROW("ID undefined");
if(map.find(id) != map.end())
THROW("Duplicated ID: %s", id.c_str());
int index = add_func(parser);
map.emplace(std::move(id), index);
}
catch(const Exception &ex) {
errors = true;
printf("Error while parsing row: %d (id: %s):\n%s\n",
r, columns[id_column], ex.what());
}
}
if(errors)
THROW("Errors while parsing sheet: %s\n", table_node.attrib("table:name"));
}
开发者ID:dreamsxin, 项目名称:FreeFT, 代码行数:92, 代码来源:data_sheet.cpp
示例6: DoSetup
QTSS_Error DoSetup(QTSS_StandardRTSP_Params* inParams)
{
ReflectorSession* theSession = NULL;
UInt32 len = sizeof(theSession);
QTSS_GetValue(inParams->inRTSPSession, sRTSPBroadcastSessionAttr, 0, &theSession, &len);
if(theSession == NULL)
return QTSS_RequestFailed;
Bool16 foundSession = false;
UInt32 theLen = 0;
RTPSessionOutput** theOutput = NULL;
QTSS_Error theErr = QTSS_GetValuePtr(inParams->inClientSession, sOutputAttr, 0, (void**)&theOutput, &theLen);
if (theLen != sizeof(RTPSessionOutput*))
{
if (theErr != QTSS_NoErr)
{
RTPSessionOutput* theNewOutput = NEW RTPSessionOutput(inParams->inClientSession, theSession, sServerPrefs, sStreamCookieAttr );
theSession->AddOutput(theNewOutput,true);
(void)QTSS_SetValue(inParams->inClientSession, sOutputAttr, 0, &theNewOutput, sizeof(theNewOutput));
}
}
//unless there is a digit at the end of this path (representing trackID), don't
//even bother with the request
char* theDigitStr = NULL;
(void)QTSS_GetValueAsString(inParams->inRTSPRequest, qtssRTSPReqFileDigit, 0, &theDigitStr);
QTSSCharArrayDeleter theDigitStrDeleter(theDigitStr);
if (theDigitStr == NULL)
{
return QTSSModuleUtils::SendErrorResponse(inParams->inRTSPRequest, qtssClientBadRequest,sExpectedDigitFilenameErr);
}
UInt32 theTrackID = ::strtol(theDigitStr, NULL, 10);
// Get info about this trackID
SourceInfo::StreamInfo* theStreamInfo = theSession->GetSourceInfo()->GetStreamInfoByTrackID(theTrackID);
// If theStreamInfo is NULL, we don't have a legit track, so return an error
if (theStreamInfo == NULL)
return QTSSModuleUtils::SendErrorResponse(inParams->inRTSPRequest, qtssClientBadRequest,
sReflectorBadTrackIDErr);
StrPtrLen* thePayloadName = &theStreamInfo->fPayloadName;
QTSS_RTPPayloadType thePayloadType = theStreamInfo->fPayloadType;
StringParser parser(thePayloadName);
parser.GetThru(NULL, '/');
theStreamInfo->fTimeScale = parser.ConsumeInteger(NULL);
if (theStreamInfo->fTimeScale == 0)
theStreamInfo->fTimeScale = 90000;
QTSS_RTPStreamObject newStream = NULL;
{
// Ok, this is completely crazy but I can't think of a better way to do this that's
// safe so we'll do it this way for now. Because the ReflectorStreams use this session's
// stream queue, we need to make sure that each ReflectorStream is not reflecting to this
// session while we call QTSS_AddRTPStream. One brutal way to do this is to grab each
// ReflectorStream's mutex, which will stop every reflector stream from running.
for (UInt32 x = 0; x < theSession->GetNumStreams(); x++)
theSession->GetStreamByIndex(x)->GetMutex()->Lock();
theErr = QTSS_AddRTPStream(inParams->inClientSession, inParams->inRTSPRequest, &newStream, 0);
for (UInt32 y = 0; y < theSession->GetNumStreams(); y++)
theSession->GetStreamByIndex(y)->GetMutex()->Unlock();
if (theErr != QTSS_NoErr)
return theErr;
}
// Set up dictionary items for this stream
theErr = QTSS_SetValue(newStream, qtssRTPStrPayloadName, 0, thePayloadName->Ptr, thePayloadName->Len);
Assert(theErr == QTSS_NoErr);
theErr = QTSS_SetValue(newStream, qtssRTPStrPayloadType, 0, &thePayloadType, sizeof(thePayloadType));
Assert(theErr == QTSS_NoErr);
theErr = QTSS_SetValue(newStream, qtssRTPStrTrackID, 0, &theTrackID, sizeof(theTrackID));
Assert(theErr == QTSS_NoErr);
theErr = QTSS_SetValue(newStream, qtssRTPStrTimescale, 0, &theStreamInfo->fTimeScale, sizeof(theStreamInfo->fTimeScale));
Assert(theErr == QTSS_NoErr);
// We only want to allow over buffering to dynamic rate clients
SInt32 canDynamicRate = -1;
theLen = sizeof(canDynamicRate);
(void) QTSS_GetValue(inParams->inRTSPRequest, qtssRTSPReqDynamicRateState, 0, (void*) &canDynamicRate, &theLen);
if (canDynamicRate < 1) // -1 no rate field, 0 off
(void)QTSS_SetValue(inParams->inClientSession, qtssCliSesOverBufferEnabled, 0, &sFalse, sizeof(sFalse));
// Place the stream cookie in this stream for future reference
void* theStreamCookie = theSession->GetStreamCookie(theTrackID);
Assert(theStreamCookie != NULL);
theErr = QTSS_SetValue(newStream, sStreamCookieAttr, 0, &theStreamCookie, sizeof(theStreamCookie));
Assert(theErr == QTSS_NoErr);
// Set the number of quality levels.
static UInt32 sNumQualityLevels = ReflectorSession::kNumQualityLevels;
theErr = QTSS_SetValue(newStream, qtssRTPStrNumQualityLevels, 0, &sNumQualityLevels, sizeof(sNumQualityLevels));
Assert(theErr == QTSS_NoErr);
//.........这里部分代码省略.........
开发者ID:appotry, 项目名称:EasyDarwin-1, 代码行数:101, 代码来源:QTSSOnDemandRelayModule.cpp
示例7: if
//**********************************************************************************************************************
AlignCommand::AlignCommand(string option) {
try {
abort = false; calledHelp = false;
//allow user to run help
if(option == "help") { help(); abort = true; calledHelp = true;}
else if(option == "citation") { citation(); abort = true; calledHelp = true;}
else {
vector<string> myArray = setParameters();
OptionParser parser(option);
map<string, string> parameters = parser.getParameters();
ValidParameters validParameter("align.seqs");
map<string, string>::iterator it;
//check to make sure all parameters are valid for command
for (it = parameters.begin(); it != parameters.end(); it++) {
if (!validParameter.isValidParameter(it->first, myArray, it->second)) { abort = true; }
}
//initialize outputTypes
vector<string> tempOutNames;
outputTypes["fasta"] = tempOutNames;
outputTypes["alignreport"] = tempOutNames;
outputTypes["accnos"] = tempOutNames;
//if the user changes the output directory command factory will send this info to us in the output parameter
outputDir = validParameter.valid(parameters, "outputdir"); if (outputDir == "not found"){ outputDir = ""; }
//if the user changes the input directory command factory will send this info to us in the output parameter
string inputDir = validParameter.valid(parameters, "inputdir");
if (inputDir == "not found"){ inputDir = ""; }
else {
string path;
//user has given a template file
it = parameters.find("reference");
if(it != parameters.end()){
path = util.hasPath(it->second);
//if the user has not given a path then, add inputdir. else leave path alone.
if (path == "") { parameters["reference"] = inputDir + it->second; }
}
it = parameters.find("fasta");
if(it != parameters.end()){
path = util.hasPath(it->second);
//if the user has not given a path then, add inputdir. else leave path alone.
if (path == "") { parameters["fasta"] = inputDir + it->second; }
}
}
templateFileName = validParameter.validFile(parameters, "reference");
if (templateFileName == "not found") { m->mothurOut("[ERROR]: The reference parameter is a required for the align.seqs command, aborting.\n"); abort = true;
}else if (templateFileName == "not open") { abort = true; }
fastafile = validParameter.validFile(parameters, "fasta");
if (fastafile == "not found") {
fastafile = current->getFastaFile();
if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter.\n"); }
else { m->mothurOut("[ERROR]: You have no current fasta file and the fasta parameter is required.\n"); abort = true; }
}
else if (fastafile == "not open") { abort = true; }
else { current->setFastaFile(fastafile); }
//check for optional parameter and set defaults
// ...at some point should added some additional type checking...
string temp;
temp = validParameter.valid(parameters, "ksize"); if (temp == "not found"){ temp = "8"; }
util.mothurConvert(temp, kmerSize);
temp = validParameter.valid(parameters, "match"); if (temp == "not found"){ temp = "1.0"; }
util.mothurConvert(temp, match);
temp = validParameter.valid(parameters, "mismatch"); if (temp == "not found"){ temp = "-1.0"; }
util.mothurConvert(temp, misMatch);
temp = validParameter.valid(parameters, "gapopen"); if (temp == "not found"){ temp = "-5.0"; }
util.mothurConvert(temp, gapOpen);
temp = validParameter.valid(parameters, "gapextend"); if (temp == "not found"){ temp = "-2.0"; }
util.mothurConvert(temp, gapExtend);
temp = validParameter.valid(parameters, "processors"); if (temp == "not found"){ temp = current->getProcessors(); }
processors = current->setProcessors(temp);
temp = validParameter.valid(parameters, "flip"); if (temp == "not found"){ temp = "t"; }
flip = util.isTrue(temp);
temp = validParameter.valid(parameters, "threshold"); if (temp == "not found"){ temp = "0.50"; }
util.mothurConvert(temp, threshold);
search = validParameter.valid(parameters, "search"); if (search == "not found"){ search = "kmer"; }
if ((search != "suffix") && (search != "kmer") && (search != "blast")) { m->mothurOut("invalid search option: choices are kmer, suffix or blast."); m->mothurOutEndLine(); abort=true; }
align = validParameter.valid(parameters, "align"); if (align == "not found"){ align = "needleman"; }
//.........这里部分代码省略.........
开发者ID:mothur, 项目名称:mothur, 代码行数:101, 代码来源:aligncommand.cpp
示例8: MOZ_ASSERT
/* static */ already_AddRefed<Image>
ImageFactory::CreateRasterImage(nsIRequest* aRequest,
ProgressTracker* aProgressTracker,
const nsCString& aMimeType,
ImageURL* aURI,
uint32_t aImageFlags,
uint32_t aInnerWindowId)
{
MOZ_ASSERT(aProgressTracker);
nsresult rv;
RefPtr<RasterImage> newImage = new RasterImage(aURI);
aProgressTracker->SetImage(newImage);
newImage->SetProgressTracker(aProgressTracker);
nsAutoCString ref;
aURI->GetRef(ref);
net::nsMediaFragmentURIParser parser(ref);
if (parser.HasSampleSize()) {
/* Get our principal */
nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
nsCOMPtr<nsIPrincipal> principal;
if (chan) {
nsContentUtils::GetSecurityManager()
->GetChannelResultPrincipal(chan, getter_AddRefs(principal));
}
if ((principal &&
principal->GetAppStatus() == nsIPrincipal::APP_STATUS_CERTIFIED) ||
gfxPrefs::ImageMozSampleSizeEnabled()) {
newImage->SetRequestedSampleSize(parser.GetSampleSize());
}
}
rv = newImage->Init(aMimeType.get(), aImageFlags);
if (NS_FAILED(rv)) {
return BadImage("RasterImage::Init failed", newImage);
}
newImage->SetInnerWindowID(aInnerWindowId);
uint32_t len = GetContentSize(aRequest);
// Pass anything usable on so that the RasterImage can preallocate
// its source buffer.
if (len > 0) {
// Bound by something reasonable
uint32_t sizeHint = std::min<uint32_t>(len, 20000000);
rv = newImage->SetSourceSizeHint(sizeHint);
if (NS_FAILED(rv)) {
// Flush memory, try to get some back, and try again.
rv = nsMemory::HeapMinimize(true);
nsresult rv2 = newImage->SetSourceSizeHint(sizeHint);
// If we've still failed at this point, things are going downhill.
if (NS_FAILED(rv) || NS_FAILED(rv2)) {
NS_WARNING("About to hit OOM in imagelib!");
}
}
}
return newImage.forget();
}
开发者ID:MekliCZ, 项目名称:positron, 代码行数:63, 代码来源:ImageFactory.cpp
示例9: TOKEN_TABLE_START
TOKEN_DEF_END
//////////////////////////////////////////////////////////////////////////
HRESULT CAdInventoryBox::LoadBuffer(BYTE* Buffer, bool Complete)
{
TOKEN_TABLE_START(commands)
TOKEN_TABLE (INVENTORY_BOX)
TOKEN_TABLE (TEMPLATE)
TOKEN_TABLE (WINDOW)
TOKEN_TABLE (EXCLUSIVE)
TOKEN_TABLE (ALWAYS_VISIBLE)
TOKEN_TABLE (AREA)
TOKEN_TABLE (SPACING)
TOKEN_TABLE (ITEM_WIDTH)
TOKEN_TABLE (ITEM_HEIGHT)
TOKEN_TABLE (SCROLL_BY)
TOKEN_TABLE (NAME)
TOKEN_TABLE (CAPTION)
TOKEN_TABLE (HIDE_SELECTED)
TOKEN_TABLE (EDITOR_PROPERTY)
TOKEN_TABLE_END
BYTE* params;
int cmd=2;
CBParser parser(Game);
bool always_visible=false;
m_Exclusive = false;
if(Complete)
{
if(parser.GetCommand ((char**)&Buffer, commands, (char**)¶ms)!=TOKEN_INVENTORY_BOX)
{
Game->LOG(0, "'INVENTORY_BOX' keyword expected.");
return E_FAIL;
}
Buffer = params;
}
while (cmd>0 && (cmd = parser.GetCommand ((char**)&Buffer, commands, (char**)¶ms)) > 0)
{
switch (cmd)
{
case TOKEN_TEMPLATE:
if(FAILED(LoadFile((char*)params))) cmd = PARSERR_GENERIC;
break;
case TOKEN_NAME:
SetName((char*)params);
break;
case TOKEN_CAPTION:
SetCaption((char*)params);
break;
case TOKEN_WINDOW:
SAFE_DELETE(m_Window);
m_Window = new CUIWindow(Game);
if(!m_Window || FAILED(m_Window->LoadBuffer(params, false)))
{
SAFE_DELETE(m_Window);
cmd = PARSERR_GENERIC;
}
else Game->RegisterObject(m_Window);
break;
case TOKEN_AREA:
parser.ScanStr((char*)params, "%d,%d,%d,%d", &m_ItemsArea.left, &m_ItemsArea.top, &m_ItemsArea.right, &m_ItemsArea.bottom);
break;
case TOKEN_EXCLUSIVE:
parser.ScanStr((char*)params, "%b", &m_Exclusive);
break;
case TOKEN_HIDE_SELECTED:
parser.ScanStr((char*)params, "%b", &m_HideSelected);
break;
case TOKEN_ALWAYS_VISIBLE:
parser.ScanStr((char*)params, "%b", &always_visible);
break;
case TOKEN_SPACING:
parser.ScanStr((char*)params, "%d", &m_Spacing);
break;
case TOKEN_ITEM_WIDTH:
parser.ScanStr((char*)params, "%d", &m_ItemWidth);
break;
case TOKEN_ITEM_HEIGHT:
parser.ScanStr((char*)params, "%d", &m_ItemHeight);
break;
case TOKEN_SCROLL_BY:
parser.ScanStr((char*)params, "%d", &m_ScrollBy);
break;
case TOKEN_EDITOR_PROPERTY:
ParseEditorProperty(params, false);
break;
}
//.........这里部分代码省略.........
开发者ID:segafan, 项目名称:wmelite_hcdaniel-repo, 代码行数:101, 代码来源:AdInventoryBox.cpp
示例10: if
//**********************************************************************************************************************
GetRelAbundCommand::GetRelAbundCommand(string option) {
try {
abort = false; calledHelp = false;
allLines = 1;
//allow user to run help
if(option == "help") { help(); abort = true; calledHelp = true; }
else if(option == "citation") { citation(); abort = true; calledHelp = true;}
else {
vector<string> myArray = setParameters();
OptionParser parser(option);
map<string,string> parameters = parser.getParameters();
map<string,string>::iterator it;
ValidParameters validParameter;
//check to make sure all parameters are valid for command
for (it = parameters.begin(); it != parameters.end(); it++) {
if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
}
//initialize outputTypes
vector<string> tempOutNames;
outputTypes["relabund"] = tempOutNames;
//if the user changes the input directory command factory will send this info to us in the output parameter
string inputDir = validParameter.validFile(parameters, "inputdir", false);
if (inputDir == "not found"){ inputDir = ""; }
else {
string path;
it = parameters.find("shared");
//user has given a template file
if(it != parameters.end()){
path = m->hasPath(it->second);
//if the user has not given a path then, add inputdir. else leave path alone.
if (path == "") { parameters["shared"] = inputDir + it->second; }
}
}
//get shared file
sharedfile = validParameter.validFile(parameters, "shared", true);
if (sharedfile == "not open") { sharedfile = ""; abort = true; }
else if (sharedfile == "not found") {
//if there is a current shared file, use it
sharedfile = m->getSharedFile();
if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
else { m->mothurOut("You have no current sharedfile and the shared parameter is required."); m->mothurOutEndLine(); abort = true; }
}else { m->setSharedFile(sharedfile); }
//if the user changes the output directory command factory will send this info to us in the output parameter
outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = m->hasPath(sharedfile); }
//check for optional parameter and set defaults
// ...at some point should added some additional type checking...
label = validParameter.validFile(parameters, "label", false);
if (label == "not found") { label = ""; }
else {
if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
else { allLines = 1; }
}
groups = validParameter.validFile(parameters, "groups", false);
if (groups == "not found") { groups = ""; pickedGroups = false; }
else {
pickedGroups = true;
m->splitAtDash(groups, Groups);
m->setGroups(Groups);
}
scale = validParameter.validFile(parameters, "scale", false); if (scale == "not found") { scale = "totalgroup"; }
if ((scale != "totalgroup") && (scale != "totalotu") && (scale != "averagegroup") && (scale != "averageotu")) {
m->mothurOut(scale + " is not a valid scaling option for the get.relabund command. Choices are totalgroup, totalotu, averagegroup, averageotu."); m->mothurOutEndLine(); abort = true;
}
}
}
catch(exception& e) {
m->errorOut(e, "GetRelAbundCommand", "GetRelAbundCommand");
exit(1);
}
}
开发者ID:azerxu, 项目名称:mothur, 代码行数:86, 代码来源:getrelabundcommand.cpp
示例11: qDebug
bool UserPlugin::onVCard(const VCardWrapper& vcardWrapper)
{
const gloox::JID jid=vcardWrapper.jid();
gloox::VCard vcard=gloox::VCard(vcardWrapper.vcard());
qDebug() << "Got vcard: "+vcardWrapper.id();
QString jidStr=QString::fromStdString(jid.full());
QString reqId=QString("vcard_%1").arg(vcardWrapper.id());
AsyncRequest* req=bot()->asyncRequests()->byStanzaId(reqId);
if (req==0l)
{
return false;
}
if (vcardWrapper.isEmpty())
{
reply(req->stanza(), "No VCard found");
bot()->asyncRequests()->removeAll(req);
return true;
}
if (req->name()=="VCARD")
{
QString replyStr=vcardWrapper.vcardStr();
if (replyStr.isEmpty())
{
reply(req->stanza(), "Empty VCard");
}
else
{
reply(req->stanza(), QString("VCard: %1").arg(replyStr));
}
}
else if (req->name()=="PHOTO")
{
std::string photoContentStd=vcard.photo().binval;
QByteArray photoContent=QByteArray(photoContentStd.data(),
photoContentStd.size());
//QFile file("/tmp/out.png");
//file.open(QIODevice::WriteOnly);
//file.write(photoContentStd.data(), photoContentStd.size());
//file.close();
QImage image;
if (!image.loadFromData(photoContent))
{
reply(req->stanza(), "Can't load image");
bot()->asyncRequests()->removeAll(req);
return true;
}
MessageParser parser(req->stanza(), getMyNick(req->stanza()));
parser.nextToken();
QString cmd=parser.nextToken().toUpper();
QString jid=parser.nextToken();
QString widthStr=parser.nextToken();
QString white=parser.nextToken();
QString black=parser.nextToken();
Image2Ascii img2ascii(image);
if (!widthStr.isEmpty())
img2ascii.setWidth(widthStr.toInt());
if (!white.isEmpty() && white.length()<=5)
img2ascii.setWhite(white);
if (!black.isEmpty() && black.length()<=5)
img2ascii.setBlack(black);
QString ascii=img2ascii.ascii();
if (ascii.isEmpty())
reply(req->stanza(), "Can't convert image to ASCII");
else
reply(req->stanza(), QString("Photo:\n%1").arg(ascii));
}
bot()->asyncRequests()->removeAll(req);
return true;
}
开发者ID:shizeeg, 项目名称:gluxi-hacks, 代码行数:75, 代码来源:userplugin.cpp
示例12: Q_UNUSED
bool UserPlugin::parseMessage(gloox::Stanza* s, const QStringList& flags)
{
Q_UNUSED(flags)
MessageParser parser(s, getMyNick(s));
parser.nextToken();
QString cmd=parser.nextToken().toUpper();
QString arg=parser.nextToken();
if(cmd=="TIME")
{
std::string id=bot()->client()->getID();
QString jid=resolveTargetJid(s, arg);
gloox::Stanza *st=gloox::Stanza::createIqStanza(
gloox::JID(jid.toStdString()), id, gloox::StanzaIqGet,
"jabber:iq:time");
qDebug() << QString::fromStdString(st->xml());
gloox::Stanza *sf=new gloox::Stanza(s);
sf->addAttribute("id", id);
AsyncRequest *req=new AsyncRequest(-1, this, sf, 3600);
req->setName(cmd);
bot()->asyncRequests()->append(req);
bot()->client()->send(st);
return true;
}
if (cmd=="VERSION" || cmd=="PING")
{
std::string id=bot()->client()->getID();
QString jid=resolveTargetJid(s, arg);
gloox::Stanza *st=gloox::Stanza::createIqStanza(
gloox::JID(jid.toStdString()), id, gloox::StanzaIqGet,
"jabber:iq:version");
qDebug() << QString::fromStdString(st->xml());
gloox::Stanza *sf=new gloox::Stanza(s);
sf->addAttribute("id", id);
AsyncRequest *req=new AsyncRequest(-1, this, sf, 3600);
req->setName(cmd);
bot()->asyncRequests()->append(req);
bot()->client()->send(st);
return true;
}
if (cmd=="DISCO")
{
std::string id=bot()->client()->getID();
QString jid=resolveTargetJid(s, arg);
gloox::Stanza *st=gloox::Stanza::createIqStanza(
gloox::JID(jid.toStdString()), id, gloox::StanzaIqGet,
"http://jabber.org/protocol/disco#items");
gloox::Stanza *sf=new gloox::Stanza(s);
sf->addAttribute("id", id);
AsyncRequest *req=new AsyncRequest(-1, this, sf, 3600);
req->setName(jid);
bot()->asyncRequests()->append(req);
bot()->client()->send(st);
return true;
}
if (cmd=="BANLIST" || cmd=="VOICELIST" || cmd=="MEMBERLIST" ||
cmd=="MODERATORLIST" || cmd=="ADMINLIST" || cmd=="OWNERLIST")
{
std::string id = bot()->client()->getID();
QString jid = QString::fromStdString(s->from().bare());
gloox::Stanza *st = gloox::Stanza::createIqStanza(
gloox::JID(jid.toStdString()), id,
gloox::StanzaIqGet,
"http://jabber.org/protocol/muc#admin");
gloox::Tag* q = st->findChild("query", "xmlns",
"http://jabber.org/protocol/muc#admin");
if (q)
{
gloox::Tag *i = new gloox::Tag(q, "item");
std::string affil;
if (cmd=="MODERATORLIST" || cmd=="MODERLIST")
i->addAttribute("role", "moderator");
else if(cmd=="BANLIST" || cmd=="OUTCAST")
affil = "outcast";
else if(cmd=="VOICELIST" || cmd=="PARTICIPANTLIST")
i->addAttribute("role", "participant");
else if(cmd=="MEMBERLIST")
affil = "member";
else if(cmd=="ADMINLIST")
affil = "admin";
else if(cmd=="OWNERLIST")
affil = "owner";
i->addAttribute("affiliation", affil);
}
st->finalize();
gloox::Stanza *sf = new gloox::Stanza(s);
//.........这里部分代码省略.........
开发者ID:shizeeg, 项目名称:gluxi-hacks, 代码行数:101, 代码来源:userplugin.cpp
示例13: parser
/*
================
idCameraAnim::Load
================
*/
void idCameraAnim::LoadAnim( void ) {
int version;
idLexer parser( LEXFL_ALLOWPATHNAMES | LEXFL_NOSTRINGESCAPECHARS | LEXFL_NOSTRINGCONCAT );
idToken token;
int numFrames;
int numCuts;
int i;
idStr filename;
const char *key;
key = spawnArgs.GetString( "anim" );
if ( !key ) {
gameLocal.Error( "Missing 'anim' key on '%s'", name.c_str() );
}
filename = spawnArgs.GetString( va( "anim %s", key ) );
if ( !filename.Length() ) {
gameLocal.Error( "Missing 'anim %s' key on '%s'", key, name.c_str() );
}
filename.SetFileExtension( MD5_CAMERA_EXT );
if ( !parser.LoadFile( filename ) ) {
gameLocal.Error( "Unable to load '%s' on '%s'", filename.c_str(), name.c_str() );
}
cameraCuts.Clear();
cameraCuts.SetGranularity( 1 );
camera.Clear();
camera.SetGranularity( 1 );
parser.ExpectTokenString( MD5_VERSION_STRING );
version = parser.ParseInt();
if ( version != MD5_VERSION ) {
parser.Error( "Invalid version %d. Should be version %d\n", version, MD5_VERSION );
}
// skip the commandline
parser.ExpectTokenString( "commandline" );
parser.ReadToken( &token );
// parse num frames
parser.ExpectTokenString( "numFrames" );
numFrames = parser.ParseInt();
if ( numFrames <= 0 ) {
parser.Error( "Invalid number of frames: %d", numFrames );
}
// parse framerate
parser.ExpectTokenString( "frameRate" );
frameRate = parser.ParseInt();
if ( frameRate <= 0 ) {
parser.Error( "Invalid framerate: %d", frameRate );
}
// parse num cuts
parser.ExpectTokenString( "numCuts" );
numCuts = parser.ParseInt();
if ( ( numCuts < 0 ) || ( numCuts > numFrames ) ) {
parser.Error( "Invalid number of camera cuts: %d", numCuts );
}
// parse the camera cuts
parser.ExpectTokenString( "cuts" );
parser.ExpectTokenString( "{" );
cameraCuts.SetNum( numCuts );
for( i = 0; i < numCuts; i++ ) {
cameraCuts[ i ] = parser.ParseInt();
if ( ( cameraCuts[ i ] < 1 ) || ( cameraCuts[ i ] >= numFrames ) ) {
parser.Error( "Invalid camera cut" );
}
}
parser.ExpectTokenString( "}" );
// parse the camera frames
parser.ExpectTokenString( "camera" );
parser.ExpectTokenString( "{" );
camera.SetNum( numFrames );
for( i = 0; i < numFrames; i++ ) {
parser.Parse1DMatrix( 3, camera[ i ].t.ToFloatPtr() );
parser.Parse1DMatrix( 3, camera[ i ].q.ToFloatPtr() );
camera[ i ].fov = parser.ParseFloat();
}
parser.ExpectTokenString( "}" );
#if 0
if ( !gameLocal.GetLocalPlayer() ) {
return;
}
idDebugGraph gGraph;
idDebugGraph tGraph;
idDebugGraph qGraph;
idDebugGraph dtGraph;
idDebugGraph dqGraph;
gGraph.SetNumSamples( numFrames );
//.........这里部分代码省略.........
开发者ID:tankorsmash, 项目名称:quadcow, 代码行数:101, 代码来源:Camera.cpp
示例14: ifs
CarModel::CarModel(b2World* world,unsigned int id)
{
m_id = id;
//open the file
std::ifstream ifs("carsetup.TOML");
//make TOML parser
toml::Parser parser(ifs);
toml::Value documentRoot = parser.parse();
toml::Value* params = documentRoot.find("carparams");
// Populate our physic parameters
m_maxForwardSpeed = (float)params->find("max_forward_speed")->as<double>();
m_maxBackwardSpeed = (float)params->find("max_backward_speed")->as<double>();
m_maxDriveForce = (float)params->find("max_drive_force")->as<double>();
m_maxLateralImpulse = (float)params->find("max_lateral_impulse")->as<double>();
m_angularDamping = (float)params->find("angular_damping")->as<double>();
m_angularFriction = (float)params->find("angular_friction")->as<double>();
m_bodyDensity = (float)params->find("body_density")->as<double>();
m_currentTraction = (float)params->find("traction")->as<double>();
m_steerTorque = (float)params->find("steer_torque")->as<double>();
m_steerTorqueOffset = (float)params->find("steer_torque_offset")->as<double>();
m_driftFriction = (float)params->find("drift_friction")->as<double>();
m_dragModifier = (float)params->find("drag_modifier")->as<double>();
m_steerAllowSpeed = (float)params->find("steer_allow_speed")->as<double>();
// Read our polygonal car body vertices
toml::Value* carBodyParams = documentRoot.find("carbody");
const toml::Array& bodyVertices = carBodyParams->find("body_vertices")->as<toml::Array>();
b2Vec2 *vertices = new b2Vec2[bodyVertices.size()];
unsigned int k = 0;
for (const toml::Value& v : bodyVertices)
{
const toml::Array& bodyVerticesCoords = v.as<toml::Array>();
vertices[k++].Set(bodyVerticesCoords.at(0).asNumber(), bodyVerticesCoords.at(1).asNumber());
}
// Create the car body definition
b2BodyDef bodyDef;
// Mark it as dynamic (it's a car so it will move :) )
bodyDef.type = b2_dynamicBody;
// This creates and adds the body to the world (adds it as the first element of the double linked list)
m_body = world->CreateBody(&bodyDef);
// We set the angular damping
m_body->SetAngularDamping(m_angularDamping);
// Create the poly shape from the vertices and link it to a fixture
b2PolygonShape polygonShape;
polygonShape.Set(vertices, bodyVertices.size());
b2Fixture* fixture = m_body->CreateFixture(&polygonShape, m_bodyDensity);
// Set the collision filter for our car (it should only collide with static, i.e walls)
b2Filter filter;
filter.categoryBits = CATEGORY_CAR;
filter.maskBits = CATEGORY_STATIC;
fixture->SetFilterData(filter);
// Set user data so we can identify our car in a possible collision, or sensor trigger
fixture->SetUserData(new CarFUD(id));
// Cleanup
delete[] vertices;
}
开发者ID:flair2005, 项目名称:carvatar, 代码行数:66, 代码来源:CarModel.cpp
六六分期app的软件客服如何联系?不知道吗?加qq群【895510560】即可!标题:六六分期
阅读:19223| 2023-10-27
今天小编告诉大家如何处理win10系统火狐flash插件总是崩溃的问题,可能很多用户都不知
阅读:9996| 2022-11-06
今天小编告诉大家如何对win10系统删除桌面回收站图标进行设置,可能很多用户都不知道
阅读:8331| 2022-11-06
今天小编告诉大家如何对win10系统电脑设置节能降温的设置方法,想必大家都遇到过需要
阅读:8700| 2022-11-06
我们在使用xp系统的过程中,经常需要对xp系统无线网络安装向导设置进行设置,可能很多
阅读:8644| 2022-11-06
今天小编告诉大家如何处理win7系统玩cf老是与主机连接不稳定的问题,可能很多用户都不
阅读:9666| 2022-11-06
电脑对日常生活的重要性小编就不多说了,可是一旦碰到win7系统设置cf烟雾头的问题,很
阅读:8630| 2022-11-06
我们在日常使用电脑的时候,有的小伙伴们可能在打开应用的时候会遇见提示应用程序无法
阅读:8004| 2022-11-06
今天小编告诉大家如何对win7系统打开vcf文件进行设置,可能很多用户都不知道怎么对win
阅读:8664| 2022-11-06
今天小编告诉大家如何对win10系统s4开启USB调试模式进行设置,可能很多用户都不知道怎
阅读:7539| 2022-11-06
请发表评论