Exemplo n.º 1
0
void StringUtil::removeComments(std::string& string) {
	int index = string.find("//");
	if (index == -1) return;
	int index2 = string.find("\r", index+1);
	int index3 = string.find("\n", index+1);
	if (index2 == -1) index2 = index3;
	else if (index3 != -1 && index3 < index2) index2 = index3;
	if (index2 == -1) {
		// Both index2 and index3 were -1, so there's no return in this line, the comment extends to the end.
		string = string.substr(0, index);
		removeComments(string);
		return;
	} else {
		// index2 is now the end of the comment.
		if (index2 == string.size()-1) {
			string = string.substr(0, index); // Return is at the end of the string
			removeComments(string);
			return;
		}
		std::string begin = string.substr(0, index);
		string = begin + string.substr(index2);
		removeComments(string);
		return;
	}

}
Exemplo n.º 2
0
/*
 * Goes through the buffer and adds the objects defined in there
 */
void getObjects(const char *buf,
                struct system *System,
                struct tip *Tip,
                struct space *Space,
                struct graphene *Graphene,
                struct substrate *Substrate)
{
	char *tmpBuf = NULL; // Temporary pointer for the buffer
	size_t strLen = strlen(buf);

	// Copy buffer to a temporary C-String
	tmpBuf = (char *) calloc(strLen + 1, sizeof(char));
	strncpy(tmpBuf, buf, strLen);
	tmpBuf[strLen] = '\0';

	// Remove comments and tokenize the whole string
	removeComments(tmpBuf);
	tmpBuf = strtok(tmpBuf, " \r\n");

	// Go through all token strings
	while (tmpBuf != NULL)
	{
		if (isalpha (*tmpBuf))
		{
			addObject(&tmpBuf, System, Tip, Space, Graphene, Substrate);
		}

		tmpBuf = strtok(NULL, " \r\n");
	}

	free(tmpBuf);
}
Exemplo n.º 3
0
void CommentsView::reloadComments()
{
    hideComments();
    removeComments();
    loadComments();
    showComments();
}
Exemplo n.º 4
0
const String& WebCLProgram::sourceWithCommentsStripped()
{
    if (m_programSourceWithCommentsStripped.isNull())
        removeComments(m_programSource, m_programSourceWithCommentsStripped);

    return m_programSourceWithCommentsStripped;
}
Exemplo n.º 5
0
int main(int argc, char **argv) {
    char buffer[1024];
    int continueloop = 0;
    char** commands;
    int state = 0; // 0 = sequential, 1 = parallel, 2 = exit    

    while(continueloop == 0){
        if (state == 0) printf("\nOperating in sequential mode\n");
        else if (state == 1) printf("\nOperating in parallel mode\n");
        printf("Type away>> ");
        fgets(buffer, 1024, stdin); 
        removeComments(buffer);
        commands = tokenify(buffer, ";");
        if (state == 0){
            state = seqParse(&commands);
        }
        else if (state == 1){
            state = parParse(&commands); 
        }
        if (state == 2){
            printf("Goodbye\n");
            freeTokens(commands);
            return 0;
        }
       freeTokens(commands);
    }
    return 0;
}
Exemplo n.º 6
0
CNpc::CNpc(CString& pImage, CString& pCode, float pX, float pY, CLevel* pLevel, bool levelNPC)
: x(pX), y(pY), hurtX(0), hurtY(0), level(pLevel), image(pImage),
levelNPC(levelNPC), clientCode(pCode),
rupees(0), darts(0), bombs(0), glovePower(0), blockFlags(0), bombPower(0),
power(0), sprite(2), shieldPower(0), swordPower(0),
visFlags(1)
{
	removeComments();
	weaponName = getFunctionParameter("toweapons ");
	if ( clientCode.length() < 20 )
	{
		if ( level->sparZone == false && clientCode.find("sparringzone") >= 0 )
			level->sparZone = true;
	}

	id = createNpcId(this);
	npcList.add(this);
	memset(saves, 0, sizeof(saves));
	memset(colors, 0, sizeof(colors));
	memset(modTime, 0, sizeof(modTime));
	gAni = "idle";
	for (int i = 0; i < 6; i++)
		imagePart.writeByte(32);

	modTime[NPCGIF] = getSysTime();
	modTime[ACTIONSCRIPT] = getSysTime();
	modTime[NPCX] = getSysTime();
	modTime[NPCY] = getSysTime();
	modTime[VISFLAGS] = getSysTime();
	modTime[NPCSPRITE] = getSysTime();
}
Exemplo n.º 7
0
void ReaderSTEP::loadModelFromString( std::string& content, shared_ptr<BuildingModel>& targetModel)
{
	progressTextCallback( L"Reading file..." );
	progressValueCallback( 0, "parse" );
	try
	{
		removeComments( content );
		readHeader( content, targetModel);
		readData( content, targetModel);
		targetModel->resolveInverseAttributes();
		targetModel->updateCache();

		// currently generated IFC classes are IFC4, files with older versions are converted. So after loading, the schema is always IFC4
		targetModel->getIfcSchemaVersion().m_IFC_FILE_SCHEMA = L"IFC4";
		targetModel->getIfcSchemaVersion().m_ifc_file_schema_enum = BuildingModel::IFC4;
	}
	catch( OutOfMemoryException& e)
	{
		throw e;
	}
	catch( BuildingException& e )
	{
		messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" );
	}
	catch( std::exception& e )
	{
		messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" );
	}
	catch( ... )
	{
		messageCallback( "An error occurred", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ );
	}
}
Exemplo n.º 8
0
int main(int argc, char* argv[])
{
    vector<string> fileContents;
    vector<Function> functions;

    if (argc > 1)
    {
        fileContents = readFile(argv[1]);
        if (fileContents.empty() == true)
        {
            cout << "Error opening file" << endl;
            return 0;
        }
    }
    else
    {
        //error: no file provided
        cout << "Must provide a c source file as an argument" << endl;
        return 0;
    }
    fileContents = removeComments(fileContents);
    functions = makeFunctions(fileContents);

    for (unsigned int i = 0; i < functions.size(); ++i)
    {
        stringstream temp;
        temp << "file" << i;
        functions.at(i).outputFile(temp.str());
    }
}
Exemplo n.º 9
0
/**
 * Removes all comments within file
 *
 * Clears whitespace down to just one space between
 * either a blank space or newline char
 *
 */
int cleanFile(char *in_file_name)
{
    FILE *f = fopen(in_file_name, "rb");
    fseek(f, 0, SEEK_END);
    long fsize = ftell(f);
    fseek(f, 0, SEEK_SET);
    
    char *string = malloc(fsize + 1);
    fread(string, fsize, 1, f);
    fclose(f);
    
    string[fsize] = 0;
    
    //stripExtraSpaces(string);
    
    int comments_removed;
    do
    {
        comments_removed = removeComments(string);
        if (comments_removed == -1)
        {
            return -1;
        }
        
    } while (comments_removed == 1);
    
    FILE *out = fopen(clean_input_name, "wb");
    fwrite(string, sizeof(char), strlen(string), out);
    fclose(out);
    free(string);
    
    return 0;
    
}
void SqliteTableModel::setQuery(const QString& sQuery, bool dontClearHeaders)
{
    // clear
    if(!dontClearHeaders)
        reset();

    if(!m_db->isOpen())
        return;

    m_sQuery = removeComments(sQuery).trimmed();

    // do a count query to get the full row count in a fast manner
    m_rowCount = getQueryRowCount();
    if(m_rowCount == -1)
    {
        m_valid = false;
        return;
    }

    // headers
    if(!dontClearHeaders)
    {
        m_headers.append(getColumns(sQuery));
    }

    // now fetch the first entries
    clearCache();
    fetchData(0, m_chunkSize);
    m_valid = true;

    emit layoutChanged();
}
Exemplo n.º 11
0
void IfcPPReaderSTEP::loadModelFromString( std::string& content, shared_ptr<IfcPPModel>& target_model )
{
	progressTextCallback( L"Reading file..." );
	progressValueCallback( 0, "parse" );
	try
	{
		removeComments( content );
		readStreamHeader( content, target_model );
		readStreamData( content, target_model );
		target_model->resolveInverseAttributes();
		target_model->updateCache();
	}
	catch( IfcPPOutOfMemoryException& e)
	{
		throw e;
	}
	catch( IfcPPException& e )
	{
		messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" );
	}
	catch( std::exception& e )
	{
		messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" );
	}
	catch( ... )
	{
		messageCallback( "An error occured", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ );
	}
}
Exemplo n.º 12
0
CNpc::CNpc(CString& pImage, CString& pCode, float pX, float pY, CLevel* pLevel)
{
	x = pX;
    y = pY;

    level = pLevel;
    hurtX = hurtY = 0;
    image = pImage;
    clientCode = pCode;
	removeComments();
	weaponName = getFunctionParameter("toweapons ");
	if(clientCode.length() < 20)
		level->sparZone = (clientCode.find("sparringzone") >= 0);

    id = createNpcId(this);
    npcList.add(this);
	memset(saves, 0, sizeof(saves));
	memset(colors, 0, sizeof(colors));
	memset(modTime, 0, sizeof(modTime));
	gAni = "idle";
	rupees = darts = bombs = glovePower = blockFlags = sprite = bombPower = power = 0;
	visFlags = 1;
	for(int i = 0; i < 6; i++)
		imagePart.writeByte(32);

    modTime[NPCGIF] = getTime();
	modTime[ACTIONSCRIPT] = getTime();
	modTime[NPCX] = getTime();
	modTime[NPCY] = getTime();
	modTime[VISFLAGS] = getTime();
}
Exemplo n.º 13
0
void CommentsView::reloadComments()
{
    qDebug() << "Reloading";
    hideComments();
    removeComments();
    loadComments();
    showComments();
}
void spherebot::set(QString intextfile)
{
    lineCounter = 0;
    textfile.clear();
    textfile.append(removeComments(intextfile));
    //qDebug()<<"The textfile String is: \n\n" + textfile + "\n\nENDE\n\n";
    lineMax = textfile.count("\n");
}
Exemplo n.º 15
0
AST* QueryParser::parse(std::string str,
                        AST* ast,
                        const int level)
{
    if(NULL == ast)
        ast = new AST();
 
    #ifdef DEBUG_PARSING_LEVELS
    if(level < 1)
        std::cout << "Parsing:" << std::endl << str;
    #endif
 
    if(str.size() < 2) return NULL;
    size_t beg = std::string::npos,
           end = std::string::npos;

	removeComments(str);
	str = StringUtils::trim(str);
    std::string header,
                body;
    
    header = StringUtils::extract(str,
                                  beg,
                                  end,
                                  HEADER_BEGIN,
                                  HEADER_END);
    if(header.size() < 2 || beg != 0)
    {
        SYNTAX_ERROR("No header in query", header);
        return NULL;
    }

    std::cout << "\nParsing header: " << header;
    Header* h = subParse(header, 1);
    Body* b = NULL;
    
    body = str.substr(end);
    
    if(body.size() < 2)
    {
        WARNING("Body is empty");
    }
    else
        b = subParse(body, 1);
    ASSERT(b != 0);  
    
    if(h != NULL)
    {
        ast->setHeader(h);
        ast->setBody(b);
    }
    else
        return NULL;

    return ast;

    
}
Exemplo n.º 16
0
void txThread::set(QString intextfile,serial &uibot)
{
    lineCounter = 0;
    textfile.clear();
    textfile.append(removeComments(intextfile));
    //qDebug()<<"The textfile String is: \n\n" + textfile + "\n\nENDE\n\n";
    lineMax = textfile.count("\n");
    serialConn = &uibot;
}
Exemplo n.º 17
0
/* main */
int main() {
    //setRandomSeed(1);
    std::ifstream inFile;
    promptUserForFile(inFile, "Input file: ");
    removeComments(inFile, std::cout);
    inFile.close();
    
    
    return 0;
}
Exemplo n.º 18
0
// Takes raw kif and process it
QStringList Parser::cleanRawKif(const QStringList &rawKif){
    QStringList answer;

    answer = splitLines(rawKif);
    answer = removeComments(answer);
    answer = makePureLines(answer);
    answer = createDoeses(answer);

    debugStringList(answer, "Clean KIF");

    return answer;
}
Exemplo n.º 19
0
/**
 * @brief xppParser::xppParser Default constructor of the parser object
 *
 * @param fn string representing the file name of the ode file
 *
 * This constructs the parser object of a given ode file. First unneeded
 * content is discarded, and a basic correctness check is don. Later arrays are
 * expanded and special constructs like markov processes and tables are handled.
 * Finally, the different keywords are parsed and put into the opts arrays.
 */
xppParser::xppParser(const std::string &fn)
    : fileName(fn)
{
    try {
        /* Initially read in the ode file */
        readFile();

        /* Initialize the keyword tries for command parsing */
        initializeTries();

        /* Check for incorrect brackets */
        checkBrackets();

        /* Remove all comments */
        removeComments();

        /* Remove unnecessary whitespaces */
        removeWhitespace();

        /* Expand array descriptions */
        expandArrays();

        /* Extract exports to dlls */
        extractExport();

        /* Extract markov processes */
        extractMarkov();

        /* Extract table definitions */
        extractTable();

        /* Extract wiener processes */
        extractWiener();

        /* Extract globals */
        extractGlobal();

        /* Extract all other definitions */
        extractDefinition();

        /* Catch errors */
    } catch (xppParserException& e) {
        std::cerr << e.what();
    } catch (std::runtime_error& e) {
        std::cerr << e.what();
    } catch (std::exception& e) {
        std::cerr << e.what();
    } catch (...) {
        std::cerr << "Unexpected error\n";
        throw;
    }
}
Exemplo n.º 20
0
Node *Document::getNode(QString name, QString defaultValue) {
    Node *node = new Node(defaultValue);

    for(int i = 0; i < lines.count(); i++) {
        if(!lines[i].isEmpty() && !lines[i].startsWith("#")) {
            QString line = lines[i].right(lines[i].size() - getLineRealStart(lines[i]));
            if(line.startsWith(name + ":")) {
                QString value = line.split(":")[1];
                value = value.right(value.size() - getLineRealStart(value));
                if(value.startsWith("{")) {
                    //Block !
                } else {
                    value = removeComments(value);
                    if(value.isEmpty() || value.startsWith("-")) {
                        //Array !
                        node->setType(NT_Array);
                        node->clearValueList();
                        if(value.startsWith("-")) {
                            QString firstArrayValue = value.right(value.size() - 1);
                            firstArrayValue = firstArrayValue.right(firstArrayValue.size() - getLineRealStart(firstArrayValue));
                            node->appendValue(firstArrayValue);
                        }
                    } else {
                        //Simple value...
                        node->setValue(value);
                        break;
                    }
                }
            } else if(node->getNodeType() == NT_Array && line.startsWith("-")) {
                //Adding value to array...
                QString value = removeComments(line.right(line.size() - 1));
                value = value.right(value.size() - getLineRealStart(value));
                node->appendValue(value);
            }
        }
    }

    return node;
}
Exemplo n.º 21
0
int main() {
	int len;

	extern char result[];

	if ((len = getlines()) > 0) {
		removeComments(len);
	}

	printf("\n%s\n%s\n", "Result:",result);

	return 0;

}
Exemplo n.º 22
0
void QFCompleterTextEditWidget::uncomment(){
    QTextCursor c(textCursor());
    if (c.selectionStart() == c.selectionEnd()) {
        c.select(QTextCursor::LineUnderCursor);
        c.insertText(removeComments(c.selectedText()));
        //setTextCursor(c);
    } else {
        // now we have to iterate through all selected blocks (lines) and indent them
        QTextCursor c1(c);
        c1.setPosition(c.selectionStart());
        QTextCursor c2(c);
        c2.setPosition(c.selectionEnd());
        c1.beginEditBlock();
        while (c1.blockNumber() <= c2.blockNumber()) {
            c1.select(QTextCursor::BlockUnderCursor);
            //std::cout<<"'"<<c1.selectedText().toLatin1().data()<<"'  =>  '"<<removeComments(c1.selectedText()).toLatin1().data()<<"'"<<std::endl;
            c1.insertText(removeComments(c1.selectedText()));
            if (!c1.movePosition(QTextCursor::NextBlock))
                break;
        }
        c1.endEditBlock();
        setTextCursor(c);
    }
}
Exemplo n.º 23
0
void SqliteTableModel::setQuery(const QString& sQuery, bool dontClearHeaders)
{
    // clear
    if(!dontClearHeaders)
    {
        m_mWhere.clear();
        m_headers.clear();
    }

    if(!m_db->isOpen())
        return;

    m_sQuery = removeComments(sQuery).trimmed();

    // do a count query to get the full row count in a fast manner
    m_rowCount = getQueryRowCount();
    if(m_rowCount == -1)
    {
        m_valid = false;
        return;
    }

    // headers
    if(!dontClearHeaders)
    {
        sqlite3_stmt* stmt;
        QByteArray utf8Query = sQuery.toUtf8();
        int status = sqlite3_prepare_v2(m_db->_db, utf8Query, utf8Query.size(), &stmt, NULL);
        if(SQLITE_OK == status)
        {
            status = sqlite3_step(stmt);
            int columns = sqlite3_data_count(stmt);
            for(int i = 0; i < columns; ++i)
                m_headers.append(QString::fromUtf8((const char*)sqlite3_column_name(stmt, i)));
        }
        sqlite3_finalize(stmt);
    }

    // now fetch the first entries
    clearCache();
    fetchData(0, m_chunkSize);
    m_valid = true;

    emit layoutChanged();
}
Exemplo n.º 24
0
std::istream& getline_fixed_recursive(std::istream& is, std::string& line, bool append)
{
    std::string s;
    if(std::getline(is, s)) {
        removeComments(s);
        trim(s);
        std::string sa = s.substr(0, s.find('\\'));
        if(append) {
            line.append(sa);
        } else {
            line = sa;
        }
        if(s.back() == '\\') {
            getline_fixed_recursive(is, line, true);
        }
    }
    return is;
}
Exemplo n.º 25
0
int main () {
	// Remove comments
	int removedComments = removeComments();
	
	// Identify operators
	printf("Operators:\n");
	int idetifiedOperators = identifyOperators();

	// Identify identifiers
	printf("\nIdentifiers:\n");
	int identifiedIdentifiers = identifyIdentifiers();

	// Identify keywords
	printf("\nKeywords:\n");
	int identifiedKeywords = identifyKeywords();

	return 0;
}
Exemplo n.º 26
0
void ConfigFileParser::parse() {
    std::ifstream file(configFilePath_.c_str());
    std::string line;
   
    while (! file. eof()) {
        getline(file, line);
        
        // First, remove the comment 
        removeComments(line);
        
        if (! line.empty()) {
            std::pair<std::string, std::string> result = (*lineProcessors_.begin())->processLine(line);
            if ( (! result.first.empty()) && (! result.second.empty()) ) {
                dictionary_.insert(result);
            }
        }
        
    }
    
    file.close();
}
void MainWindow::interpretGcode(QString code)       //for future gcode interpretation
{
    code = removeComments(code);
    QStringList lines = code.split("\n");
    QStringList line;
    int state = 0; // 0 = pen up , 1 = pen down
    for(int i = 0;i<lines.length();i++)
    {
        //qDebug()<<lines[i];
        line = lines[i].split(" ");
        if(lines[i].contains("M300 S" + QString::number(penUpAngle) +".00"))
            state = 0;
        else if(lines[i].contains("M300 S" + QString::number(penDownAngle) +".00"))
            state = 1;

        if(state == 1)//drawing
        {
            //to do (Gcode drawer widget)
        }
    }
}
void MainWindow::loadFile(const QString &fileName)
{
    qDebug()<<"loading file: "<<fileName;
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("Application"),
                             tr("Cannot read file %1:\n%2.")
                             .arg(fileName)
                             .arg(file.errorString()));
        return;
    }
    curFile = QFileInfo(fileName).absoluteFilePath();
    curDir = QFileInfo(fileName).absoluteDir();
    statusBar()->showMessage(tr("File loaded"), 2000);

    QString code = file.readAll();
    extractOptions(code);
    interpretGcode(code);
    refreshLayerNames(code);
    ui->fileTextEdit->setText(code);
    qDebug()<<removeComments(code);

    scene->clear();
    QString picPath = QFileInfo(fileName).absoluteFilePath();
    picPath.chop(5);        //cut .gcode
    picPath.append("svg");
    QGraphicsSvgItem *item = new QGraphicsSvgItem(picPath);
    scene->addItem(item);
    ui->graphicsView->setEnabled(true);
    ui->graphicsView->fitInView(item);

    if(!ui->fileTextEdit->toPlainText().isEmpty())
    {
        setWindowTitle("Spherebot Control      File: " + fileName);
        ui->fileName->setText(QFileInfo(fileName).fileName());
    }
    else ui->sendButton->setEnabled(false);
}
Exemplo n.º 29
0
/*
 *parseAnalyzeMdfFile function
 *
 *file : a pointer to file MDF file descriptor
 *
 *this function will take a MDF file descriptor and return
 *a pointer to a MDF struct represinting the information in the file
 */
struct MDF *parseAnalyzeMdfFile(FILE *file)
{
  int max_nol;
  char **arr;
  char **arr2;
  char **arr3;
  struct MDF *res;

  max_nol = numberOfLines(file);
  rewind(file);
  arr = getArrayOfLines(file, max_nol, 1000);
  fclose(file);

  arr2 = removeComments(arr, max_nol, 1000);
  freeCharArray(arr, max_nol);
  arr3 = removeEmptyLines(arr2, max_nol, 1000);
  freeCharArray(arr2, max_nol);

  res = createMDF(arr3);
  freeCharArray(arr3, max_nol);

  return res;
}
Exemplo n.º 30
0
bool DTD::parseDTD(const KURL &url)
{
 QString fileName = QString::null;
 if (!KIO::NetAccess::download(url, fileName))
 {
   KMessageBox::error(0, i18n("<qt>Cannot download the DTD from <b>%1</b>.</qt>").arg(url.prettyURL(0, KURL::StripFileProtocol)));
   return false;
 }
  QFile file(fileName);
  if (file.open(IO_ReadOnly))
  {
    QTextStream fileStream(&file);
    fileStream.setEncoding(QTextStream::UnicodeUTF8);
    QString entireDTD = fileStream.read();
    file.close();
    removeComments(entireDTD);

    QString line;
    QStringList lines = QStringList::split("\n",entireDTD);
    QStringList::Iterator it = lines.begin();
    while (it != lines.end()) {
      line = *it;

      if (line.startsWith("<")) {
        while (!line.endsWith(">") && it != lines.end()) {
          ++it;
          line += " \\end" + *it;
        }
      } else if (line.startsWith("%")) {
        while (!line.endsWith(";") && it != lines.end()) {
          ++it;
          line += *it;
        }
      }

      line = line.stripWhiteSpace();
      line = line.simplifyWhiteSpace();

      //kdDebug(24000) << "Parsed line is: " << line << endl;

      if ( line.startsWith("<!ENTITY") && line.endsWith(">"))
      {
        parseDTDEntity(line);
      }
      else
      if (line.startsWith("<!ELEMENT") && line.endsWith(">"))
      {
        parseDTDElement(line);
      }
      else
      if (line.startsWith("<!ATTLIST") && line.endsWith(">"))
      {
        parseDTDAttlist(line);
      }
      else
      if (line.startsWith("%") && line.endsWith(";"))
      {
        line.remove(0,1);
        line.truncate(line.length()-1);
        KURL entityURL = url;
        entityURL.setPath(url.directory()+ "/" + line + ".ent");
        parseDTD(entityURL);
      } else
      {
        kdDebug(24000) << QString("Unknown tag: [%1]").arg(line) << endl;
      }

      if (it != lines.end()) ++it;
    }
  }
}