Esempio n. 1
0
      dimension_size_type
      ifdIndex(const SeriesIFDRange& seriesIFDRange,
               dimension_size_type   series,
               dimension_size_type   plane)
      {
        if (series >= seriesIFDRange.size())
          {
            boost::format fmt("Invalid series number ‘%1%’");
            fmt % series;
            throw FormatException(fmt.str());
          }
        const IFDRange& range(seriesIFDRange.at(series));

        // Compute timepoint and subchannel from plane number.
        dimension_size_type ifdidx = range.begin + plane;
        assert(range.begin <= plane && plane < range.end);

        if (plane >= (range.end - range.begin))
          {
            boost::format fmt("Invalid plane number ‘%1%’ for series ‘%2%’");
            fmt % plane % series;
            throw FormatException(fmt.str());
          }

        return ifdidx;
      }
Esempio n. 2
0
void Parser::parseBct(const std::string &cmd)
{
    glm::vec2 pos;
    std::string tmp = cmd;
    std::list<int> recourse;
    size_t rank = cmd.find_first_of(' ');
    
    if (rank == std::string::npos)
        throw FormatException();
    pos.x = getNbFromString(cmd);
    pos.y = getNbFromString(cmd.substr(rank + 1));
    tmp = cmd.substr(rank + 1);
    for (int i = 0; i != 7; ++i) {
        if ((rank = tmp.find_first_of(' ')) == std::string::npos)
            throw FormatException();
        tmp = tmp.substr(rank + 1);
        recourse.push_back(getNbFromString(tmp));
    }
    for (Map::const_iterator it = _map->begin(), end = _map->end();  it != end; ++it) {
        if ((*it)->getPosition().x == pos.x && (*it)->getPosition().y == pos.y) {
            (*it)->setRecourse(recourse);
            return ;
        }
    }
    _map->push_back(new Ground(pos, *_gem, *_food));
    _map->back()->setRecourse(recourse);
    
}
Esempio n. 3
0
Compositor::Ptr CompositorLoader::ParseCompositor(ResourceManager& resourceManager, const json::Value& root)
{
	Compositor::Ptr result(new Compositor());

	if (root["renderTargets"].GetType() != ObjectVal)
	{
		throw FormatException("renderTargets must be an object");
	}

	json::Object renderTargets = root["renderTargets"].ToObject();

	ParseRenderTargets(result, renderTargets);

	const Value& stages = root["stages"];

	if (stages.GetType() != ArrayVal)
	{
		throw FormatException("stages must be an array");
	}

	Array arrayStages = stages.ToArray();

	for (auto it = arrayStages.begin(); it != arrayStages.end(); ++it)
	{
		ParseStage(resourceManager, result, *it);
	}

	return result;
}
Esempio n. 4
0
/********************************************************************************
* LongNumber
* public methods
*********************************************************************************/
LongNumber::LongNumber(char const* strnum) : container(0)
{
    bool hasSign = false;
    bool isStatic = true;
    while (*strnum == ' ')
        strnum++;
    if (*strnum == '+')
        strnum++;
    else if (*strnum == '-')
    {
        strnum++;
        hasSign = true;
    }
    char const* iter = strnum;
    long long curVal = 0;
    int curLength = 0;
    while (*iter != 0)
    {
        curLength++;
        if (isStatic)
        {
            if (*iter < '0' || *iter > '9')
                throw FormatException("Wrong character");
            char digit = *iter - '0';
            if (!checkMult(curVal, 10, curVal))
                isStatic = false;
            else if (!checkAdd(curVal, digit, curVal))
                isStatic = false;
        }
        iter++;
    }
    container = NumberContainer(isStatic, curLength);
    container.setSign(hasSign);
    if (isStatic)
        container.setValue(curVal);
    else
    {
        int position = 0;
        iter--;
        while (iter != strnum)
        {
            if (*iter < '0' || *iter > '9')
            {
                container.~NumberContainer();
                throw FormatException("Wrong character");
            }
            container.setDigit(position, *iter - '0');
            position++;
            iter--;
        }
        container.setDigit(position, *iter - '0');
    }
}
    bool QXmlFeatureReader::readHeader(FeatureHeader& hdr)
    {
        QFile file(m_filename.c_str());
        if (!file.open(QIODevice::ReadOnly | QFile::Text))
        {
            throw FormatException(qPrintable(file.errorString()));
        }

        QTextStream in(&file);
        in.setCodec("UTF-8");

        QString line;
        QRegExp rxType("<type>(\\w+)</type>");
        QRegExp rxFrameLength("<frameLength>(\\d+)</frameLength>");
        QRegExp rxParamsPerFrame("<paramsPerFrame>(\\d+)</paramsPerFrame>");
        QRegExp rxEndHeader("</header>");
        do
        {
            line = in.readLine();
            if (rxType.indexIn(line) != -1)
                hdr.type = rxType.cap(1).toStdString();
            if (rxFrameLength.indexIn(line) != -1)
                hdr.frameLength = rxFrameLength.cap(1).toUInt();
            if (rxParamsPerFrame.indexIn(line) != -1)
                hdr.paramsPerFrame = rxParamsPerFrame.cap(1).toUInt();

            if (rxEndHeader.indexIn(line) != -1)
                break;
        }
        while (!line.isNull());
        file.close();

        return true;
    }
Esempio n. 6
0
	uint8_t Message::readByte(const char** source, const char* bound)
	{
		if (*source < bound)
			return *((*source)++);

		throw FormatException();
	}
Esempio n. 7
0
	void FFmpegAudioDecoder::Initialize()
	{
		AVFormatContext* format = decoder->GetFormatContext();
		for (streamIndex = 0; streamIndex < format->nb_streams; streamIndex++) {
			stream = format->streams[streamIndex];
			if (!stream)
				continue;
			if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO)
				break;
		}

		if (streamIndex >= format->nb_streams)
			BRICKS_FEATURE_THROW(FormatException());

		codec = decoder->OpenStream(streamIndex);

		channels = stream->codec->channels;
		samplerate = stream->codec->sample_rate;
		if (stream->duration < 0)
			samples = INT64_MAX;
		else
			samples = stream->time_base.num * stream->duration * samplerate / stream->time_base.den;

		bufferSize = 129000;
		buffer = av_malloc(bufferSize);

		cache = av_malloc(bufferSize);
		cacheLength = 0;

		// TODO: Handle stream->codec->sample_fmt
	}
Esempio n. 8
0
EdgeSampling::Type SamplerLoader::ParseEdgeSampling(const std::string& value)
{
	if (value == "repeat")
	{
		return EdgeSampling::Repeat;
	}
	else if (value == "mirror")
	{
		return EdgeSampling::Mirror;
	}
	else if (value == "clamp")
	{
		return EdgeSampling::Clamp;
	}
	else if (value == "border")
	{
		return EdgeSampling::Border;
	}
	else if (value == "mirrorOnce")
	{
		return EdgeSampling::MirrorOnce;
	}
	else
	{
		throw FormatException("edge sampling mode must be repeat, mirror, clamp, border, mirrorOnce");
	}
}
Esempio n. 9
0
void CompositorLoader::ParseStage(ResourceManager& resourceManager, Compositor::Ptr& compositor, const json::Value& stageJson)
{
	if (stageJson.HasKey("disabled") && stageJson["disabled"].ToBool(false))
	{
		return;
	}

	if (!stageJson.HasKey("stage") || stageJson["stage"].GetType() != StringVal)
	{
		throw FormatException("stages[].stage needs to be a string containing the relvative path to a CompositeStage");
	}

	CompositeStageConnections connections;

	ParseStageConnections(connections, stageJson);

	std::string stageFilename = stageJson["stage"].ToString();
	CompositeStage::Ptr stage = resourceManager.LoadResource<CompositeStage>(stageFilename);

	if (stageJson.HasKey("shaderValues"))
	{
		Array defaultValues = stageJson["shaderValues"].ToArray();

		for (auto it = defaultValues.begin(); it != defaultValues.end(); ++it)
		{
			JsonTypeHelper::ParseValueIntoParameters(stage->GetStateParameters(), *it);
		}
	}

	compositor->AddCompositeStage(stage, connections);
}
Esempio n. 10
0
Auto<Resource> CompositorLoader::LoadResource(ResourceManager& resourceManager, std::istream& inputStream, const std::string& internalName)
{
	if (!JsonDocumentLoader::IsJsonDocument(inputStream))
	{
		throw FormatException("Compositor must be a json document");
	}

	Value documentRoot = JsonDocumentLoader::LoadJson(inputStream);

	if (documentRoot["documentType"].ToString("") != "compositor")
	{
		throw FormatException("documentType not marked as a compositor");
	}

	return ParseCompositor(resourceManager, documentRoot);
}
Esempio n. 11
0
	std::wstring Message::readUTF8(const char** source, const char* bound)
	{
		unsigned len = readShort(source, bound);
		const char *bytes = *source;
		if (bytes + len - 1 < bound)
		{
			(*source) += len;
			std::wstring ret;
			try {
				utf8::utf8to16(bytes, bytes + len, std::back_inserter(ret));
			} catch (const utf8::exception&) { throw FormatException("Bad UTF-8"); }
				
			return ret;
		}

		throw FormatException();
	}
Esempio n. 12
0
    bool QXmlFeatureReader::read(FeatureHeader& hdr,
        Extractor::featureArrayType& featureArray)
    {
        QFile file(m_filename.c_str());
        if (!file.open(QIODevice::ReadOnly | QFile::Text))
        {
            throw FormatException(qPrintable(file.errorString()));
        }

        ptrHdr = &hdr;
        ptrFeatureArray = &featureArray;
        reader.setDevice(&file);
        reader.readNext();
        while (!reader.atEnd())
        {
            if (reader.isStartElement())
            {
                if (reader.name() == "featureFile")
                {
                    readFeatureFileElement();
                }
                else
                {
                    reader.raiseError(QObject::tr("Not a feature file!"));
                }
            }
            else
            {
                reader.readNext();
            }
        }

        file.close();
        if (reader.hasError())
        {
            QString msg = QObject::tr("Parse error at line %1: %2").
                arg(reader.lineNumber()).
                arg(reader.errorString());
            throw FormatException(msg.toStdString());
        }

        return true;
    }
Esempio n. 13
0
	std::string Message::readString(const char** source, const char* bound)
	{
		unsigned len = readShort(source, bound);
		const char *bytes = *source;
		if (bytes + len - 1 < bound)
		{
			(*source) += len;
			return std::string(bytes, len);
		}

		throw FormatException();
	}
Esempio n. 14
0
void Parser::parseCmd(const std::string &cmd)
{
    size_t pos = cmd.find_first_of(' ');
    
    try {
        if (pos == std::string::npos)
            throw FormatException();
        if (!cmd.size())
            return ;
        std::string tmp = cmd.substr(0, pos);
        if (_parse.find(tmp) != _parse.end()) {
            if ((pos = cmd.find_first_of(' ')) == std::string::npos)
                throw FormatException();
            (this->*_parse[tmp])(cmd.substr(pos + 1));
        }
    }
    catch (std::exception &e) {
        if (cmd != "BIENVENUE")
            std::cerr << e.what() << std::endl;
        return ;
    }
}
void Erosion::Arguments(const QHash<QString, QString> &args, int& shape, int& ksize)
{
	bool ok = false;
	QHash<QString, QString>::const_iterator it;

	if ((it = args.find("Value")) != args.end()) {
		ksize = it.value().toInt(&ok);

		if (!ok) {
			throw FormatException("couldn't convert \"Value\" argument for erosion");
		} else if (ksize < 0) {
			throw ArgumentException("\"Value\" argument for erosion must be positive");
		}
		ksize = 2 * (ksize-1) + 1;
	}

	if ((it = args.find("Shape")) != args.end()) {
		if (it.value() == "Rect") {
			shape = cv::MORPH_RECT;
		} else if (it.value() == "Cross") {
			shape = cv::MORPH_CROSS;
		} else if (it.value() == "Ellipse") {
			shape = cv::MORPH_ELLIPSE;
		} else {
			throw ArgumentException("\"Shape\" doesn't name an existing type");
		}
	}

	if ((it = args.find("KernelSize")) != args.end()) {
		ksize = it.value().toInt(&ok);

		if (!ok) {
			throw FormatException("couldn't convert \"KernelSize\" argument for dilation effect");
		} else if (ksize < 0) {
			throw ArgumentException("\"KernelSize\" argument for dilation effect must be positive");
		}
		ksize = 2 * (ksize-1) + 1;
	}
}
Esempio n. 16
0
InterpolationMode::Type SamplerLoader::ParseInterpolatioMode(const std::string& value)
{
	if (value == "point")
	{
		return InterpolationMode::Point;
	}
	else if (value == "linear")
	{
		return InterpolationMode::Linear;
	}
	else
	{
		throw FormatException("interpolation mode must be point or linear");
	}
}
Esempio n. 17
0
SamplingMode::Type SamplerLoader::ParseSamplingMode(const std::string& value)
{
	if (value == "basic")
	{
		return SamplingMode::Basic;
	}
	else if (value == "compare")
	{
		return SamplingMode::Compare;
	}
	else
	{
		throw FormatException("sampling mode must be basic or compare");
	}
}
cv::Mat QImageToMat(const QImage& img)
{
	int format = ConvertQformat(img.format());

	switch (format) {
	case CV_8UC4:
		return ConvertMat4(img);
	case CV_8UC3:
		return ConvertMat3(img);
	case CV_8UC1:
		return ConvertMat1(img);
	default:
		throw FormatException("can't convert this pixel format");
	}
}
Esempio n. 19
0
	uint32_t Message::readLong(const char** source, const char* bound)
	{
		const char *bytes = *source;
		if (bytes + 3 < bound)
		{
			union {
				uint8_t bytes[4];
				uint32_t value;
			} ret;
			(*source) += 4;
			ret.bytes[0] = *bytes++; ret.bytes[1] = *bytes++; ret.bytes[2] = *bytes++; ret.bytes[3] = *bytes;
			return ntohl(ret.value);
		}

		throw FormatException();
	}
Esempio n. 20
0
	uint16_t Message::readShort(const char** source, const char* bound)
	{
		const char *bytes = *source;
		if (bytes + 1 < bound)
		{
			union {
				uint8_t bytes[2];
				uint16_t value;
			} ret;
			(*source) += 2;
			ret.bytes[0] = *bytes++; ret.bytes[1] = *bytes;
 			return ntohs(ret.value);
		}

		throw FormatException();
	}
QImage MatToQImage(const cv::Mat& mat)
{
	QImage::Format format = ConvertCvFormat(mat.type());

	switch (format) {
	case QImage::Format_ARGB32:
	case QImage::Format_RGB32:
		return ConvertQ4(mat);
	case QImage::Format_RGB888:
		return ConvertQ3(mat);
	case QImage::Format_Indexed8:
		return ConvertQ1(mat);
	default:
		throw FormatException("can't convert this pixel format");
	}
}
void Sobel::Arguments(const QHash<QString, QString> &args, int& ksize)
{
	bool ok = false;
	QHash<QString,QString>::const_iterator it;

	if ((it = args.find("Value")) != args.end()) {
		ksize = it.value().toInt(&ok);

		if (!ok) {
			throw FormatException("couldn't convert \"Value\" argument for sobel");
		} else if (ksize < 0) {
			throw ArgumentException("\"Value\" argument for sobel must be positive");
		}
		ksize = (2 * (ksize-1) + 1);
		ksize = ksize > 31 ? 31 : ksize;
	}
}
Esempio n. 23
0
      void
      MinimalTIFFReader::initFile(const boost::filesystem::path& id)
      {
        ::ome::bioformats::detail::FormatReader::initFile(id);

        tiff = TIFF::open(id, "r");

        if (!tiff)
          {
            boost::format fmt("Failed to open ‘%1%’");
            fmt % id.string();
            throw FormatException(fmt.str());
          }

        readIFDs();

        fillMetadata(*getMetadataStore(), *this);
      }
Esempio n. 24
0
      void
      MinimalTIFFReader::getLookupTable(dimension_size_type plane,
                                        VariantPixelBuffer& buf) const
      {
        assertId(currentId, true);

        const ome::compat::shared_ptr<const IFD>& ifd(ifdAtIndex(plane));

        try
          {
            ifd->readLookupTable(buf);
          }
        catch (const std::exception& e)
          {
            boost::format fmt("Failed to get lookup table:");
            fmt % e.what();
            throw FormatException(fmt.str());
          }
      }
Esempio n. 25
0
void	Rotate::Process( uint32_t inStartOffset,
										uint32_t inEndOffset )
{
	if (inEndOffset != inStartOffset + 8)
	{
		throw DataLengthException( Name(), inStartOffset, inEndOffset, 8 );
	}

	uint32_t axisEnum = FetchUInt32( inStartOffset );
	
	if (axisEnum > 2)
	{
		throw FormatException( Name(), inStartOffset );
	}
	
	float radians = FetchFloat32( inStartOffset+4 );
	
	Out() << Indent() << Name() << " ( " <<
		axisName[ axisEnum ] << " " << radians << " )\n";
}
Esempio n. 26
0
    void Deserialize(
        InputStreamFormatter<utf8>& formatter,
        IEntityInterface& interf,
        DocumentTypeId docType)
    {
        auto docId = interf.CreateDocument(docType, nullptr);

            // Parse the input file, and send the result to the given entity interface
            // we expect only a list of entities in the root (no attributes)
        using Blob = InputStreamFormatter<utf8>::Blob;
        for (;;) {
            switch (formatter.PeekNext()) {
            case Blob::BeginElement:
                DeserializeEntity(formatter, interf, docId);
                break;

            case Blob::None: return; // end of file

            default:
                Throw(FormatException("Unexpected blob while deserializing entities", formatter.GetLocation()));
            }
        }
    }
Esempio n. 27
0
void Parser::parseMsz(const std::string &cmd)
{
    glm::vec2 pos;
    size_t rank = cmd.find_first_of(' ');
    
    if (rank == std::string::npos) {
        _map->setSize(glm::vec2(1, 1));
        throw FormatException();
    }
    pos.x = getNbFromString(cmd);
    pos.y = getNbFromString(cmd.substr(rank + 1));
    _map->setSize(pos);
    if (_map->size()) {
        for (Map::iterator it = _map->begin(); it != _map->end();) {
            it = _map->erase(it);
        }
        for (Map::Players::iterator it = _map->playerBegin(); it != _map->playerEnd();) {
            it = _map->removePlayer(it);
        }
        for (Map::Eggs::iterator it = _map->eggBegin(); it != _map->eggEnd();) {
            it = _map->removeEgg(it);
        }
    }
}
Esempio n. 28
0
      void
      MinimalTIFFWriter::saveBytes(dimension_size_type plane,
                                   VariantPixelBuffer& buf,
                                   dimension_size_type x,
                                   dimension_size_type y,
                                   dimension_size_type w,
                                   dimension_size_type h)
      {
        assertId(currentId, true);

        setPlane(plane);

        dimension_size_type expectedIndex =
          tiff::ifdIndex(seriesIFDRange, getSeries(), plane);

        if (ifdIndex != expectedIndex)
          {
            boost::format fmt("IFD index mismatch: actual is %1% but %2% expected");
            fmt % ifdIndex % expectedIndex;
            throw FormatException(fmt.str());
          }

        ifd->writeImage(buf, x, y, w, h);
      }
Esempio n. 29
0
void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
{
    std::string message = FormatException(pex, pszThread);
    LogPrintf("\n\n************************\n%s\n", message);
    fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
}
Esempio n. 30
0
static void fillExceptionDlg( HWND hwnd, ExceptDlgInfo *info ) {

    char                buf[BUF_SIZE];
    char                fname[ FNAME_BUFLEN ];
    DWORD               line;
    ProcStats           stats;
    HWND                ctl;
    address             addr;

    GetCurrAddr(&addr,info->regs);
    SetDlgCourierFont( hwnd, INT_TASK_NAME );
    SetDlgCourierFont( hwnd, INT_TASK_PATH );
    SetDlgCourierFont( hwnd, INT_FAULT_TYPE );
    SetDlgCourierFont( hwnd, INT_CS_IP );
    SetDlgCourierFont( hwnd, INT_SOURCE_INFO );
    SetDlgCourierFont( hwnd, INT_SOURCE_INFO2 );

    RCsprintf( buf, STR_EXCEPTION_ENCOUNTERED, AppName );
    SetWindowText( hwnd, buf );

    CopyRCString( STR_PROCESS_NAME, buf, BUF_SIZE );
    SetDlgItemText( hwnd, INT_TASK_NAME_TEXT, buf );

    if( !info->dbinfo->u.Exception.dwFirstChance ) {
        if( ConfigData.exception_action == INT_CHAIN_TO_NEXT ) {
            ConfigData.exception_action = INT_TERMINATE;
        }
        ctl = GetDlgItem( hwnd, INT_CHAIN_TO_NEXT );
        EnableWindow( ctl, FALSE );
    }
    CheckDlgButton( hwnd, ConfigData.exception_action, BST_CHECKED );
    CopyRCString( STR_PROCESS_ID, buf, BUF_SIZE );
    SetDlgItemText( hwnd, INT_TASK_PATH_TEXT, buf );

    while( !GetProcessInfo( info->procinfo->procid, &stats ) ) {
        Sleep( 100 );
        RefreshInfo();
    }
    SetDlgItemText( hwnd, INT_TASK_NAME, stats.name );

    sprintf( buf, "%08lX", info->procinfo->procid );
    SetDlgItemText( hwnd, INT_TASK_PATH, buf );

    FormatException( buf, info->dbinfo->u.Exception.ExceptionRecord.ExceptionCode );
    SetDlgItemText( hwnd, INT_FAULT_TYPE, buf );

    if( info->threadinfo != NULL ) {
        strcpy( buf, "Fault " );
        MADRegSpecialName( MSR_IP, info->regs, MAF_FULL, BUF_SIZE - 7, buf+6 );
        SetDlgItemText( hwnd, INT_IP_NAME, buf );
        SetIp( hwnd, &addr );
    }
    if( info->got_dbginfo && GetLineNum( &addr,fname, FNAME_BUFLEN, &line ) ) {
        RCsprintf( buf, STR_LINE_X_OF, line );
        SetDlgItemText( hwnd, INT_SOURCE_INFO, buf );
        SetDlgItemText( hwnd, INT_SOURCE_INFO2, fname );
    } else {
        CopyRCString( STR_N_A, buf, BUF_SIZE );
        SetDlgItemText( hwnd, INT_SOURCE_INFO, buf );
        SetDlgItemText( hwnd, INT_SOURCE_INFO2, "" );
    }
}