Foam::autoPtr<ChemistryModel> Foam::basicChemistryModel::New ( const fvMesh& mesh ) { IOdictionary chemistryDict ( IOobject ( "chemistryProperties", mesh.time().constant(), mesh, IOobject::MUST_READ, IOobject::NO_WRITE, false ) ); word chemistryTypeName; if (chemistryDict.isDict("chemistryType")) { const dictionary& chemistryTypeDict ( chemistryDict.subDict("chemistryType") ); Info<< "Selecting chemistry type " << chemistryTypeDict << endl; const int nCmpt = 8; const char* cmptNames[nCmpt] = { "chemistrySolver", "chemistryModel", "chemistryThermo", "transport", "thermo", "equationOfState", "specie", "energy" }; IOdictionary thermoDict ( IOobject ( "thermophysicalProperties", mesh.time().constant(), mesh, IOobject::MUST_READ_IF_MODIFIED, IOobject::NO_WRITE, false ) ); word thermoTypeName; if (thermoDict.isDict("thermoType")) { const dictionary& thermoTypeDict(thermoDict.subDict("thermoType")); thermoTypeName = word(thermoTypeDict.lookup("transport")) + '<' + word(thermoTypeDict.lookup("thermo")) + '<' + word(thermoTypeDict.lookup("equationOfState")) + '<' + word(thermoTypeDict.lookup("specie")) + ">>," + word(thermoTypeDict.lookup("energy")) + ">"; } else { FatalIOErrorIn ( (ChemistryModel::typeName + "::New(const mesh&)").c_str(), thermoDict ) << "thermoType is in the old format and must be upgraded" << exit(FatalIOError); } Switch isTDAC(chemistryTypeDict.lookupOrDefault("TDAC",false)); // Construct the name of the chemistry type from the components if (isTDAC) { chemistryTypeName = word(chemistryTypeDict.lookup("chemistrySolver")) + '<' + "TDACChemistryModel<" + word(chemistryTypeDict.lookup("chemistryThermo")) + ',' + thermoTypeName + ">>"; } else { chemistryTypeName = word(chemistryTypeDict.lookup("chemistrySolver")) + '<' + "chemistryModel<" + word(chemistryTypeDict.lookup("chemistryThermo")) + ',' + thermoTypeName + ">>"; } typename ChemistryModel::fvMeshConstructorTable::iterator cstrIter = ChemistryModel::fvMeshConstructorTablePtr_->find(chemistryTypeName); if (cstrIter == ChemistryModel::fvMeshConstructorTablePtr_->end()) { FatalErrorIn(ChemistryModel::typeName + "::New(const mesh&)") << "Unknown " << ChemistryModel::typeName << " type " << nl << "chemistryType" << chemistryTypeDict << nl << nl << "Valid " << ChemistryModel ::typeName << " types are:" << nl << nl; // Get the list of all the suitable chemistry packages available wordList validChemistryTypeNames ( ChemistryModel::fvMeshConstructorTablePtr_->sortedToc() ); // Build a table of the thermo packages constituent parts // Note: row-0 contains the names of constituent parts List<wordList> validChemistryTypeNameCmpts ( validChemistryTypeNames.size() + 1 ); validChemistryTypeNameCmpts[0].setSize(nCmpt); forAll(validChemistryTypeNameCmpts[0], j) { validChemistryTypeNameCmpts[0][j] = cmptNames[j]; } // Split the thermo package names into their constituent parts forAll(validChemistryTypeNames, i) { validChemistryTypeNameCmpts[i+1] = basicThermo::splitThermoName ( validChemistryTypeNames[i], nCmpt ); } // Print the table of available packages // in terms of their constituent parts printTable(validChemistryTypeNameCmpts, FatalError); FatalError<< exit(FatalError); }
void word_jump(cell word_) { gc_root<word> word(word_,parent); literal(tag_fixnum(xt_tail_pic_offset)); literal(word.value()); emit(parent->userenv[JIT_WORD_JUMP]); }
HugeNumber operator + ( HugeNumber &u, HugeNumber &v) // Slogenie neotrisatelnix selix chisel { word j; dword k; // Cifra perenosa word uk; // Chislo razriadov u word vk; // Chislo razriadov v word wk; // Chislo razriadov w word kw; dword p; HugeNumber w; // Zdes bydem nakaplivat rezyltat vk=v.Razr(); uk=u.Razr(); wk=wmax(uk,vk); kw=wmin(uk,vk); w.Resize(wk+1); // Delaem nygnyiy razriadnost rezyltata k=0; // Symiryem razriadi po samomy korotkomy chisly for (j=0; j<kw; j++) { p=dword(u.digit[j])+dword(v.digit[j])+k; if (p>=base) { k=1; w.digit[j] = word(p & (base-1)); } else { k=0; w.digit[j]= word(p); }; }; // Tiper nado prosymirovat ostavshiesia razriadi dlinnogo chisla i // razriad perenosa. if (k!=0) { // Bil perenos pri symmirovanii po korotkomy chisly // Nado symmirivat ostavshiesia razriady if (uk>vk) { // Symmiryem, poka est cifra perenosa for (; j<uk; j++) { p=u.digit[j]+k; if (p>=base) { k=1; w.digit[j] = word(p & (base-1)); } else { k=0; w.digit[j]= word(p); break; }; } // Kopiryem ostavshiesia razriady if (k==0) for (j++; j<uk; j++) w.digit[j]=u.digit[j]; } else { // Symmiryem, poka est cifra perenosa for (; j<vk; j++) { p=v.digit[j]+k; w.digit[j]= word(p & (base-1)); if (p>=base) { k=1; } else { k=0; break; }; } // Kopiryem ostavshiesia razriady if (k==0) for (j++; j<vk; j++) w.digit[j]=v.digit[j]; }; if (k!=0) { // Symmirovanie provedeno po vsem razriadam, no eshe est // cifra perenosa w.digit[j]=word(k); } } else { // Nebilo perenosa pri symmirovanii po korotkomy chisly // Nado prosto skopirovat ostavshiesia razriady dlinnogo chisla if (vk>uk) for (; j<vk; j++) w.digit[j]=v.digit[j]; else if (uk>vk) for (; j<uk; j++) w.digit[j]=word(u.digit[j]+k); }; return w; };
int RSIM_Simulator::configure(int argc, char **argv, char **envp) { int argno = 1; if (argno>=argc) { fprintf(stderr, "usage: %s [SIMULATOR_SWITCHES...] [--] SPECIMEN [SPECIMEN_ARGS...]\n", argv[0]); exit(1); } while (argno<argc && '-'==argv[argno][0]) { if (!strcmp(argv[argno], "--")) { argno++; break; } else if (!strncmp(argv[argno], "--log=", 6)) { /* Save log file name pattern, extending it to an absolute name in case the specimen changes directories */ if (argv[argno][6]=='/') { tracing_file_name = argv[argno]+6; } else { char dirname[4096]; char *dirname_p = getcwd(dirname, sizeof dirname); ROSE_ASSERT(dirname_p); tracing_file_name = std::string(dirname) + "/" + (argv[argno]+6); } argno++; } else if (!strncmp(argv[argno], "--debug=", 8)) { tracing_flags = tracingFacilityBit(TRACE_MISC); char *s = argv[argno]+8; while (s && *s) { char *comma = strchr(s, ','); std::string word(s, comma?comma-s:strlen(s)); s = comma ? comma+1 : NULL; if (word=="all") { tracing_flags = (unsigned)(-1); } else if (word=="insn") { tracing_flags |= tracingFacilityBit(TRACE_INSN); } else if (word=="state") { tracing_flags |= tracingFacilityBit(TRACE_STATE); } else if (word=="mem") { tracing_flags |= tracingFacilityBit(TRACE_MEM); } else if (word=="mmap") { tracing_flags |= tracingFacilityBit(TRACE_MMAP); } else if (word=="signal") { tracing_flags |= tracingFacilityBit(TRACE_SIGNAL); } else if (word=="syscall") { tracing_flags |= tracingFacilityBit(TRACE_SYSCALL); } else if (word=="loader") { tracing_flags |= tracingFacilityBit(TRACE_LOADER); } else if (word=="progress") { tracing_flags |= tracingFacilityBit(TRACE_PROGRESS); } else if (word=="thread") { tracing_flags |= tracingFacilityBit(TRACE_THREAD); } else if (word=="futex") { tracing_flags |= tracingFacilityBit(TRACE_FUTEX); } else { fprintf(stderr, "%s: debug words must be from the set: " "all, insn, state, mem, mmap, syscall, signal, loader, progress, thread, futex\n", argv[0]); exit(1); } } argno++; } else if (!strcmp(argv[argno], "--debug")) { tracing_flags = tracingFacilityBit(TRACE_MISC); argno++; } else if (!strncmp(argv[argno], "--core=", 7)) { core_flags = 0; for (char *s=argv[argno]+7; s && *s; /*void*/) { if (!strncmp(s, "elf", 3)) { s += 3; core_flags |= CORE_ELF; } else if (!strncmp(s, "rose", 4)) { s += 4; core_flags |= CORE_ROSE; } else { fprintf(stderr, "%s: unknown core dump type for %s\n", argv[0], argv[argno]); } while (','==*s) s++; } argno++; } else if (!strncmp(argv[argno], "--interp=", 9)) { interp_name = argv[argno++]+9; } else if (!strncmp(argv[argno], "--vdso=", 7)) { vdso_paths.clear(); for (char *s=argv[argno]+7; s && *s; /*void*/) { char *colon = strchr(s, ':'); vdso_paths.push_back(std::string(s, colon?colon-s:strlen(s))); s = colon ? colon+1 : NULL; } argno++; } else if (!strncmp(argv[argno], "--semaphore=", 12)) { std::string semname = argv[argno]+12; if (semname[0]!='/') semname = "/" + semname; if (semname.find_first_of('/', 1)!=std::string::npos) { fprintf(stderr, "%s: invalid semaphore name: \"%s\" should not contain internal slashes\n", argv[0], argv[argno]+12); exit(1); } set_semaphore_name(argv[argno]+12); argno++; } else if (!strcmp(argv[argno], "--showauxv")) { fprintf(stderr, "showing the auxiliary vector for x86sim:\n"); argno++; struct auxv_t { unsigned long type; unsigned long val; }; char **p = envp; if (!p) { fprintf(stderr, "cannot show auxp (no envp)\n"); } else { while (*p++); for (auxv_t *auxvp=(auxv_t*)p; 1; auxvp++) { switch (auxvp->type) { case 0: fprintf(stderr, " 0 AT_NULL %lu\n", auxvp->val); break; case 1: fprintf(stderr, " 1 AT_IGNORE %lu\n", auxvp->val); break; case 2: fprintf(stderr, " 2 AT_EXECFD %lu\n", auxvp->val); break; case 3: fprintf(stderr, " 3 AT_PHDR 0x%lx\n", auxvp->val); break; case 4: fprintf(stderr, " 4 AT_PHENT 0x%lx\n", auxvp->val); break; case 5: fprintf(stderr, " 5 AT_PHNUM %lu\n", auxvp->val); break; case 6: fprintf(stderr, " 6 AT_PAGESZ %lu\n", auxvp->val); break; case 7: fprintf(stderr, " 7 AT_BASE 0x%lx\n", auxvp->val); break; case 8: fprintf(stderr, " 8 AT_FLAGS 0x%lx\n", auxvp->val); break; case 9: fprintf(stderr, " 9 AT_ENTRY 0x%lx\n", auxvp->val); break; case 10: fprintf(stderr, " 10 AT_NOTELF %lu\n", auxvp->val); break; case 11: fprintf(stderr, " 11 AT_UID %ld\n", auxvp->val); break; case 12: fprintf(stderr, " 12 AT_EUID %ld\n", auxvp->val); break; case 13: fprintf(stderr, " 13 AT_GID %ld\n", auxvp->val); break; case 14: fprintf(stderr, " 14 AT_EGID %ld\n", auxvp->val); break; case 15: fprintf(stderr, " 15 AT_PLATFORM 0x%lx\n", auxvp->val); break; case 16: fprintf(stderr, " 16 AT_HWCAP 0x%lx\n", auxvp->val); break; case 17: fprintf(stderr, " 17 AT_CLKTCK %lu\n", auxvp->val); break; case 18: fprintf(stderr, " 18 AT_FPUCW %lu\n", auxvp->val); break; case 19: fprintf(stderr, " 19 AT_DCACHEBSIZE %lu\n", auxvp->val); break; case 20: fprintf(stderr, " 20 AT_ICACHEBSIZE %lu\n", auxvp->val); break; case 21: fprintf(stderr, " 21 AT_UCACHEBSIZE %lu\n", auxvp->val); break; case 22: fprintf(stderr, " 22 AT_IGNOREPPC %lu\n", auxvp->val); break; case 23: fprintf(stderr, " 23 AT_SECURE %ld\n", auxvp->val); break; case 32: fprintf(stderr, " 32 AT_SYSINFO 0x%lx\n", auxvp->val); break; case 33: fprintf(stderr, " 33 AT_SYSINFO_PHDR 0x%lx\n", auxvp->val); break; case 34: fprintf(stderr, " 34 AT_L1I_CACHESHAPE 0x%lx\n", auxvp->val); break; case 35: fprintf(stderr, " 35 AT_L1D_CACHESHAPE 0x%lx\n", auxvp->val); break; case 36: fprintf(stderr, " 36 AT_L2_CACHESHAPE 0x%lx\n", auxvp->val); break; case 37: fprintf(stderr, " 37 AT_L3_CACHESHAPE 0x%lx\n", auxvp->val); break; default: fprintf(stderr, " %lu AT_(unknown) 0x%lx\n", auxvp->type, auxvp->val); break; } if (!auxvp->type) break; } } } else if (!strncmp(argv[argno], "--trace=", 8)) { if (btrace_file) fclose(btrace_file); if (NULL==(btrace_file=fopen(argv[argno]+8, "wb"))) { fprintf(stderr, "%s: %s: %s\n", argv[0], argv[argno]+8, strerror(errno)); exit(1); } #ifdef X86SIM_BINARY_TRACE_UNBUFFERED setbuf(btrace_file, NULL); #endif argno++; } else { fprintf(stderr, "usage: %s [SWITCHES] PROGRAM ARGUMENTS...\n", argv[0]); exit(1); } } return argno; }
uint16_t ModbusGetUserCommandAdditional3() { return word(ModbusUserCommandAdditional3Hi, ModbusUserCommandAdditional3Lo); }
void PolynomialMod2::SetByte(size_t n, byte value) { reg.CleanGrow(BytesToWords(n+1)); reg[n/WORD_SIZE] &= ~(word(0xff) << 8*(n%WORD_SIZE)); reg[n/WORD_SIZE] |= (word(value) << 8*(n%WORD_SIZE)); }
void ntpSync() { const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets int pos; unsigned long timeout; time_t utc, local; TimeChangeRule *tcr; memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) //Serial.println("2"); packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; altSerial.println("AT+CIPSTART=1,\"UDP\",\"192.168.10.253\",123"); if (!waitforLine("OK", 2000)) { Serial.println("Unable to connect to NTP server"); return; } altSerial.println("AT+CIPSEND=1,48"); if (!waitforString(">", 1000)) { Serial.println("Prompt missed"); return; } Serial.println("Sending query"); altSerial.write(packetBuffer, NTP_PACKET_SIZE); if (!waitforString("+IPD,1,48:", 2000)) { Serial.println("NTP Server did not respond"); return; } pos = 0; timeout = millis() + 1000; memset(packetBuffer, 0, NTP_PACKET_SIZE); while ((pos < NTP_PACKET_SIZE) && (millis() < timeout)) { if (altSerial.available() > 0) packetBuffer[pos++] = altSerial.read(); } if (!waitforLine("SEND OK", 2000)) { Serial.println("Failed to send?"); } altSerial.println("AT+CIPCLOSE=1"); if (!waitforLine("OK", 2000)) { Serial.println("Unable to close port"); return; } // Serial.print("Bytes received: "); // Serial.println(pos); unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); // combine the four bytes (two words) into a long integer // this is NTP time (seconds since Jan 1 1900): unsigned long secsSince1900 = highWord << 16 | lowWord; // Serial.print("Seconds since Jan 1 1900 = " ); // Serial.println(secsSince1900); // now convert NTP time into everyday time: // Serial.print("Unix time = "); // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: const unsigned long seventyYears = 2208988800UL; // subtract seventy years: unsigned long epoch = secsSince1900 - seventyYears; // print Unix time: // Serial.println(epoch); setTime(epoch); utc = now(); printTime(utc, "UTC"); local = myTZ.toLocal(utc, &tcr); printTime(local, tcr -> abbrev); }
void TextPreview::drawTextArea(QPainter *painter) { useTimer = false; if(ff8Text.isEmpty()) return; bool jp = font->tableCount() == 4; FF8Window ff8Window = getWindow(); /* Window Background */ if(ff8Window.type!=NOWIN) { painter->translate(realPos(ff8Window)); } painter->setBrush(QPixmap(":/images/menu-fond.png")); /* Frame */ QPen pen(QColor(41,41,41)); pen.setWidth(1); pen.setJoinStyle(Qt::MiterJoin); painter->setPen(pen); painter->drawRect(0, 0, maxW, maxH); painter->setPen(QColor(132,132,132)); painter->drawLine(2, 1, maxW-2, 1); painter->drawLine(1, 2, 1, maxH-2); painter->setPen(QColor(58,58,58)); painter->drawLine(2, maxH-1, maxW-1, maxH-1); painter->drawLine(maxW-1, 2, maxW-1, maxH-2); painter->setPen(QColor(99,99,99)); painter->drawPoint(1, 1); painter->setPen(QColor(82,82,82)); painter->drawPoint(maxW-1, 1); painter->drawPoint(1, maxH-1); int ask_first=-1, ask_last=-1; if(ff8Window.type==0x6f) { ask_first = ff8Window.ask_first; ask_last = ff8Window.ask_last; if(ask_last >= ask_first) painter->drawPixmap(10, 11+16*ask_first, QPixmap(":/images/cursor.png")); } /* Text */ fontColor = TdwFile::White; int charId, line=0, x = (ask_first==0 && ask_last>=0 ? 40 : 8), y = 8; int start = pagesPos.value(currentPage, 0), size = ff8Text.size(); for(int i=start ; i<size ; ++i) { charId = (quint8)ff8Text.at(i); if(charId>=32) { if(jp) { letter(&x, &y, charId-32, painter);// 210-32 } else { if(charId<227) { letter(&x, &y, charId-32, painter); } else if(charId>=232) { letter(&x, &y, optimisedDuo[charId-232][0], painter); letter(&x, &y, optimisedDuo[charId-232][1], painter); } } } else if(charId<=1)//NewPage break; else if(charId==2)//\n { ++line; x = (ask_first<=line && ask_last>=line ? 40 : 8); y += 16; } else if(charId<32) { ++i; switch(charId) { case 0x03: // Character names charId = (quint8)ff8Text.at(i); if(charId>=0x30 && charId<=0x3a) word(&x, &y, names.at(charId-0x30), painter, 5); else if(charId==0x40) word(&x, &y, names.at(11), painter, 5); else if(charId==0x50) word(&x, &y, names.at(12), painter, 5); else if(charId==0x60) word(&x, &y, names.at(13), painter, 5); break; case 0x04:// Var charId = (quint8)ff8Text.at(i); if((charId>=0x20 && charId<=0x27) || (charId>=0x30 && charId<=0x37)) word(&x, &y, FF8Text::toFF8("0", false), painter); else if(charId>=0x40 && charId<=0x47) word(&x, &y, FF8Text::toFF8("00000000", false), painter); break; case 0x05: // Icons charId = (quint8)ff8Text.at(i)-0x20; if(charId>=0 && charId<96) { painter->drawImage(x, y, getIconImage(charId)); x += iconWidth[charId] + iconPadding[charId]; } break; case 0x06: // Colors charId = (quint8)ff8Text.at(i); if(charId>=0x20 && charId<=0x27)// Colors fontColor = (TdwFile::Color)(charId-0x20); else if(charId>=0x28 && charId<=0x2f)// BlinkColors { useTimer = true; fontColor = (TdwFile::Color)(charId-0x20); } break; case 0x0e: // Locations charId = (quint8)ff8Text.at(i); if(charId>=0x20 && charId<=0x27) word(&x, &y, locations.at(charId-0x20), painter, 5); break; case 0x19: // Jap 1 if(jp) { letter(&x, &y, (quint8)ff8Text.at(i)-0x20, painter, 1); } break; case 0x1a: // Jap 2 if(jp) { letter(&x, &y, (quint8)ff8Text.at(i)-0x20, painter, 2); } break; case 0x1b: // Jap 3 if(jp) { letter(&x, &y, (quint8)ff8Text.at(i)-0x20, painter, 3); } break; case 0x1c: // Jap 4 if(jp) { letter(&x, &y, (quint8)ff8Text.at(i)-0x20, painter, 4); } break; } } } }
Foam::binaryOperationSearchableSurface::binaryOperationSearchableSurface ( const IOobject& io, const dictionary& dict ) : searchableSurface(io), aName_(dict.lookupOrDefault<word>("aName","A")), bName_(dict.lookupOrDefault<word>("bName","B")), a_( searchableSurface::New ( word(dict.subDict("a").lookup("type")), IOobject( name()+"_"+word(dict.lookup("type"))+"_"+aName_, io.instance(), io.db(), io.readOpt(), io.writeOpt() ), dict.subDict("a") ) ), b_( searchableSurface::New ( word(dict.subDict("b").lookup("type")), IOobject( name()+"_"+word(dict.lookup("type"))+"_"+bName_, io.instance(), io.db(), io.readOpt(), io.writeOpt() ), dict.subDict("b") ) ), nrARegions_( a().regions().size() ), nrBRegions_( b().regions().size() ) { if(aName_==bName_) { FatalErrorIn("binaryOperationSearchableSurface::binaryOperationSearchableSurface") << "'aName' and 'bName' have the same value " << aName_ << " for " << name() << endl << exit(FatalError); } if(regions().size()!=size()) { FatalErrorIn("binaryOperationSearchableSurface::binaryOperationSearchableSurface") << "Number of regions " << regions().size() << " not equal to size " << size() << nl << "Regions: " << regions() << endl << exit(FatalError); } #ifdef FOAM_SEARCHABLE_SURF_HAS_BOUND_METHOD pointField pts(4); pts[0]=a().bounds().min(); pts[1]=a().bounds().max(); pts[2]=b().bounds().min(); pts[3]=b().bounds().max(); bounds()=boundBox(pts); #endif }
Foam::Istream& Foam::UIPstream::read(token& t) { // Return the put back token if it exists if (Istream::getBack(t)) { return *this; } char c; // return on error if (!read(c)) { t.setBad(); return *this; } // Set the line number of this token to the current stream line number t.lineNumber() = lineNumber(); // Analyse input starting with this character. switch (c) { // Punctuation case token::END_STATEMENT : case token::BEGIN_LIST : case token::END_LIST : case token::BEGIN_SQR : case token::END_SQR : case token::BEGIN_BLOCK : case token::END_BLOCK : case token::COLON : case token::COMMA : case token::ASSIGN : case token::ADD : case token::SUBTRACT : case token::MULTIPLY : case token::DIVIDE : { t = token::punctuationToken(c); return *this; } // Word case token::WORD : { word* pval = new word; if (read(*pval)) { if (token::compound::isCompound(*pval)) { t = token::compound::New(*pval, *this).ptr(); delete pval; } else { t = pval; } } else { delete pval; t.setBad(); } return *this; } // String case token::VERBATIMSTRING : { // Recurse to read actual string read(t); t.type() = token::VERBATIMSTRING; return *this; } case token::VARIABLE : { // Recurse to read actual string read(t); t.type() = token::VARIABLE; return *this; } case token::STRING : { string* pval = new string; if (read(*pval)) { t = pval; if (c == token::VERBATIMSTRING) { t.type() = token::VERBATIMSTRING; } } else { delete pval; t.setBad(); } return *this; } // Label case token::LABEL : { label val; if (read(val)) { t = val; } else { t.setBad(); } return *this; } // floatScalar case token::FLOAT_SCALAR : { floatScalar val; if (read(val)) { t = val; } else { t.setBad(); } return *this; } // doubleScalar case token::DOUBLE_SCALAR : { doubleScalar val; if (read(val)) { t = val; } else { t.setBad(); } return *this; } // Character (returned as a single character word) or error default: { if (isalpha(c)) { t = word(c); return *this; } setBad(); t.setBad(); return *this; } } }
Foam::searchableSurfaces::searchableSurfaces ( const IOobject& io, const dictionary& topDict ) : PtrList<searchableSurface>(topDict.size()), names_(topDict.size()), regionNames_(topDict.size()), allSurfaces_(identity(topDict.size())) { label surfI = 0; forAllConstIter(dictionary, topDict, iter) { const word& key = iter().keyword(); if (!topDict.isDict(key)) { FatalErrorIn ( "searchableSurfaces::searchableSurfaces" "( const IOobject&, const dictionary&)" ) << "Found non-dictionary entry " << iter() << " in top-level dictionary " << topDict << exit(FatalError); } const dictionary& dict = topDict.subDict(key); names_[surfI] = key; dict.readIfPresent("name", names_[surfI]); // Make IOobject with correct name autoPtr<IOobject> namedIO(io.clone()); // Note: we would like to e.g. register triSurface 'sphere.stl' as // 'sphere'. Unfortunately // no support for having object read from different location than // their object name. Maybe have stlTriSurfaceMesh which appends .stl // when reading/writing? namedIO().rename(key); // names_[surfI] // Create and hook surface set ( surfI, searchableSurface::New ( dict.lookup("type"), namedIO(), dict ) ); const searchableSurface& s = operator[](surfI); // Construct default region names by prepending surface name // to region name. const wordList& localNames = s.regions(); wordList& rNames = regionNames_[surfI]; rNames.setSize(localNames.size()); forAll(localNames, regionI) { rNames[regionI] = names_[surfI] + '_' + localNames[regionI]; } // See if dictionary provides any global region names. if (dict.found("regions")) { const dictionary& regionsDict = dict.subDict("regions"); forAllConstIter(dictionary, regionsDict, iter) { const word& key = iter().keyword(); if (regionsDict.isDict(key)) { // Get the dictionary for region iter.keyword() const dictionary& regionDict = regionsDict.subDict(key); label index = findIndex(localNames, key); if (index == -1) { FatalErrorIn ( "searchableSurfaces::searchableSurfaces" "( const IOobject&, const dictionary&)" ) << "Unknown region name " << key << " for surface " << s.name() << endl << "Valid region names are " << localNames << exit(FatalError); } rNames[index] = word(regionDict.lookup("name")); } } } surfI++; }
void contentTypeField::setBoundary(const string& boundary) { getParameter("boundary")->setValue(word(boundary, vmime::charsets::US_ASCII)); }
void contentTypeField::setReportType(const string& reportType) { getParameter("report-type")->setValue(word(reportType, vmime::charsets::US_ASCII)); }
TerrainManager::TerrainManager( const Time & runTime, const dictionary & dict, const searchableSurface * const stl_ ): BlockMeshManager(runTime), stl_(stl_), blockNrs_(dict.lookup("blocks")), cellNrs_(dict.lookup("cells")), domainBox_ ( CoordinateSystem ( point(dict.lookup("p_corner")), List< Foam::vector >(dict.subDict("coordinates").lookup("baseVectors")) ), scalarList(dict.lookup("dimensions")), dict.lookupOrDefault< scalar >("boxResolution",0.0001) ), stlBox_(domainBox_), splineNormalDist_(0), mode_upwardSplines_(0), zeroLevel_(0), gradingFactors_(dict.lookup("gradingFactors")), cylinderModule_(this), modificationModule_(this), gradingModule_(this), blendingFunction_ ( new ScalarBlendingFunction() ){ // Read dictionary: p_above_ = point(dict.lookup("p_above")); maxDistProj_ = readScalar(dict.lookup("maxDistProj")); // option for stl_ inside the domain box: if(dict.found("stlInsideBox")){ if(dict.subDict("stlInsideBox").found("zeroLevel")){ zeroLevel_ = readScalar(dict.subDict("stlInsideBox").lookup("zeroLevel")); } stlBox_ = Box ( CoordinateSystem ( point(dict.subDict("stlInsideBox").lookup("p_corner_inside_stl")), coordinateSystem().axes() ), scalarList(dict.subDict("stlInsideBox").lookup("dimensions_inside_stl")), dict.subDict("stlInsideBox").lookupOrDefault< scalar >("boxResolution",0.0001) ); blendingFunction_ = ScalarBlendingFunction::New ( dict.subDict("stlInsideBox").subDict("blendingFunction") ); if(dict.subDict("stlInsideBox").subDict("blendingFunction").found("writePDF")){ const dictionary & writeDict = dict.subDict("stlInsideBox").subDict("blendingFunction").subDict("writePDF"); blendingFunction_().writePDFs ( word(writeDict.lookup("baseName")), fileName(writeDict.lookup("resultsFolder")), point(writeDict.lookup("probePoint0")), point(writeDict.lookup("probePoint1")), 0,1, readLabel(writeDict.lookup("steps")), readLabel(writeDict.lookup("plotPoints")), readLabel(writeDict.lookup("interpolOrder")) ); } else { Info << "TerrainManager: keyword 'writePDF' not found in sub dictionary 'blendingFunction'." << endl; } } // module orography modifications: if(dict.found("terrainModification")){ Info << " loading orography modification module" << endl; if(!modificationModule_.load(dict.subDict("terrainModification"))){ Info << "\n TerrainManager: Error while loading orography modification module." << endl; throw; } } // module block grading: if(dict.found("blockGrading")){ Info << " loading block grading module" << endl; if(!gradingModule_.load(dict.subDict("blockGrading"))){ Info << "\n TerrainManager: Error while loading block grading module." << endl; throw; } } // module outer cylinder: if(dict.found("outerCylinder")){ Info << " loading cylinder module" << endl; if(!cylinderModule_.load(dict.subDict("outerCylinder"))){ Info << "\n TerrainManager: Error while loading cylinder module." << endl; throw; } } // option for othogonalization of upward splines: if(dict.found("orthogonalizeUpwardSplines")){ dictionary upsDict = dict.subDict("orthogonalizeUpwardSplines"); splineNormalDist_ = readScalar(upsDict.lookup("splineNormalDist")); if(upsDict.found("ignoreBoundary")) mode_upwardSplines_ = 2; else mode_upwardSplines_ = 1; } // add patches: patchesRef().resize(6); patchesRef().set ( Block::WEST, new BlockMeshPatch ( *this, word(dict.lookup("patch_name_west")), word(dict.lookup("patch_type_west")) ) ); patchesRef().set ( Block::EAST, new BlockMeshPatch ( *this, word(dict.lookup("patch_name_east")), word(dict.lookup("patch_type_east")) ) ); patchesRef().set ( Block::SOUTH, new BlockMeshPatch ( *this, word(dict.lookup("patch_name_south")), word(dict.lookup("patch_type_south")) ) ); patchesRef().set ( Block::NORTH, new BlockMeshPatch ( *this, word(dict.lookup("patch_name_north")), word(dict.lookup("patch_type_north")) ) ); patchesRef().set ( Block::GROUND, new BlockMeshPatch ( *this, word(dict.lookup("patch_name_ground")), word(dict.lookup("patch_type_ground")) ) ); patchesRef().set ( Block::SKY, new BlockMeshPatch ( *this, word(dict.lookup("patch_name_sky")), word(dict.lookup("patch_type_sky")) ) ); // only one block in up direction: blockNrs_[UP] = 1; // set spline point numbers: splinePointNrs_.resize(3); splinePointNrs_[0] = cellNrs_[0] - 1; splinePointNrs_[1] = cellNrs_[1] - 1; splinePointNrs_[2] = cellNrs_[2] - 1; // init landscape_: if(stl_){ landscape_.set ( new STLLandscape ( stl_, &(blendingFunction_()), &domainBox_, &stlBox_, zeroLevel_ ) ); } // output boxes: domainBox_.writeSTL("domainBox.stl"); stlBox_.writeSTL("stlBox.stl"); }
/* * Read an ascii label in from fd f, * in the same format as that put out by display(), * and fill in lp. */ static int getasciilabel(FILE *f, struct disklabel *lp) { char *cp, *endp; const char **cpp; u_int part; char *tp, line[BUFSIZ]; u_long v; int lineno = 0, errors = 0; int i; makelabel("auto", lp); bzero(&part_set, sizeof(part_set)); bzero(&part_size_type, sizeof(part_size_type)); bzero(&part_offset_type, sizeof(part_offset_type)); lp->d_bbsize = BBSIZE; /* XXX */ lp->d_sbsize = 0; /* XXX */ while (fgets(line, sizeof(line) - 1, f)) { lineno++; if ((cp = strchr(line,'\n')) != 0) *cp = '\0'; cp = skip(line); if (cp == NULL) continue; tp = strchr(cp, ':'); if (tp == NULL) { fprintf(stderr, "line %d: syntax error\n", lineno); errors++; continue; } *tp++ = '\0', tp = skip(tp); if (!strcmp(cp, "type")) { if (tp == NULL) tp = unknown; cpp = dktypenames; for (; cpp < &dktypenames[DKMAXTYPES]; cpp++) if (*cpp && !strcmp(*cpp, tp)) { lp->d_type = cpp - dktypenames; break; } if (cpp < &dktypenames[DKMAXTYPES]) continue; errno = 0; v = strtoul(tp, &endp, 10); if (errno != 0 || *endp != '\0') v = DKMAXTYPES; if (v >= DKMAXTYPES) fprintf(stderr, "line %d:%s %lu\n", lineno, "Warning, unknown disk type", v); else lp->d_type = v; continue; } if (!strcmp(cp, "flags")) { for (v = 0; (cp = tp) && *cp != '\0';) { tp = word(cp); if (!strcmp(cp, "removeable")) v |= D_REMOVABLE; else if (!strcmp(cp, "ecc")) v |= D_ECC; else if (!strcmp(cp, "badsect")) v |= D_BADSECT; else { fprintf(stderr, "line %d: %s: bad flag\n", lineno, cp); errors++; } } lp->d_flags = v; continue; } if (!strcmp(cp, "drivedata")) { for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) { lp->d_drivedata[i++] = strtoul(cp, NULL, 10); tp = word(cp); } continue; } if (sscanf(cp, "%lu partitions", &v) == 1) { if (v > MAXPARTITIONS) { fprintf(stderr, "line %d: bad # of partitions\n", lineno); lp->d_npartitions = MAXPARTITIONS; errors++; } else if (v < DEFPARTITIONS) { fprintf(stderr, "line %d: bad # of partitions\n", lineno); lp->d_npartitions = DEFPARTITIONS; errors++; } else lp->d_npartitions = v; continue; } if (tp == NULL) tp = blank; if (!strcmp(cp, "disk")) { strncpy(lp->d_typename, tp, sizeof (lp->d_typename)); continue; } if (!strcmp(cp, "label")) { strncpy(lp->d_packname, tp, sizeof (lp->d_packname)); continue; } if (!strcmp(cp, "bytes/sector")) { v = strtoul(tp, NULL, 10); if (v == 0 || (v % DEV_BSIZE) != 0) { fprintf(stderr, "line %d: %s: bad sector size\n", lineno, tp); errors++; } else lp->d_secsize = v; continue; } if (!strcmp(cp, "sectors/track")) { v = strtoul(tp, NULL, 10); #if (ULONG_MAX != 0xffffffffUL) if (v == 0 || v > 0xffffffff) #else if (v == 0) #endif { fprintf(stderr, "line %d: %s: bad %s\n", lineno, tp, cp); errors++; } else lp->d_nsectors = v; continue; } if (!strcmp(cp, "sectors/cylinder")) { v = strtoul(tp, NULL, 10); if (v == 0) { fprintf(stderr, "line %d: %s: bad %s\n", lineno, tp, cp); errors++; } else lp->d_secpercyl = v; continue; } if (!strcmp(cp, "tracks/cylinder")) { v = strtoul(tp, NULL, 10); if (v == 0) { fprintf(stderr, "line %d: %s: bad %s\n", lineno, tp, cp); errors++; } else lp->d_ntracks = v; continue; } if (!strcmp(cp, "cylinders")) { v = strtoul(tp, NULL, 10); if (v == 0) { fprintf(stderr, "line %d: %s: bad %s\n", lineno, tp, cp); errors++; } else lp->d_ncylinders = v; continue; } if (!strcmp(cp, "sectors/unit")) { v = strtoul(tp, NULL, 10); if (v == 0) { fprintf(stderr, "line %d: %s: bad %s\n", lineno, tp, cp); errors++; } else lp->d_secperunit = v; continue; } if (!strcmp(cp, "rpm")) { v = strtoul(tp, NULL, 10); if (v == 0 || v > USHRT_MAX) { fprintf(stderr, "line %d: %s: bad %s\n", lineno, tp, cp); errors++; } else lp->d_rpm = v; continue; } if (!strcmp(cp, "interleave")) { v = strtoul(tp, NULL, 10); if (v == 0 || v > USHRT_MAX) { fprintf(stderr, "line %d: %s: bad %s\n", lineno, tp, cp); errors++; } else lp->d_interleave = v; continue; } if (!strcmp(cp, "trackskew")) { v = strtoul(tp, NULL, 10); if (v > USHRT_MAX) { fprintf(stderr, "line %d: %s: bad %s\n", lineno, tp, cp); errors++; } else lp->d_trackskew = v; continue; } if (!strcmp(cp, "cylinderskew")) { v = strtoul(tp, NULL, 10); if (v > USHRT_MAX) { fprintf(stderr, "line %d: %s: bad %s\n", lineno, tp, cp); errors++; } else lp->d_cylskew = v; continue; } if (!strcmp(cp, "headswitch")) { v = strtoul(tp, NULL, 10); lp->d_headswitch = v; continue; } if (!strcmp(cp, "track-to-track seek")) { v = strtoul(tp, NULL, 10); lp->d_trkseek = v; continue; } /* the ':' was removed above */ if (*cp < 'a' || *cp > MAX_PART || cp[1] != '\0') { fprintf(stderr, "line %d: %s: Unknown disklabel field\n", lineno, cp); errors++; continue; } /* Process a partition specification line. */ part = *cp - 'a'; if (part >= lp->d_npartitions) { fprintf(stderr, "line %d: partition name out of range a-%c: %s\n", lineno, 'a' + lp->d_npartitions - 1, cp); errors++; continue; } part_set[part] = 1; if (getasciipartspec(tp, lp, part, lineno) != 0) { errors++; break; } } errors += checklabel(lp); return (errors == 0); }
Foam::autoPtr<Foam::dynamicFvMesh> Foam::dynamicFvMesh::New(const IOobject& io) { wordList libNames(1); libNames[0]=word("mesquiteMotionSolver"); forAll(libNames,i) { const word libName("lib"+libNames[i]+".so"); bool ok=dlLibraryTable::open(libName); if(!ok) { WarningIn("dynamicFvMesh::New(const IOobject& io)") << "Loading of dynamic mesh library " << libName << " unsuccesful. Some dynamic mesh methods may not be " << " available" << endl; } } // Enclose the creation of the dynamicMesh to ensure it is // deleted before the dynamicFvMesh is created otherwise the dictionary // is entered in the database twice IOdictionary dynamicMeshDict ( IOobject ( "dynamicMeshDict", io.time().constant(), (io.name() == dynamicFvMesh::defaultRegion ? "" : io.name() ), io.db(), IOobject::MUST_READ, IOobject::NO_WRITE, false ) ); word dynamicFvMeshTypeName(dynamicMeshDict.lookup("dynamicFvMesh")); Info<< "Selecting dynamicFvMesh " << dynamicFvMeshTypeName << endl; dlLibraryTable::open ( dynamicMeshDict, "dynamicFvMeshLibs", IOobjectConstructorTablePtr_ ); if (!IOobjectConstructorTablePtr_) { FatalErrorIn ( "dynamicFvMesh::New(const IOobject&)" ) << "dynamicFvMesh table is empty" << exit(FatalError); } IOobjectConstructorTable::iterator cstrIter = IOobjectConstructorTablePtr_->find(dynamicFvMeshTypeName); if (cstrIter == IOobjectConstructorTablePtr_->end()) { FatalErrorIn ( "dynamicFvMesh::New(const IOobject&)" ) << "Unknown dynamicFvMesh type " << dynamicFvMeshTypeName << endl << endl << "Valid dynamicFvMesh types are :" << endl << IOobjectConstructorTablePtr_->toc() << exit(FatalError); } return autoPtr<dynamicFvMesh>(cstrIter()(io)); }
Foam::relativeVelocityModels::fromMesoscale::fromMesoscale ( const dictionary& dict, const incompressibleTwoPhaseInteractingMixture& mixture ) : relativeVelocityModel(dict, mixture), Vr_(const_cast< GeometricField < vector, fvPatchField, volMesh > &>(mixture.U().mesh().lookupObject< GeometricField <vector, fvPatchField, volMesh> >(word("Vr")))) {}
int main(int argc, char *argv[]) { time_t start = clock(); int noWords; char str[100]; scanf("%d", &noWords); #ifdef DEBUG printf(">%d<\n",noWord); fflush(stdio); #endif int i=0, len; long long totalChars = 0; while(i < noWords) { scanf("%s", str); std::string word(str); #ifdef DEBUG printf(">%s<\n",&word[0]); #endif len = word.length(); for(int j=0;j<len;++j) { if(word[j]>='A' && word[j]<='Z') { word[j] += 32; } } try { #ifndef TST trie.insert(word,min(KeywordExtractor :: MAX_TRIE_DEPTH, len)); #else trie.insert(word, len); #endif totalChars += len; } catch (MyException exp) { std::cout << "\nFor string " << word << " Error: " << exp; } ++i; } std::string checks[3] = {"hello", "cat", "bomb"}; int sizeCheck = sizeof(checks)/sizeof(std::string); printf("\n>sizeCheck: %d<", sizeCheck); for(int i=0;i<sizeCheck;++i) { if( #ifdef TST trie.check(checks[i], checks[i].length()) #else trie.check(checks[i],min(KeywordExtractor :: MAX_TRIE_DEPTH, checks[i].length())) #endif ) printf("\nGot %s", &checks[i][0]); } printf("\nTotalChars : %d\n", totalChars); int totalTries = trie.countAll(); int totalMemory = totalTries * #ifdef TST sizeof(KeywordExtractor::TernarySearchTree); #else sizeof(KeywordExtractor :: Trie); #endif printf("\nTotal Tries:%d\nTotal Memory: %d\nUseful Memory (perc.): %f\n", totalTries, totalMemory, ((100*totalChars)/(double)totalMemory)); if(argc == 2) { std::ifstream inf(argv[1]); if(!inf.is_open()) { std::cout << "\nCan't open file: " << argv[1]; } else { std::map<std::string, int> countKeywords; std::string word; bool badWord = false; while(!inf.eof()) { inf >> word; len = word.length(); badWord = false; for(int i=0;i<len;++i) { if(word[i]>='A' && word[i]<='Z') { word[i] += 32; } else if(!(word[i]>='a' && word[i]<='z')) { badWord = true; break; } } if(badWord) { continue; } try { if(!trie.check(word, #ifdef TST len) #else min(KeywordExtractor :: MAX_TRIE_DEPTH, len)) #endif ) { ++countKeywords[word]; } } catch (MyException exp) { } } struct Result { std::string keyword; int count; Result(std::string _k, int _c) : keyword(_k), count(_c) { } bool operator<(const Result &res) const { return count > res.count; } }; std::vector<Result> results; std::cout << "\nKeyword\tCount\n"; for(std::map<std::string,int>::iterator mit = countKeywords.begin(); mit != countKeywords.end(); ++mit) { results.push_back(Result(mit->first, mit->second)); // std::cout << mit->first << "\t" << mit->second << std::endl; } sort(results.begin(), results.end()); for(std::vector<Result> :: iterator rit = results.begin(); rit < results.end(); ++rit) { std::cout << rit->keyword << "\t" << rit->count << std::endl; } } }
// Walk through a string, applying the rules specified by the keyword token list and // create a list of color segments. void LLKeywords::findSegments(std::vector<LLTextSegment *>* seg_list, const LLWString& wtext, const LLColor4 &defaultColor) { std::for_each(seg_list->begin(), seg_list->end(), DeletePointer()); seg_list->clear(); if( wtext.empty() ) { return; } S32 text_len = wtext.size(); seg_list->push_back( new LLTextSegment( LLColor3(defaultColor), 0, text_len ) ); const llwchar* base = wtext.c_str(); const llwchar* cur = base; const llwchar* line = NULL; while( *cur ) { if( *cur == '\n' || cur == base ) { if( *cur == '\n' ) { cur++; if( !*cur || *cur == '\n' ) { continue; } } // Start of a new line line = cur; // Skip white space while( *cur && isspace(*cur) && (*cur != '\n') ) { cur++; } if( !*cur || *cur == '\n' ) { continue; } // cur is now at the first non-whitespace character of a new line // Line start tokens { BOOL line_done = FALSE; for (token_list_t::iterator iter = mLineTokenList.begin(); iter != mLineTokenList.end(); ++iter) { LLKeywordToken* cur_token = *iter; if( cur_token->isHead( cur ) ) { S32 seg_start = cur - base; while( *cur && *cur != '\n' ) { // skip the rest of the line cur++; } S32 seg_end = cur - base; LLTextSegment* text_segment = new LLTextSegment( cur_token->getColor(), seg_start, seg_end ); text_segment->setToken( cur_token ); insertSegment( seg_list, text_segment, text_len, defaultColor); line_done = TRUE; // to break out of second loop. break; } } if( line_done ) { continue; } } } // Skip white space while( *cur && isspace(*cur) && (*cur != '\n') ) { cur++; } while( *cur && *cur != '\n' ) { // Check against delimiters { S32 seg_start = 0; LLKeywordToken* cur_delimiter = NULL; for (token_list_t::iterator iter = mDelimiterTokenList.begin(); iter != mDelimiterTokenList.end(); ++iter) { LLKeywordToken* delimiter = *iter; if( delimiter->isHead( cur ) ) { cur_delimiter = delimiter; break; } } if( cur_delimiter ) { S32 between_delimiters = 0; S32 seg_end = 0; seg_start = cur - base; cur += cur_delimiter->getLength(); if( cur_delimiter->getType() == LLKeywordToken::TWO_SIDED_DELIMITER ) { while( *cur && !cur_delimiter->isHead(cur)) { // Check for an escape sequence. if (*cur == '\\') { // Count the number of backslashes. S32 num_backslashes = 0; while (*cur == '\\') { num_backslashes++; between_delimiters++; cur++; } // Is the next character the end delimiter? if (cur_delimiter->isHead(cur)) { // Is there was an odd number of backslashes, then this delimiter // does not end the sequence. if (num_backslashes % 2 == 1) { between_delimiters++; cur++; } else { // This is an end delimiter. break; } } } else { between_delimiters++; cur++; } } if( *cur ) { cur += cur_delimiter->getLength(); seg_end = seg_start + between_delimiters + 2 * cur_delimiter->getLength(); } else { // eof seg_end = seg_start + between_delimiters + cur_delimiter->getLength(); } } else { llassert( cur_delimiter->getType() == LLKeywordToken::ONE_SIDED_DELIMITER ); // Left side is the delimiter. Right side is eol or eof. while( *cur && ('\n' != *cur) ) { between_delimiters++; cur++; } seg_end = seg_start + between_delimiters + cur_delimiter->getLength(); } LLTextSegment* text_segment = new LLTextSegment( cur_delimiter->getColor(), seg_start, seg_end ); text_segment->setToken( cur_delimiter ); insertSegment( seg_list, text_segment, text_len, defaultColor); // Note: we don't increment cur, since the end of one delimited seg may be immediately // followed by the start of another one. continue; } } // check against words llwchar prev = cur > base ? *(cur-1) : 0; if( !isalnum( prev ) && (prev != '_') ) { const llwchar* p = cur; while( isalnum( *p ) || (*p == '_') ) { p++; } S32 seg_len = p - cur; if( seg_len > 0 ) { LLWString word( cur, 0, seg_len ); word_token_map_t::iterator map_iter = mWordTokenMap.find(word); if( map_iter != mWordTokenMap.end() ) { LLKeywordToken* cur_token = map_iter->second; S32 seg_start = cur - base; S32 seg_end = seg_start + seg_len; // llinfos << "Seg: [" << word.c_str() << "]" << llendl; LLTextSegment* text_segment = new LLTextSegment( cur_token->getColor(), seg_start, seg_end ); text_segment->setToken( cur_token ); insertSegment( seg_list, text_segment, text_len, defaultColor); } cur += seg_len; continue; } } if( *cur && *cur != '\n' ) { cur++; } } } }
bool Foam::IOobject::readHeader(Istream& is) { if (IOobject::debug) { Info<< "IOobject::readHeader(Istream&) : reading header for file " << is.name() << endl; } // Check Istream not already bad if (!is.good()) { if (rOpt_ == MUST_READ || rOpt_ == MUST_READ_IF_MODIFIED) { FatalIOErrorIn("IOobject::readHeader(Istream&)", is) << " stream not open for reading essential object from file " << is.name() << exit(FatalIOError); } if (IOobject::debug) { SeriousIOErrorIn("IOobject::readHeader(Istream&)", is) << " stream not open for reading from file " << is.name() << endl; } return false; } token firstToken(is); if ( is.good() && firstToken.isWord() && firstToken.wordToken() == "FoamFile" ) { dictionary headerDict(is); is.version(headerDict.lookup("version")); is.format(headerDict.lookup("format")); headerClassName_ = word(headerDict.lookup("class")); const word headerObject(headerDict.lookup("object")); if (IOobject::debug && headerObject != name()) { IOWarningIn("IOobject::readHeader(Istream&)", is) << " object renamed from " << name() << " to " << headerObject << " for file " << is.name() << endl; } // The note entry is optional headerDict.readIfPresent("note", note_); } else { SeriousIOErrorIn("IOobject::readHeader(Istream&)", is) << "First token could not be read or is not the keyword 'FoamFile'" << nl << nl << "Check header is of the form:" << nl << endl; writeHeader(Info); return false; } // Check stream is still OK if (is.good()) { objState_ = GOOD; } else { if (rOpt_ == MUST_READ || rOpt_ == MUST_READ_IF_MODIFIED) { FatalIOErrorIn("IOobject::readHeader(Istream&)", is) << " stream failure while reading header" << " on line " << is.lineNumber() << " of file " << is.name() << " for essential object" << name() << exit(FatalIOError); } if (IOobject::debug) { Info<< "IOobject::readHeader(Istream&) :" << " stream failure while reading header" << " on line " << is.lineNumber() << " of file " << is.name() << endl; } objState_ = BAD; return false; } if (IOobject::debug) { Info<< " .... read" << endl; } return true; }
/** * Keeps connection to the cameras alive: Reads UDP incoming and empties/processes the outgoing command queue * Therefore: Call this in the loop() function and make sure it gets called multiple times a second, including after sending commands. */ void ClientSonyVISCAoverIP::runLoop(uint16_t delayTime) { unsigned long enterTime = millis(); do { // Reading incoming UDP data on port: while (true) { // Iterate until UDP buffer is empty uint16_t packetSize = _Udp.parsePacket(); if (_Udp.available()) { IPAddress remote = _Udp.remoteIP(); uint8_t cam = remote[3] - forthByteBase; // Select the cam from the IP address. if (camNumOK(cam)) { // valid range for VISCA _Udp.read(_packetBuffer, 8); // Read header uint16_t payloadType = word(_packetBuffer[0], _packetBuffer[1]); uint16_t packetLength = word(_packetBuffer[2], _packetBuffer[3]); uint16_t sequenceNumber = word(_packetBuffer[6], _packetBuffer[7]); // Actually, this is probably a 32 bit unsigned long... if (packetSize == packetLength + 8) { // Just to make sure these are equal, they should be! if (_serialOutput & 0x80) { Serial << "Incoming Packet from cam #" << cam << " (" << packetLength << " bytes): 0x" << _HEXPADL(payloadType, 4, "0") << ": "; for (uint8_t a = 4; a < 8; a++) { Serial << _HEXPADL(_packetBuffer[a], 2, "0") << " "; } Serial << " / "; } // Read the VISCA packet itself: _Udp.read(_packetBuffer, SONYVISCAIP_packetBufferLength); if (_serialOutput & 0x80) { for (uint8_t a = 0; a < packetLength; a++) { Serial << _HEXPADL(_packetBuffer[a], 2, "0") << " "; } Serial << ": "; } if (!_isConnected[cam - 1]) { // If not connected, look for reply to reset counter package if (payloadType == 0x0201 && packetLength == 1 && _packetBuffer[0] == 0x01) { // Response to sequence number "RESET" connect package _isConnected[cam - 1] = true; if (_serialOutput & 0x80) { Serial << F("Connected to VISCA camera #") << cam << "\n"; } } } else { _lastContact[cam - 1] = millis(); _pushedStateUpdate[cam - 1] = false; if (_camLastTX[cam - 1] > 0) { // Waiting for response // if (_localPacketIdCounter[cam - 1] == sequenceNumber) { // the returned sequence number is a reference to the sequence number we sent to the camera - but notice that an ack and complete package will refer to the same number. At the moment I see no need to track the package number - we just look for acks and ignores "completes" if (payloadType == 0x0111 && _packetBuffer[0] == 0x90) { if (_applicationCommandBuffer[cam - 1][_applicationCommandBufferCurrentIndex[cam - 1]][0] == 0x01 && packetLength == 3 && (_packetBuffer[1] & 0xF0) == 0x40) { // an ack for a command if (_serialOutput & 0x80) { Serial << "ACK in " << (millis() - _camLastTX[cam - 1]) << "ms\n"; } _camLastTX[cam - 1] = 0; } if (_applicationCommandBuffer[cam - 1][_applicationCommandBufferCurrentIndex[cam - 1]][0] == 0x01 && packetLength == 4 && (_packetBuffer[1] & 0xF0) == 0x60) { // an error for a command if (_serialOutput) { Serial << "ERROR in " << (millis() - _camLastTX[cam - 1]) << "ms\n"; } _camLastTX[cam - 1] = 0; } if (_applicationCommandBuffer[cam - 1][_applicationCommandBufferCurrentIndex[cam - 1]][0] == 0x09 && (_packetBuffer[1] & 0xF0) == 0x50) { // a inquery answer if (_serialOutput & 0x80) { Serial << "INQUERY ANS in " << (millis() - _camLastTX[cam - 1]) << "ms\n"; } _camLastTX[cam - 1] = 0; parsePacketBufferInqueryData(cam); } } } } if (_serialOutput & 0x80) { Serial << "\n"; } } else { //#if SONYVISCAIP_debug if (_serialOutput & 0x80) { Serial.print(F("ERROR: Packet size mismatch: ")); Serial.print(packetSize, DEC); Serial.print(F(" != ")); Serial.println(packetLength, DEC); } //#endif // Flushing larger packets while (_Udp.available()) { _Udp.read(_packetBuffer, SONYVISCAIP_packetBufferLength); } } } else { Serial << "ERROR: Cam number " << cam << " out of range!\n"; } } else break; } // Send a command from buffer to cameras: for (uint8_t cam = 1; cam <= SONYVISCAIP_cams; cam++) { sendCommand(cam); } // If connection is gone anyway, try to reconnect: for (uint8_t cam = 1; cam <= SONYVISCAIP_cams; cam++) { if (_camOnline[cam - 1]) { if (hasTimedOut(_lastContact[cam - 1], 400) && _applicationCommandBufferLastPositionAdded[cam - 1] == _applicationCommandBufferCurrentIndex[cam - 1]) { // Send a "get state update" when nothing else happens (output buffer is empty) // if (_serialOutput) // Serial.println(F("pushNextStateUpdate()")); pushNextStateUpdate(cam); } else if (hasTimedOut(_lastContact[cam - 1], 1000 + 2000)) { // Allow a get state update 2000 ms to register if (_serialOutput) Serial.println(F("Connection to Camera has timed out - reconnecting!")); connect(cam); } } } } while (delayTime > 0 && !hasTimedOut(enterTime, delayTime)); }
void creat_index (mot* *tab,char name[26]) { page *ptrpg; mot *ptr,*ptr1,*ptr2; int s = 0, z = 0,f; float num_page ; for (s = 0 ; s <26 ; s++) { tab[s]=NULL; } s=0 ; // on a utilise la variable s comme compteur pour compter le nbr du ligne :) char chain[100],chain1[100]; FILE *fp; fp = fopen(name,"rt"); if (fp == NULL) { printf("\n\n\t Impossible d'ouvrir le fichier \n") ; printf(" veuillez verifier Que le Fichier %s exist et dans le meme directory\n\n\n\n",name); Sleep(5000); exit (3); } else { while (fgets (chain,100,fp)!= NULL) { // on prend une ligne de 100 carectere s = s +1 ; // on a utilise la variable s comme compteur pour compter le nbr du ligne :) if (strlen(chain) != 1 ) { // on verifie si la chaine n'est pas vide or \n only write(chain); // on ecrase et on ecrit la ligne dans un fichier tmp.txt FILE *ft ; // on ouvre le fichier tmp.txt cette fois en mode lire seulement ft = fopen("tmp.txt","rt"); while (fscanf(ft,"%s",chain1) != EOF) { float j ; j = s ; // on lit jusqu"a la fin du fichier tmp.txt Qui contient une seul ligne num_page=ceil(j/lp); if (check(chain1) !=1 && strlen(chain1) > 2 && isalpha(chain1[0])) { if(tab[tolower(chain1[0]) - 'a'] == NULL){ ptr =(mot *)malloc(sizeof(mot )); tab[tolower(chain1[0]) - 'a'] = ptr ; ptr->motindex=(char *)malloc(strlen(chain1)+1); strcpy(ptr->motindex,chain1); ptr->next=NULL; ptr->prempg=(page *)malloc(sizeof(page )); ptr->prempg->nbrocc=1; ptr->prempg->numpg=(int )num_page; ptr->prempg->next=NULL; ptr->derpg=(page *)malloc(sizeof(page)); ptr->derpg=ptr->prempg; } else { ptr = tab[tolower(chain1[0]) - 'a']; z = word(tab,chain1,(int )num_page); switch (z) { case 3 : ptrpg = ptr->prempg; ptr->prempg=(page *)malloc(sizeof(page)); ptr->prempg->nbrocc=1; ptr->prempg->numpg=(int )num_page; ptr->prempg->next = ptrpg; break ; case 2 : ptr = word2(tab[tolower(chain1[0]) - 'a'],chain1,(int )num_page); if (ptr==NULL){ printf("we have an error \n"); } ptr->derpg->nbrocc++; break ; case 1 : ptr = word2(tab[tolower(chain1[0]) - 'a'],chain1,( int )num_page); if (ptr == NULL) { printf("we have problem"); } ptrpg=(page *)malloc(sizeof(page )); ptr->derpg->next=ptrpg; ptr->derpg=ptrpg; ptrpg->next=NULL; ptrpg->nbrocc=1; ptrpg->numpg=(int )num_page; break ; case 0 : ptr1 = tab[tolower(chain1[0]) - 'a'] ; f=0; while(strcasecmp(chain1,ptr->motindex)>0){ f=1; ptr1 = ptr; ptr = ptr->next; if (ptr == NULL){ break; } } if (f==0){ ptr2 = (mot *)malloc(sizeof(mot )); tab[tolower(chain1[0]) - 'a'] =ptr2; ptr2->next=ptr1; ptr2->motindex=(char *)malloc(strlen(chain1)+1); strcpy(ptr2->motindex,chain1); ptr2->prempg=(page *)malloc(sizeof(page )); ptr2->prempg->nbrocc=1; ptr2->prempg->numpg=(int )num_page; ptr2->prempg->next=NULL; ptr2->derpg=ptr2->prempg; }else { ptr2 = (mot *)malloc(sizeof(mot )); ptr2->motindex=(char *)malloc(strlen(chain1)+1); strcpy(ptr2->motindex,chain1); ptr2->prempg=(page *)malloc(sizeof(page )); ptr2->prempg->nbrocc=1; ptr2->prempg->numpg=(int)num_page; ptr2->prempg->next=NULL; ptr2->derpg=(page *)malloc(sizeof(page)); ptr2->derpg=ptr2->prempg; ptr2->next=ptr1->next; ptr1->next=ptr2; } break ; default : printf("i guess we have a problem here \n"); break ; } } } ; }fclose(ft); } }remove("tmp.txt"); } }
int yylex(void) { int c; static char *buf = 0; static int bufsize = 500; if (buf == 0 && (buf = (char *) malloc(bufsize)) == NULL) FATAL( "out of space in yylex" ); if (sc) { sc = 0; RET('}'); } if (reg) { reg = 0; return regexpr(); } /* printf("top\n"); */ for (;;) { c = gettok(&buf, &bufsize); /* printf("gettok [%s]\n", buf); */ if (c == 0) return 0; if (isalpha(c) || c == '_') return word(buf); if (isdigit(c)) { yylval.cp = setsymtab(buf, tostring(buf), atof(buf), CON|NUM, symtab); /* should this also have STR set? */ RET(NUMBER); } yylval.i = c; switch (c) { case '\n': /* {EOL} */ RET(NL); case '\r': /* assume \n is coming */ case ' ': /* {WS}+ */ case '\t': break; case '#': /* #.* strip comments */ while ((c = input()) != '\n' && c != 0) ; unput(c); break; case ';': RET(';'); case '\\': if (peek() == '\n') { input(); } else if (peek() == '\r') { input(); input(); /* \n */ lineno++; } else { RET(c); } break; case '&': if (peek() == '&') { input(); RET(AND); } else RET('&'); case '|': if (peek() == '|') { input(); RET(BOR); } else RET('|'); case '!': if (peek() == '=') { input(); yylval.i = NE; RET(NE); } else if (peek() == '~') { input(); yylval.i = NOTMATCH; RET(MATCHOP); } else RET(NOT); case '~': yylval.i = MATCH; RET(MATCHOP); case '<': if (peek() == '=') { input(); yylval.i = LE; RET(LE); } else { yylval.i = LT; RET(LT); } case '=': if (peek() == '=') { input(); yylval.i = EQ; RET(EQ); } else { yylval.i = ASSIGN; RET(ASGNOP); } case '>': if (peek() == '=') { input(); yylval.i = GE; RET(GE); } else if (peek() == '>') { input(); yylval.i = APPEND; RET(APPEND); } else { yylval.i = GT; RET(GT); } case '+': if (peek() == '+') { input(); yylval.i = INCR; RET(INCR); } else if (peek() == '=') { input(); yylval.i = ADDEQ; RET(ASGNOP); } else RET('+'); case '-': if (peek() == '-') { input(); yylval.i = DECR; RET(DECR); } else if (peek() == '=') { input(); yylval.i = SUBEQ; RET(ASGNOP); } else RET('-'); case '*': if (peek() == '=') { /* *= */ input(); yylval.i = MULTEQ; RET(ASGNOP); } else if (peek() == '*') { /* ** or **= */ input(); /* eat 2nd * */ if (peek() == '=') { input(); yylval.i = POWEQ; RET(ASGNOP); } else { RET(POWER); } } else RET('*'); case '/': RET('/'); case '%': if (peek() == '=') { input(); yylval.i = MODEQ; RET(ASGNOP); } else RET('%'); case '^': if (peek() == '=') { input(); yylval.i = POWEQ; RET(ASGNOP); } else RET(POWER); case '$': /* BUG: awkward, if not wrong */ c = gettok(&buf, &bufsize); if (isalpha(c)) { if (strcmp(buf, "NF") == 0) { /* very special */ unputstr("(NF)"); RET(INDIRECT); } c = peek(); if (c == '(' || c == '[' || (infunc && isarg(buf) >= 0)) { unputstr(buf); RET(INDIRECT); } yylval.cp = setsymtab(buf, "", 0.0, STR|NUM, symtab); RET(IVAR); } else if (c == 0) { /* */ SYNTAX( "unexpected end of input after $" ); RET(';'); } else { unputstr(buf); RET(INDIRECT); } case '}': if (--bracecnt < 0) SYNTAX( "extra }" ); sc = 1; RET(';'); case ']': if (--brackcnt < 0) SYNTAX( "extra ]" ); RET(']'); case ')': if (--parencnt < 0) SYNTAX( "extra )" ); RET(')'); case '{': bracecnt++; RET('{'); case '[': brackcnt++; RET('['); case '(': parencnt++; RET('('); case '"': return string(); /* BUG: should be like tran.c ? */ default: RET(c); } } }
// la procedure ajout_mot comme son nom l'indique ajoute un mot donne // dans l'index void ajout_mot (mot **tableau,char chainn[50],int k){ mot *ptr,*ptr1,*ptr2; page *ptrpg; int z,f; if(tableau[tolower(chainn[0]) - 'a'] == NULL){ ptr =(mot *)malloc(sizeof(mot )); tableau[tolower(chainn[0]) - 'a'] = ptr ; ptr->motindex=(char *)malloc(strlen(chainn)+1); strcpy(ptr->motindex,chainn); ptr->next=NULL; ptr->prempg=(page *)malloc(sizeof(page )); ptr->prempg->nbrocc=1; ptr->prempg->numpg=k; ptr->prempg->next=NULL; ptr->derpg=(page *)malloc(sizeof(page)); ptr->derpg=ptr->prempg; } else { ptr = tableau[tolower(chainn[0]) - 'a'] ; z = word(tableau,chainn,k); printf("======================> Z :%d\n",z); switch (z) { case 3 : ptrpg = ptr->prempg; ptr->prempg=NULL; ptr->prempg=(page *)malloc(sizeof(page)); ptr->prempg->nbrocc=1; ptr->prempg->numpg=k; ptr->prempg->next = ptrpg; break ; case 2 : ptr = word2(tableau[tolower(chainn[0]) - 'a'],chainn,k); if (ptr==NULL){ printf("we have an error \n"); } ptr->derpg->nbrocc++; ptr->derpg->next=NULL; break ; case 1: ptr = word2(tableau[tolower(chainn[0]) - 'a'],chainn,k); if (ptr == NULL) { printf("we have problem"); } ptrpg=(page *)malloc(sizeof(page )); ptr->derpg->next=ptrpg; ptr->derpg=ptrpg; ptrpg->next=NULL; ptrpg->nbrocc=1; ptrpg->numpg=k; break ; case 0: ptr1 = tableau[tolower(chainn[0]) - 'a'] ; f=0; while(strcasecmp(chainn,ptr->motindex)>0){ f=1; ptr1 = ptr; ptr = ptr->next; if (ptr == NULL){ break; } } if (f==0){ ptr2 = (mot *)malloc(sizeof(mot )); tableau[tolower(chainn[0]) - 'a'] =ptr2; ptr2->next=ptr1; ptr2->motindex=(char *)malloc(strlen(chainn)+1); strcpy(ptr2->motindex,chainn); ptr2->prempg=(page *)malloc(sizeof(page )); ptr2->prempg->nbrocc=1; ptr2->prempg->numpg=k; ptr2->prempg->next=NULL; ptr2->derpg = (page * )malloc(sizeof(page)); ptr2->derpg=ptr2->prempg; }else { ptr2 = (mot *)malloc(sizeof(mot )); ptr2->motindex=(char *)malloc(strlen(chainn)+1); strcpy(ptr2->motindex,chainn); ptr2->prempg=(page *)malloc(sizeof(page )); ptr2->prempg->nbrocc=1; ptr2->prempg->numpg=k; ptr2->prempg->next=NULL; ptr2->derpg=(page *)malloc(sizeof(page)); ptr2->derpg=ptr2->prempg; ptr2->next=ptr1->next; ptr1->next=ptr2; } break ; } } }
/** * @brief * This method validates slave incoming messages * * @return 0 if OK, EXCEPTION if anything fails * @ingroup buffer */ uint8_t ModbusValidateRequest() { // check message crc vs calculated crc uint16_t u16MsgCRC = ((_au8Buffer[_u8BufferSize - 2] << 8) | _au8Buffer[_u8BufferSize - 1]); // combine the crc Low & High bytes if (ModbusCalcCRC(_u8BufferSize - 2) != u16MsgCRC) { _u16errCnt++; return NO_REPLY; } // check fct code bool isSupported = false; for (uint8_t i = 0; i< sizeof ( fctsupported); i++) { if (fctsupported[i] == _au8Buffer[FUNC]) { isSupported = 1; break; } } if (!isSupported) { _u16errCnt++; return EXC_FUNC_CODE; } // check start address & nb range uint16_t u16regs = 0; uint16_t u16count = 0; uint8_t u8regs; switch (_au8Buffer[ FUNC ]) { case MB_FC_READ_COILS: case MB_FC_READ_DISCRETE_INPUT: case MB_FC_WRITE_MULTIPLE_COILS: // Всего может быть до 16 адресов u16regs = word(_au8Buffer[ ADD_HI ], _au8Buffer[ ADD_LO ]); u16count = word(_au8Buffer[ NB_HI ], _au8Buffer[ NB_LO ]); if (u16count > 16) return EXC_REGS_QUANT; if (u16regs > 15 || u16regs + u16count > 16) return EXC_ADDR_RANGE; break; case MB_FC_WRITE_COIL: u16regs = word(_au8Buffer[ ADD_HI ], _au8Buffer[ ADD_LO ]); u8regs = _au8Buffer[ NB_HI ]; if (u8regs != 0x00 && u8regs != 0xFF) return EXC_REGS_QUANT; if (u16regs > 15) return EXC_ADDR_RANGE; break; case MB_FC_WRITE_REGISTER: u16regs = word(_au8Buffer[ ADD_HI ], _au8Buffer[ ADD_LO ]); u8regs = (uint8_t) u16regs; if (u8regs > _holdingRegsCount) return EXC_ADDR_RANGE; break; case MB_FC_READ_INPUT_REGISTER: // 4 u16regs = word(_au8Buffer[ ADD_HI ], _au8Buffer[ ADD_LO ]); u16regs += word(_au8Buffer[ NB_HI ], _au8Buffer[ NB_LO ]); u8regs = (uint8_t) u16regs; if (u8regs > _inputRegsCount) return EXC_ADDR_RANGE; break; case MB_FC_READ_REGISTERS: case MB_FC_WRITE_MULTIPLE_REGISTERS: u16regs = word(_au8Buffer[ ADD_HI ], _au8Buffer[ ADD_LO ]); u16regs += word(_au8Buffer[ NB_HI ], _au8Buffer[ NB_LO ]); u8regs = (uint8_t) u16regs; if (u8regs > _holdingRegsCount) return EXC_ADDR_RANGE; break; case MB_FC_REPORT_SLAVE_ID: break; // Read eeprom case MB_FC_READ_FILE_RECORD: { uint8_t res = CheckFunc20(); if(res != 0) return res; } break; // Write to EEPROM case MB_FC_WRITE_FILE_RECORD: if (_au8Buffer[ FILE_REF_TYPE ] != 6) return EXC_ADDR_RANGE; // Support only file # 0x0001 if (_au8Buffer[ FILE_NUM_HI ] != 0x00 || _au8Buffer[ FILE_NUM_LO ] != 0x01) return EXC_ADDR_RANGE; // Test for EEPROM range unsigned long startAddrBytes = ((_au8Buffer[ FILE_REC_HI ] << 8) | _au8Buffer[ FILE_REC_LO ]) << 1; unsigned long recLenBytes = ((_au8Buffer[ FILE_REC_LEN_HI ] << 8) | _au8Buffer[ FILE_REC_LEN_LO ]) << 1; if (startAddrBytes + recLenBytes >= _EEPROMSIZE) return EXC_ADDR_RANGE; break; case MB_FC_READ_DEVICE_ID: if(_au8Buffer[ MEI_TYPE ] != 0x0E) return EXC_FUNC_CODE; uint8_t readDevId = _au8Buffer[ MEI_READ_DEV_ID ]; if(readDevId != 0x01 && readDevId != 0x02 && readDevId != 0x04) return EXC_REGS_QUANT; if(readDevId == 0x04 && _au8Buffer[ MEI_OBJ_ID ] > 0x06) return EXC_ADDR_RANGE; break; case MB_FC_SYSTEM_COMMAND: if(_au8Buffer[COM_COM_ID] != MB_COMMAND_RESET && _au8Buffer[COM_COM_ID] != MB_COMMAND_SET_ADDRESS && _au8Buffer[COM_COM_ID] != MB_COMMAND_SET_TIME) return EXC_REGS_QUANT; break; case MB_FC_USER_COMMAND: break; case MB_FC_READ_DEVICE_STATUS: break; } _lastFunction = _au8Buffer[ FUNC ]; return 0; // OK, no exception code thrown }
/* * Read an ascii label in from FILE f, * in the same format as that put out by display(), * and fill in lp. */ int getasciilabel(FILE *f, struct disklabel *lp) { char **cpp, *cp; const char *errstr; struct partition *pp; char *mp, *tp, *s, line[BUFSIZ]; char **omountpoints = NULL; int lineno = 0, errors = 0; u_int32_t v, fsize; u_int64_t lv; unsigned int part; lp->d_version = 1; lp->d_bbsize = BBSIZE; /* XXX */ lp->d_sbsize = SBSIZE; /* XXX */ if (!(omountpoints = calloc(MAXPARTITIONS, sizeof(char *)))) errx(4, "out of memory"); mpcopy(omountpoints, mountpoints); for (part = 0; part < MAXPARTITIONS; part++) { free(mountpoints[part]); mountpoints[part] = NULL; } while (fgets(line, sizeof(line), f)) { lineno++; mp = NULL; if ((cp = strpbrk(line, "\r\n"))) *cp = '\0'; if ((cp = strpbrk(line, "#"))) { *cp = '\0'; mp = skip(cp+1); if (mp && *mp != '/') mp = NULL; } cp = skip(line); if (cp == NULL) continue; tp = strchr(cp, ':'); if (tp == NULL) { warnx("line %d: syntax error", lineno); errors++; continue; } *tp++ = '\0', tp = skip(tp); if (!strcmp(cp, "type")) { if (tp == NULL) tp = "unknown"; else if (strcasecmp(tp, "IDE") == 0) tp = "ESDI"; cpp = dktypenames; for (; cpp < &dktypenames[DKMAXTYPES]; cpp++) if ((s = *cpp) && !strcasecmp(s, tp)) { lp->d_type = cpp - dktypenames; goto next; } v = GETNUM(lp->d_type, tp, 0, &errstr); if (errstr || v >= DKMAXTYPES) warnx("line %d: warning, unknown disk type: %s", lineno, tp); lp->d_type = v; continue; } if (!strcmp(cp, "flags")) { for (v = 0; (cp = tp) && *cp != '\0';) { tp = word(cp); if (!strcmp(cp, "badsect")) v |= D_BADSECT; else if (!strcmp(cp, "vendor")) v |= D_VENDOR; else { warnx("line %d: bad flag: %s", lineno, cp); errors++; } } lp->d_flags = v; continue; } if (!strcmp(cp, "drivedata")) { int i; for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) { v = GETNUM(lp->d_drivedata[i], cp, 0, &errstr); if (errstr) warnx("line %d: bad drivedata %s", lineno, cp); lp->d_drivedata[i++] = v; tp = word(cp); } continue; } if (sscanf(cp, "%d partitions", &v) == 1) { if (v == 0 || v > MAXPARTITIONS) { warnx("line %d: bad # of partitions", lineno); lp->d_npartitions = MAXPARTITIONS; errors++; } else lp->d_npartitions = v; continue; } if (tp == NULL) tp = ""; if (!strcmp(cp, "disk")) { strncpy(lp->d_typename, tp, sizeof (lp->d_typename)); continue; } if (!strcmp(cp, "label")) { strncpy(lp->d_packname, tp, sizeof (lp->d_packname)); continue; } if (!strcmp(cp, "duid")) { if (duid_parse(lp, tp) != 0) { warnx("line %d: bad %s: %s", lineno, cp, tp); errors++; } continue; } if (!strcmp(cp, "bytes/sector")) { v = GETNUM(lp->d_secsize, tp, 1, &errstr); if (errstr || (v % 512) != 0) { warnx("line %d: bad %s: %s", lineno, cp, tp); errors++; } else lp->d_secsize = v; continue; } if (!strcmp(cp, "sectors/track")) { v = GETNUM(lp->d_nsectors, tp, 1, &errstr); if (errstr) { warnx("line %d: bad %s: %s", lineno, cp, tp); errors++; } else lp->d_nsectors = v; continue; } if (!strcmp(cp, "sectors/cylinder")) { v = GETNUM(lp->d_secpercyl, tp, 1, &errstr); if (errstr) { warnx("line %d: bad %s: %s", lineno, cp, tp); errors++; } else lp->d_secpercyl = v; continue; } if (!strcmp(cp, "tracks/cylinder")) { v = GETNUM(lp->d_ntracks, tp, 1, &errstr); if (errstr) { warnx("line %d: bad %s: %s", lineno, cp, tp); errors++; } else lp->d_ntracks = v; continue; } if (!strcmp(cp, "cylinders")) { v = GETNUM(lp->d_ncylinders, tp, 1, &errstr); if (errstr) { warnx("line %d: bad %s: %s", lineno, cp, tp); errors++; } else lp->d_ncylinders = v; continue; } /* Ignore fields that are no longer in the disklabel. */ if (!strcmp(cp, "rpm") || !strcmp(cp, "interleave") || !strcmp(cp, "trackskew") || !strcmp(cp, "cylinderskew") || !strcmp(cp, "headswitch") || !strcmp(cp, "track-to-track seek")) continue; /* Ignore fields that are forcibly set when label is read. */ if (!strcmp(cp, "total sectors") || !strcmp(cp, "boundstart") || !strcmp(cp, "boundend")) continue; if ('a' <= *cp && *cp <= 'z' && cp[1] == '\0') { unsigned int part = *cp - 'a'; if (part >= lp->d_npartitions) { if (part >= MAXPARTITIONS) { warnx("line %d: bad partition name: %s", lineno, cp); errors++; continue; } else { lp->d_npartitions = part + 1; } } pp = &lp->d_partitions[part]; #define NXTNUM(n, field, errstr) { \ if (tp == NULL) { \ warnx("line %d: too few fields", lineno); \ errors++; \ break; \ } else \ cp = tp, tp = word(cp), (n) = GETNUM(field, cp, 0, errstr); \ } NXTNUM(lv, lv, &errstr); if (errstr) { warnx("line %d: bad partition size: %s", lineno, cp); errors++; } else { DL_SETPSIZE(pp, lv); } NXTNUM(lv, lv, &errstr); if (errstr) { warnx("line %d: bad partition offset: %s", lineno, cp); errors++; } else { DL_SETPOFFSET(pp, lv); } if (tp == NULL) { pp->p_fstype = FS_UNUSED; goto gottype; } cp = tp, tp = word(cp); cpp = fstypenames; for (; cpp < &fstypenames[FSMAXTYPES]; cpp++) if ((s = *cpp) && !strcasecmp(s, cp)) { pp->p_fstype = cpp - fstypenames; goto gottype; } if (isdigit((unsigned char)*cp)) v = GETNUM(pp->p_fstype, cp, 0, &errstr); else v = FSMAXTYPES; if (errstr || v >= FSMAXTYPES) { warnx("line %d: warning, unknown filesystem type: %s", lineno, cp); v = FS_UNUSED; } pp->p_fstype = v; gottype: switch (pp->p_fstype) { case FS_UNUSED: /* XXX */ if (tp == NULL) /* ok to skip fsize/bsize */ break; NXTNUM(fsize, fsize, &errstr); if (fsize == 0) break; NXTNUM(v, v, &errstr); pp->p_fragblock = DISKLABELV1_FFS_FRAGBLOCK(fsize, v / fsize); break; case FS_BSDFFS: NXTNUM(fsize, fsize, &errstr); if (fsize == 0) break; NXTNUM(v, v, &errstr); pp->p_fragblock = DISKLABELV1_FFS_FRAGBLOCK(fsize, v / fsize); NXTNUM(pp->p_cpg, pp->p_cpg, &errstr); break; default: break; } if (mp) mountpoints[part] = strdup(mp); continue; } warnx("line %d: unknown field: %s", lineno, cp); errors++; next: ; } errors += checklabel(lp); if (errors > 0) mpcopy(mountpoints, omountpoints); mpfree(omountpoints); return (errors > 0); }
void emit_subprimitive(cell word_) { gc_root<word> word(word_,parent); gc_root<array> code_pair(word->subprimitive,parent); literals.append(parent->untag<array>(array_nth(code_pair.untagged(),0))); emit(array_nth(code_pair.untagged(),1)); }
/* * Read a partition line into partition `part' in the specified disklabel. * Return 0 on success, 1 on failure. */ static int getasciipartspec(char *tp, struct disklabel *lp, int part, int lineno) { struct partition *pp; char *cp, *endp; const char **cpp; u_long v; pp = &lp->d_partitions[part]; cp = NULL; v = 0; NXTWORD(part_size_type[part],v); if (v == 0 && part_size_type[part] != '*') { fprintf(stderr, "line %d: %s: bad partition size\n", lineno, cp); return (1); } pp->p_size = v; v = 0; NXTWORD(part_offset_type[part],v); if (v == 0 && part_offset_type[part] != '*' && part_offset_type[part] != '\0') { fprintf(stderr, "line %d: %s: bad partition offset\n", lineno, cp); return (1); } pp->p_offset = v; if (tp == NULL) { fprintf(stderr, "line %d: missing file system type\n", lineno); return (1); } cp = tp, tp = word(cp); for (cpp = fstypenames; cpp < &fstypenames[FSMAXTYPES]; cpp++) if (*cpp && !strcmp(*cpp, cp)) break; if (*cpp != NULL) { pp->p_fstype = cpp - fstypenames; } else { if (isdigit(*cp)) { errno = 0; v = strtoul(cp, &endp, 10); if (errno != 0 || *endp != '\0') v = FSMAXTYPES; } else v = FSMAXTYPES; if (v >= FSMAXTYPES) { fprintf(stderr, "line %d: Warning, unknown file system type %s\n", lineno, cp); v = FS_UNUSED; } pp->p_fstype = v; } switch (pp->p_fstype) { case FS_UNUSED: case FS_BSDFFS: case FS_BSDLFS: /* accept defaults for fsize/frag/cpg */ if (tp) { NXTNUM(pp->p_fsize); if (pp->p_fsize == 0) break; NXTNUM(v); pp->p_frag = v / pp->p_fsize; if (tp != NULL) NXTNUM(pp->p_cpg); } /* else default to 0's */ break; default: break; } return (0); }
typename Table::iterator Foam::basicThermo::lookupThermo ( const dictionary& thermoDict, Table* tablePtr ) { word thermoTypeName; if (thermoDict.isDict("thermoType")) { const dictionary& thermoTypeDict(thermoDict.subDict("thermoType")); Info<< "Selecting thermodynamics package " << thermoTypeDict << endl; const int nCmpt = 7; const char* cmptNames[nCmpt] = { "type", "mixture", "transport", "thermo", "equationOfState", "specie", "energy" }; // Construct the name of the thermo package from the components thermoTypeName = word(thermoTypeDict.lookup("type")) + '<' + word(thermoTypeDict.lookup("mixture")) + '<' + word(thermoTypeDict.lookup("transport")) + '<' + word(thermoTypeDict.lookup("thermo")) + '<' + word(thermoTypeDict.lookup("equationOfState")) + '<' + word(thermoTypeDict.lookup("specie")) + ">>," + word(thermoTypeDict.lookup("energy")) + ">>>"; // Lookup the thermo package typename Table::iterator cstrIter = tablePtr->find(thermoTypeName); // Print error message if package not found in the table if (cstrIter == tablePtr->end()) { FatalErrorInFunction << "Unknown " << Thermo::typeName << " type " << nl << "thermoType" << thermoTypeDict << nl << nl << "Valid " << Thermo::typeName << " types are:" << nl << nl; // Get the list of all the suitable thermo packages available wordList validThermoTypeNames ( tablePtr->sortedToc() ); // Build a table of the thermo packages constituent parts // Note: row-0 contains the names of constituent parts List<wordList> validThermoTypeNameCmpts ( validThermoTypeNames.size() + 1 ); validThermoTypeNameCmpts[0].setSize(nCmpt); forAll(validThermoTypeNameCmpts[0], j) { validThermoTypeNameCmpts[0][j] = cmptNames[j]; } // Split the thermo package names into their constituent parts forAll(validThermoTypeNames, i) { validThermoTypeNameCmpts[i+1] = Thermo::splitThermoName(validThermoTypeNames[i], nCmpt); } // Print the table of available packages // in terms of their constituent parts printTable(validThermoTypeNameCmpts, FatalError); FatalError<< exit(FatalError); }
GenSGSStress::GenSGSStress ( const volVectorField& U, const surfaceScalarField& phi, transportModel& transport ) : LESModel(word("GenSGSStress"), U, phi, transport), ce_ ( dimensioned<scalar>::lookupOrAddToDict ( "ce", coeffDict_, 1.048 ) ), couplingFactor_ ( dimensioned<scalar>::lookupOrAddToDict ( "couplingFactor", coeffDict_, 0.0 ) ), B_ ( IOobject ( "B", runTime_.timeName(), U_.db(), IOobject::MUST_READ, IOobject::AUTO_WRITE ), mesh_ ), nuSgs_ ( IOobject ( "nuSgs", runTime_.timeName(), U_.db(), IOobject::NO_READ, IOobject::NO_WRITE ), nu(), B_.boundaryField().types() ) { if (couplingFactor_.value() < 0.0 || couplingFactor_.value() > 1.0) { FatalErrorIn ( "GenSGSStress::GenSGSStress" "(const volVectorField& U, const surfaceScalarField& phi," "transportModel& lamTransportModel)" ) << "couplingFactor = " << couplingFactor_ << " is not in range 0 - 1" << nl << exit(FatalError); } }