Пример #1
0
/*!
 *  pixReadIndexed()
 *
 *      Input:  sarray (of full pathnames)
 *              index (into pathname array)
 *      Return: pix if OK; null if not found
 *
 *  Notes:
 *      (1) This function is useful for selecting image files from a
 *          directory, where the integer @index is embedded into
 *          the file name.
 *      (2) This is typically done by generating the sarray using
 *          getNumberedPathnamesInDirectory(), so that the @index
 *          pathname would have the number @index in it.  The size
 *          of the sarray should be the largest number (plus 1) appearing
 *          in the file names, respecting the constraints in the
 *          call to getNumberedPathnamesInDirectory().
 *      (3) Consequently, for some indices into the sarray, there may
 *          be no pathnames in the directory containing that number.
 *          By convention, we place empty C strings ("") in those
 *          locations in the sarray, and it is not an error if such
 *          a string is encountered and no pix is returned.
 *          Therefore, the caller must verify that a pix is returned.
 *      (4) See convertSegmentedPagesToPS() in src/psio1.c for an
 *          example of usage.
 */
PIX *
pixReadIndexed(SARRAY  *sa,
               l_int32  index)
{
    char    *fname;
    l_int32  n;
    PIX     *pix;

    PROCNAME("pixReadIndexed");

    if (!sa)
        return (PIX *)ERROR_PTR("sa not defined", procName, NULL);
    n = sarrayGetCount(sa);
    if (index < 0 || index >= n)
        return (PIX *)ERROR_PTR("index out of bounds", procName, NULL);

    fname = sarrayGetString(sa, index, L_NOCOPY);
    if (fname[0] == '\0')
        return NULL;

    if ((pix = pixRead(fname)) == NULL) {
        L_ERROR("pix not read from file %s\n", procName, fname);
        return NULL;
    }

    return pix;
}
Пример #2
0
/*!
 *  pixReadMemJp2k()
 *
 *      Input:  data (const; jpeg-encoded)
 *              size (of data)
 *              reduction (scaling factor: 1, 2, 4, 8)
 *              box  (<optional> for extracting a subregion), can be null
 *              hint (a bitwise OR of L_JP2K_* values; 0 for default)
 *              debug (output callback messages, etc)
 *      Return: pix, or null on error
 *
 *  Notes:
 *      (1) This crashes when reading through the fmemopen cookie.
 *          Until we can fix this, we use the file-based work-around.
 *          And fixing this may take some time, because the basic
 *          stream interface is no longer supported in openjpeg.
 *      (2) See pixReadJp2k() for usage.
 */
PIX *
pixReadMemJp2k(const l_uint8  *data,
               size_t          size,
               l_uint32        reduction,
               BOX            *box,
               l_int32         hint,
               l_int32         debug)
{
FILE     *fp;
PIX      *pix;

    PROCNAME("pixReadMemJp2k");

    if (!data)
        return (PIX *)ERROR_PTR("data not defined", procName, NULL);

#if 0  /* Avoid the crash for now */
    if ((fp = fmemopen((void *)data, size, "r")) == NULL)
        return (PIX *)ERROR_PTR("stream not opened", procName, NULL);
#else
    L_WARNING("work-around: writing to a temp file\n", procName);
    if ((fp = tmpfile()) == NULL)
        return (PIX *)ERROR_PTR("tmpfile stream not opened", procName, NULL);
    fwrite(data, 1, size, fp);
    rewind(fp);
#endif  /* HAVE_FMEMOPEN */
    pix = pixReadStreamJp2k(fp, reduction, box, hint, debug);
    fclose(fp);
    if (!pix) L_ERROR("pix not read\n", procName);
    return pix;
}
Пример #3
0
/*!
 *  pixReadRGBAPng()
 *
 *      Input:  filename (of png file)
 *      Return: pix, or null on error
 *
 *  Notes:
 *      (1) Wrapper to keep the alpha channel of a png, if it exists.
 *      (2) The default behavior of pix read functions is to ignore
 *          the alpha channel.
 *      (3) This always leaves alpha stripping in the same mode as
 *          when this function begins.  So if alpha stripping is in
 *          default mode, this disables it, reads the file (including
 *          the alpha channel), and resets back to stripping.  Otherwise,
 *          it leaves stripping disabled.
 */
PIX *
pixReadRGBAPng(const char  *filename)
{
l_int32  format;
PIX     *pix;

    PROCNAME("pixReadRGBAPng");

    if (!filename)
        return (PIX *)ERROR_PTR("filename not defined", procName, NULL);

        /* Make sure it's a png file */
    findFileFormat(filename, &format);
    if (format != IFF_PNG) {
        L_ERROR_STRING("file format is %s, not png", procName,
                       ImageFileFormatExtensions[format]);
        return NULL;
    }

        /* If alpha channel reading is enabled, just read it */
    if (var_PNG_STRIP_ALPHA == FALSE)
        return pixRead(filename);

    l_pngSetStripAlpha(0);
    pix = pixRead(filename);
    l_pngSetStripAlpha(1);  /* reset to default */
    if (!pix) L_ERROR("pix not read", procName);
    return pix;
}
Пример #4
0
/*!
 *  recogaReadStream()
 *
 *      Input:  stream
 *      Return: recog, or null on error
 */
L_RECOGA *
recogaReadStream(FILE  *fp)
{
l_int32    version, i, nrec, ignore;
L_RECOG   *recog;
L_RECOGA  *recoga;

    PROCNAME("recogaReadStream");

    if (!fp)
        return (L_RECOGA *)ERROR_PTR("stream not defined", procName, NULL);

    if (fscanf(fp, "\nRecoga Version %d\n", &version) != 1)
        return (L_RECOGA *)ERROR_PTR("not a recog file", procName, NULL);
    if (version != RECOG_VERSION_NUMBER)
        return (L_RECOGA *)ERROR_PTR("invalid recog version", procName, NULL);
    if (fscanf(fp, "Number of recognizers = %d\n\n", &nrec) != 1)
        return (L_RECOGA *)ERROR_PTR("nrec not read", procName, NULL);

    recoga = recogaCreate(nrec);
    for (i = 0; i < nrec; i++) {
        ignore = fscanf(fp, "==============================\n");
        if (fscanf(fp, "Recognizer %d\n", &ignore) != 1)
            return (L_RECOGA *)ERROR_PTR("malformed file", procName, NULL);
        if ((recog = recogReadStream(fp)) == NULL) {
            recogaDestroy(&recoga);
            L_ERROR("recog read failed for recog %d\n", procName, i);
            return NULL;
        }
        ignore = fscanf(fp, "\n");
        recogaAddRecog(recoga, recog);
    }
    return recoga;
}
Пример #5
0
/**
 * Creates a new instance of the DataAccess class. Only one static connection
 * is made to the database in each program using this class, which is shared by
 * all instances. It is important to abort or commit transactions when they are
 * finished with to prevent database deadlock.
 */
DataAccess::DataAccess() {
    const char* routine = "DataAccess::DataAccess";

	// For each instance increment counter. We can only close the connection
	// when the last instance is destroyed.
    DataAccess::instanceCount++;

	// If this is the first instance create the connection to database
    if (DataAccess::instanceCount == 1) {
        try {
			// Create connection
			C = new PqxxConnection( getConnectionString() );
            L_INFO(LOG_DB,"Connected to database " + std::string(C->dbname()));
            L_INFO(LOG_DB," -> Backend version: " 
                            + dps_itoa(C->server_version()));
            L_INFO(LOG_DB," -> Protocal version: " 
                            + dps_itoa(C->protocol_version()));
			// Init the transaction mutex
            t_routine_mutex = new pthread_mutex_t;
            pthread_mutex_init(t_routine_mutex,NULL);
			W = 0;
        }
        catch (const std::exception &e) {
            L_ERROR(LOG_DB,"Exception: " + std::string(e.what()));
            throw;
        }
        catch (...) {
			// Whoops! We can't connect to the DB
            L_CRITICAL(LOG_DB,"An unexpected error occured");
            throw;
        }
    }
}
Пример #6
0
/*!
 * \brief   pixReadMemJpeg()
 *
 * \param[in]    data const; jpeg-encoded
 * \param[in]    size of data
 * \param[in]    cmflag colormap flag 0 means return RGB image if color;
 *                      1 means create a colormap and return
 *                      an 8 bpp colormapped image if color
 * \param[in]    reduction scaling factor: 1, 2, 4 or 8
 * \param[out]   pnwarn [optional] number of warnings
 * \param[in]    hint a bitwise OR of L_JPEG_* values; 0 for default
 * \return  pix, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) The %size byte of %data must be a null character.
 *      (2) The only hint flag so far is L_JPEG_READ_LUMINANCE,
 *          given in the enum in imageio.h.
 *      (3) See pixReadJpeg() for usage.
 * </pre>
 */
PIX *
pixReadMemJpeg(const l_uint8  *data,
               size_t          size,
               l_int32         cmflag,
               l_int32         reduction,
               l_int32        *pnwarn,
               l_int32         hint)
{
l_int32   ret;
l_uint8  *comment;
FILE     *fp;
PIX      *pix;

    PROCNAME("pixReadMemJpeg");

    if (pnwarn) *pnwarn = 0;
    if (!data)
        return (PIX *)ERROR_PTR("data not defined", procName, NULL);

    if ((fp = fopenReadFromMemory(data, size)) == NULL)
        return (PIX *)ERROR_PTR("stream not opened", procName, NULL);
    pix = pixReadStreamJpeg(fp, cmflag, reduction, pnwarn, hint);
    if (pix) {
        ret = fgetJpegComment(fp, &comment);
        if (!ret && comment) {
            pixSetText(pix, (char *)comment);
            LEPT_FREE(comment);
        }
    }
    fclose(fp);
    if (!pix) L_ERROR("pix not read\n", procName);
    return pix;
}
Пример #7
0
/*!
 *  kernelNormalize()
 *
 *      Input:  kels (source kel, to be normalized)
 *              normsum (desired sum of elements in keld)
 *      Return: keld (normalized version of kels), or null on error
 *                   or if sum of elements is very close to 0)
 *
 *  Notes:
 *      (1) If the sum of kernel elements is close to 0, do not
 *          try to calculate the normalized kernel.  Instead,
 *          return a copy of the input kernel, with an error message.
 */
L_KERNEL *
kernelNormalize(L_KERNEL  *kels,
                l_float32  normsum)
{
l_int32    i, j, sx, sy, cx, cy;
l_float32  sum, factor;
L_KERNEL  *keld;

    PROCNAME("kernelNormalize");

    if (!kels)
        return (L_KERNEL *)ERROR_PTR("kels not defined", procName, NULL);

    kernelGetSum(kels, &sum);
    if (L_ABS(sum) < 0.01) {
        L_ERROR("null sum; not normalizing; returning a copy", procName);
        return kernelCopy(kels);
    }

    kernelGetParameters(kels, &sy, &sx, &cy, &cx);
    if ((keld = kernelCreate(sy, sx)) == NULL)
        return (L_KERNEL *)ERROR_PTR("keld not made", procName, NULL);
    keld->cy = cy;
    keld->cx = cx;

    factor = normsum / sum;
    for (i = 0; i < sy; i++)
        for (j = 0; j < sx; j++)
            keld->data[i][j] = factor * kels->data[i][j];

    return keld;
}
Пример #8
0
static node *uncle(node *n) {
    if (!n || !n->parent || !n->parent->parent) {
        L_ERROR("root and child of root have no uncle\n", "uncle");
        return NULL;
    }
    return sibling(n->parent);
}
Пример #9
0
/*!
 * \brief   pixReadStreamGif()
 *
 * \param[in]    fp file stream
 * \return  pix, or NULL on error
 */
PIX *
pixReadStreamGif(FILE  *fp)
{
l_int32          fd;
GifFileType     *gif;

    PROCNAME("pixReadStreamGif");

#if GIFLIB_MAJOR == 5 && GIFLIB_MINOR == 1 && GIFLIB_RELEASE == 2  /* 5.1.2 */
    L_ERROR("Can't use giflib-5.1.2; suggest 5.1.1 or earlier\n", procName);
    return NULL;
#endif  /* 5.1.2 */

    if ((fd = fileno(fp)) < 0)
        return (PIX *)ERROR_PTR("invalid file descriptor", procName, NULL);
#ifdef _WIN32
    fd = _dup(fd);
#endif /* _WIN32 */

#ifndef _MSC_VER
    lseek(fd, 0, SEEK_SET);
#else
    _lseek(fd, 0, SEEK_SET);
#endif  /* _MSC_VER */

    if ((gif = DGifOpenFileHandle(fd, NULL)) == NULL)
        return (PIX *)ERROR_PTR("invalid file or file not found",
                                procName, NULL);

    return gifToPix(gif);
}
Пример #10
0
void Task::init()
{
  L_FUNC("");

  L_INFO("+++ test Logger");
  L_FATAL("L_FATAL");
  L_ERROR("L_ERROR");
  L_WARN("L_WARN");
  L_INFO("L_INFO");
  L_DEBUG("L_DEBUG");
  L_INFO("--- test Logger");

  L_INFO(QString()); // --> "?"
  L_INFO(" \n Trimmed \n\n"); // --> whitespace removed from start and end
  L_INFO("UTF-8 Unicode text: äöü àéè");

  QString formattedOutput1 = "JSON output 1:\n"
    "{\n"
    "  \"firstName\": \"Mario\",\n"
    "  \"age\": 44\n"
    "}"
  ;
  L_INFO(formattedOutput1);

  QString formattedOutput2 = "{<br>  \"firstName\": \"Mario\",<br>  \"age\": 44<br>}";
  L_INFO(formattedOutput2.prepend("JSON output 2:<br>").replace("<br>", "\n"));

  QTimer::singleShot(1000, this, SLOT(slotRun()));
  QTimer::singleShot(1000, this, SLOT(slotRun()));
  QTimer::singleShot(3000, this, SLOT(slotRun()));
  QTimer::singleShot(6000, this, SLOT(theEnd()));
}
Пример #11
0
/* ------------------------------------------------------------- *
 *                  Static red-black tree helpers                *
 * ------------------------------------------------------------- */
static node *grandparent(node *n) {
    if (!n || !n->parent || !n->parent->parent) {
        L_ERROR("root and child of root have no grandparent\n", "grandparent");
        return NULL;
    }
    return n->parent->parent;
}
Пример #12
0
/** copies data from the head of the queue into passed buffer.
 *
 * if data from the head of the queue copied successfully
 * removes head of the queue. \n
 * if head of the queue was not removed successfully
 * logs warning.
 *
 * @param _root root node of the queue
 * @param _data buffer in which head's data would be copied
 * @param _size passed buffer size
 *
 * @return #true if successfully poped \n
 *			#false otherwise
 *
 *	@see d_list_get_head
 *	@see d_list_remove_head
 */
bool d_queue_pop(QUEUE_ROOT* _root, void* _data, size_t _size)
{
/* #ifdef _DEBUG */
/* 	L_DEBUG( "0x%08x\n", _root ); */
/* #endif */
	
	if ( !_root )
	{
		L_ERROR( "_root == NULL\n", "" );

		return false;
	}

	if ( d_list_get_head((LIST_ROOT*)_root, _data, _size) )
	{
		if ( !d_list_remove_head((LIST_ROOT*)_root) )
		{
			// pointer moved anyway
			// just let developers know that here is memleaks
			L_WARN( "unable to remove QUEUE_HEAD\n", "" );
		}

		return true;
	}

	return false;
}
Пример #13
0
/*!
 *  recogStringToIndex()
 *
 *      Input:  recog
 *              text (text string for some class)
 *              &index (<return> index for that class; -1 if not found)
 *      Return: 0 if OK, 1 on error (not finding the string is an error)
 */
l_int32
recogStringToIndex(L_RECOG  *recog,
                   char     *text,
                   l_int32  *pindex)
{
char    *charstr;
l_int32  i, n, diff;

    PROCNAME("recogStringtoIndex");

    if (!pindex)
        return ERROR_INT("&index not defined", procName, 1);
    *pindex = -1;
    if (!recog)
        return ERROR_INT("recog not defined", procName, 1);
    if (!text)
        return ERROR_INT("text not defined", procName, 1);

        /* Search existing characters */
    n = recog->setsize;
    for (i = 0; i < n; i++) {
        recogGetClassString(recog, i, &charstr);
        if (!charstr) {
            L_ERROR("string not found for index %d\n", procName, i);
            continue;
        }
        diff = strcmp(text, charstr);
        FREE(charstr);
        if (diff) continue;
        *pindex = i;
        return 0;
    }

    return 1;  /* not found */
}
Пример #14
0
/** deinitializes #LIST_ROOT.
 *
 * removes all nodes in the list (by calling #d_list_remove_head)
 * and zeroes passed pointer to the #LIST_ROOT
 *
 * logs warning if #d_list_remove_head was not successfully done
 *
 * @param _root pointer to the root node
 *
 * @return currently #true in case of non-null pointer \n
 *			#false otherwise
 */
bool d_list_deinit(LIST_ROOT* _root)
{
/* #ifdef _DEBUG */
/* 	L_DEBUG( "0x%08x\n", _root ); */
/* #endif */
	
	if ( !_root )
	{
		L_ERROR( "_root == NULL\n", "" );

		return false;
	}

	bool clr = true;
	while ( _root->count )
	{
		clr &= d_list_remove_head( _root );
	}

	if ( !clr )
	{
		L_WARN( "memleaks are possible\n", "" );
	}

	memset( _root, 0, sizeof(_root) );

	return true;
}
Пример #15
0
/*!
 *  boxaEncapsulateAligned()
 *
 *      Input:  boxa
 *              num (number put into each boxa in the baa)
 *              copyflag  (L_COPY or L_CLONE)
 *      Return: boxaa, or null on error
 *
 *  Notes:
 *      (1) This puts @num boxes from the input @boxa into each of a
 *          set of boxa within an output boxaa.
 *      (2) This assumes that the boxes in @boxa are in sets of @num each.
 */
BOXAA *
boxaEncapsulateAligned(BOXA    *boxa,
                       l_int32  num,
                       l_int32  copyflag)
{
l_int32  i, j, n, nbaa, index;
BOX     *box;
BOXA    *boxat;
BOXAA   *baa;

    PROCNAME("boxaEncapsulateAligned");

    if (!boxa)
        return (BOXAA *)ERROR_PTR("boxa not defined", procName, NULL);
    if (copyflag != L_COPY && copyflag != L_CLONE)
        return (BOXAA *)ERROR_PTR("invalid copyflag", procName, NULL);

    n = boxaGetCount(boxa);
    nbaa = (n + num - 1) / num;
    if (n / num != nbaa)
        L_ERROR("inconsistent alignment: n / num not an integer", procName);
    baa = boxaaCreate(nbaa);
    for (i = 0, index = 0; i < nbaa; i++) {
        boxat = boxaCreate(num);
        for (j = 0; j < num; j++, index++) {
            box = boxaGetBox(boxa, index, copyflag);
            boxaAddBox(boxat, box, L_INSERT);
        }
        boxaaAddBoxa(baa, boxat, L_INSERT);
    }

    return baa;
}
Пример #16
0
/*!
 *  recogaDestroy()
 *
 *      Input:  &recoga (<will be set to null before returning>)
 *      Return: void
 *
 *  Notes:
 *      (1) If a recog has a parent, the parent owns it.  To destroy
 *          a recog, it must first be "orphaned".
 */
void
recogaDestroy(L_RECOGA  **precoga)
{
l_int32    i;
L_RECOG   *recog;
L_RECOGA  *recoga;

    PROCNAME("recogaDestroy");

    if (precoga == NULL) {
        L_WARNING("ptr address is null!\n", procName);
        return;
    }

    if ((recoga = *precoga) == NULL)
        return;

    rchaDestroy(&recoga->rcha);
    for (i = 0; i < recoga->n; i++) {
        if ((recog = recoga->recog[i]) == NULL) {
            L_ERROR("recog not found for index %d\n", procName, i);
            continue;
        }
        recog->parent = NULL;  /* orphan it */
        recogDestroy(&recog);
    }
    LEPT_FREE(recoga->recog);
    LEPT_FREE(recoga);
    *precoga = NULL;
    return;
}
Пример #17
0
/*!
 *  dewarpaRestoreModels()
 *
 *      Input:  dewa (populated with dewarp structs for pages)
 *      Return: 0 if OK, 1 on error
 *
 *  Notes:
 *      (1) This puts all real models (and only real models) in the
 *          primary dewarp array.  First remove all dewarps that are
 *          only references to other page models.  Then move all models
 *          that had been cached back into the primary dewarp array.
 *      (2) After this is done, we still need to recompute and insert
 *          the reference models before dewa->modelsready is true.
 */
l_int32
dewarpaRestoreModels(L_DEWARPA  *dewa)
{
l_int32    i;
L_DEWARP  *dew;

    PROCNAME("dewarpaRestoreModels");

    if (!dewa)
        return ERROR_INT("dewa not defined", procName, 1);

        /* Strip out ref models.  Then only real models will be in the
         * primary dewarp array. */
    dewarpaStripRefModels(dewa);

        /* The cache holds only real models, which are not necessarily valid. */
    for (i = 0; i <= dewa->maxpage; i++) {
        if ((dew = dewa->dewarpcache[i]) != NULL) {
            if (dewa->dewarp[i]) {
                L_ERROR("dew in both cache and main array!: page %d\n",
                        procName, i);
            } else {
                dewa->dewarp[i] = dew;
                dewa->dewarpcache[i] = NULL;
            }
        }
    }
    dewa->modelsready = 0;  /* new ref models not yet inserted */

        /* Regenerate the page lists */
    dewarpaListPages(dewa);
    return 0;
}
Пример #18
0
/*
 *  pushNewPixel()
 *
 *      Input:  lqueue
 *              x, y   (pixel coordinates)
 *              &minx, &maxx, &miny, &maxy  (<return> bounding box update)
 *      Return: void
 *
 *  Notes:
 *      (1) This is a wrapper for adding a NewPixel to a queue, which
 *          updates the bounding box for all pixels on that queue and
 *          uses the storage stack to retrieve a NewPixel.
 */
static void
pushNewPixel(L_QUEUE  *lq,
             l_int32   x,
             l_int32   y,
             l_int32  *pminx,
             l_int32  *pmaxx,
             l_int32  *pminy,
             l_int32  *pmaxy)
{
L_NEWPIXEL  *np;

    PROCNAME("pushNewPixel");

    if (!lq) {
        L_ERROR("queue not defined\n", procName);
        return;
    }

        /* Adjust bounding box */
    *pminx = L_MIN(*pminx, x);
    *pmaxx = L_MAX(*pmaxx, x);
    *pminy = L_MIN(*pminy, y);
    *pmaxy = L_MAX(*pmaxy, y);

        /* Get a newpixel to use */
    if (lstackGetCount(lq->stack) > 0)
        np = (L_NEWPIXEL *)lstackRemove(lq->stack);
    else
        np = (L_NEWPIXEL *)CALLOC(1, sizeof(L_NEWPIXEL));

    np->x = x;
    np->y = y;
    lqueueAdd(lq, np);
    return;
}
Пример #19
0
/**
 * Aborts any changes to the database in the last transaction and unlocks the
 * transaction lock.
 */
void DataAccess::abort(std::string name) {
    const char* routine = "DataAccess::abort";
    
    // Lock routine mutex
    pthread_mutex_lock(t_routine_mutex);

    // If we abort a different transaction, we must be stupid
    if (transActive && transName != name) {
        pthread_mutex_unlock(t_routine_mutex);
        L_ERROR(LOG_DB,"Attempted to abort the wrong transaction!");
		L_ERROR(LOG_DB,"Tried to abort " + name + " while " + transName
			+ " is still active.");
        return;
    }
	
    // We're kind, so we'll let it pass if someone tries to abort a transaction
	// which doesn't exist.
    if (!W) {
        pthread_mutex_unlock(t_routine_mutex);
        return;
    }

	// Try to abort the transaction
    try {
		L_INFO(LOG_DB,"Aborting transaction '" + transName + "'");
	    W->abort();
	}
    catch (const std::exception &e) {
        pthread_mutex_unlock(t_routine_mutex);
        L_ERROR(LOG_DB,"Exception: " + std::string(e.what()));
        throw -1;
    }
    catch (...) {
        pthread_mutex_unlock(t_routine_mutex);
        L_CRITICAL(LOG_DB,"Unexpected exception.");
        throw -1;
    }

	// Delete Work and set pointer to null
    delete W;
    W = 0;
    transActive = false;
    transName = "";

    // Unlock routine mutex
    pthread_mutex_unlock(t_routine_mutex);
}
Пример #20
0
void GLThreadCheck::check() {
    try {
        GL_thread->do_check();
    } catch(WrongThreadError& e) {
        L_ERROR("Tried to call OpenGL dependent code from the wrong thread");
        throw;
    }
}
Пример #21
0
/*
 *  l_rbtreePrint()
 *
 *      Input:  stream
 *              t (rbtree)
 *      Return: null
 */
void
l_rbtreePrint(FILE      *fp,
              L_RBTREE  *t)
{
    PROCNAME("l_rbtreePrint");
    if (!fp) {
        L_ERROR("stream not defined\n", procName);
        return;
    }
    if (!t) {
        L_ERROR("tree not defined\n", procName);
        return;
    }

    print_tree_helper(fp, t->root, t->keytype, 0);
    fprintf(fp, "\n");
}
Пример #22
0
/**
 * Commits any changes to the database in the last transaction and unlocks the
 * transaction lock.
 */
void DataAccess::commit(std::string name) {
    const char* routine = "DataAccess::commit";
    
	// Lock routine mutex
    pthread_mutex_lock(t_routine_mutex);
	
    // If we commit a different transaction, we must be stupid
    if (transActive && transName != name) {
        L_ERROR(LOG_DB,"Attempted to commit the wrong transaction!");
		L_ERROR(LOG_DB,"Tried to commit " + name + " while " + transName
			+ " is still active.");
		pthread_mutex_unlock(t_routine_mutex);
        return;
    }
    
	// We shouldn't try to commit when we've not done anything. Stupid.
    if (!W) {
		pthread_mutex_unlock(t_routine_mutex);
		throw -1;
	}

	// Try to commit the transaction
	try {	
	    L_INFO(LOG_DB,"Committing transaction '" + transName + "'");
	    W->commit();
	}
    catch (const std::exception &e) {
        pthread_mutex_unlock(t_routine_mutex);
        L_ERROR(LOG_DB,"Exception: " + std::string(e.what()));
        throw -1;
    }
    catch (...) {
        pthread_mutex_unlock(t_routine_mutex);
        L_CRITICAL(LOG_DB,"Unexpected exception.");
        throw -1;
    }

	// Clean up Work and set pointer null
	delete W;
	W = 0;
    transActive = false;
    transName = "";

    // Unlock routine mutex
    pthread_mutex_unlock(t_routine_mutex);
}
Пример #23
0
static void verify_property_1(node *n) {
    if (node_color(n) != L_RED_NODE && node_color(n) != L_BLACK_NODE) {
        L_ERROR("color neither RED nor BLACK\n", "verify_property_1");
        return;
    }
    if (n == NULL) return;
    verify_property_1(n->left);
    verify_property_1(n->right);
}
Пример #24
0
/*!
 * \brief   pixCountConnComp()
 *
 * \param[in]    pixs 1 bpp
 * \param[in]    connectivity 4 or 8
 * \param[out]   pcount
 * \return  0 if OK, 1 on error
 *
 * Notes:
 *     (1 This is the top-level call for getting the number of
 *         4- or 8-connected components in a 1 bpp image.
 *     2 It works on a copy of the input pix.  The c.c. are located
 *         in raster order and erased one at a time.
 */
l_int32
pixCountConnComp(PIX      *pixs,
                 l_int32   connectivity,
                 l_int32  *pcount)
{
    l_int32   h, iszero;
    l_int32   x, y, xstart, ystart;
    PIX      *pixt;
    L_STACK  *stack, *auxstack;

    PROCNAME("pixCountConnComp");

    if (!pcount)
        return ERROR_INT("&count not defined", procName, 1);
    *pcount = 0;  /* initialize the count to 0 */
    if (!pixs || pixGetDepth(pixs) != 1)
        return ERROR_INT("pixs not defined or not 1 bpp", procName, 1);
    if (connectivity != 4 && connectivity != 8)
        return ERROR_INT("connectivity not 4 or 8", procName, 1);

    pixt = NULL;
    stack = NULL;

    pixZero(pixs, &iszero);
    if (iszero)
        return 0;

    if ((pixt = pixCopy(NULL, pixs)) == NULL)
        return ERROR_INT("pixt not made", procName, 1);

    h = pixGetHeight(pixs);
    if ((stack = lstackCreate(h)) == NULL) {
        L_ERROR("stack not made\n", procName);
        goto cleanup;
    }
    auxstack = lstackCreate(0);
    stack->auxstack = auxstack;

    xstart = 0;
    ystart = 0;
    while (1) {
        if (!nextOnPixelInRaster(pixt, xstart, ystart, &x, &y))
            break;

        pixSeedfill(pixt, stack, x, y, connectivity);
        (*pcount)++;
        xstart = x;
        ystart = y;
    }

    /* Cleanup, freeing the fillsegs on each stack */
cleanup:
    lstackDestroy(&stack, TRUE);
    pixDestroy(&pixt);

    return 0;
}
Пример #25
0
static void delete_case6(L_RBTREE *t, node *n) {
    sibling(n)->color = node_color(n->parent);
    n->parent->color = L_BLACK_NODE;
    if (n == n->parent->left) {
        if (node_color(sibling(n)->right) != L_RED_NODE) {
            L_ERROR("right sibling is not RED", "delete_case6");
            return;
        }
        sibling(n)->right->color = L_BLACK_NODE;
        rotate_left(t, n->parent);
    } else {
        if (node_color(sibling(n)->left) != L_RED_NODE) {
            L_ERROR("left sibling is not RED", "delete_case6");
            return;
        }
        sibling(n)->left->color = L_BLACK_NODE;
        rotate_right(t, n->parent);
    }
}
Пример #26
0
static node *maximum_node(node *n) {
    if (!n) {
        L_ERROR("n not defined\n", "maximum_node");
        return NULL;
    }
    while (n->right != NULL) {
        n = n->right;
    }
    return n;
}
Пример #27
0
static node *sibling(node *n) {
    if (!n || !n->parent) {
        L_ERROR("root has no sibling\n", "sibling");
        return NULL;
    }
    if (n == n->parent->left)
        return n->parent->right;
    else
        return n->parent->left;
}
Пример #28
0
/*!
 *  l_pngSetZlibCompression()
 *
 *      Input:  val (zlib compression value)
 *      Return: void
 *
 *  Notes:
 *      (1) Valid zlib compression values are in the interval [0 ... 9],
 *          where, as defined in zlib.h:
 *            0         Z_NO_COMPRESSION
 *            1         Z_BEST_SPEED    (poorest compression)
 *            9         Z_BEST_COMPRESSION
 *          For the default value, use either of these:
 *            6         Z_DEFAULT_COMPRESSION
 *           -1         (resolves to Z_DEFAULT_COMPRESSION)
 *      (2) If you use the defined constants in zlib.h instead of the
 *          compression integers given above, you must include zlib.h.
 */
void
l_pngSetZlibCompression(l_int32  val)
{
    PROCNAME("l_pngSetZlibCompression");
    if (val < -1 || val > 9) {
        L_ERROR("Invalid zlib comp val; using default", procName);
        val = Z_DEFAULT_COMPRESSION;
    }
    var_ZLIB_COMPRESSION = val;
}
/*!
 *  dewarpSinglePageRun()
 *
 *      Input:  pixs (any depth)
 *              pixb (1 bpp)
 *              dewa (initialized)
 *              &pixd (<return> dewarped result)
 *              debug (1 for debugging output, 0 otherwise)
 *      Return: 0 if OK, 1 on error (list of page numbers), or null on error
 *
 *  Notes:
 *      (1) Dewarps pixs and returns the result in &pixd.
 *      (2) The model parameters must be set before calling this.
 *      (3) If a model cannot be built, this returns a copy of pixs in &pixd.
 */
l_int32
dewarpSinglePageRun(PIX        *pixs,
                    PIX        *pixb,
                    L_DEWARPA  *dewa,
                    PIX       **ppixd,
                    l_int32     debug)
{
const char  *debugfile;
l_int32      vsuccess, ret;
L_DEWARP    *dew;

    PROCNAME("dewarpSinglePageRun");

    if (!ppixd)
        return ERROR_INT("&pixd not defined", procName, 1);
    *ppixd = NULL;
    if (!pixs)
        return ERROR_INT("pixs not defined", procName, 1);
    if (!pixb)
        return ERROR_INT("pixs not defined", procName, 1);
    if (!dewa)
        return ERROR_INT("dewa not defined", procName, 1);

        /* Generate the page model */
    lept_mkdir("lept");
    dew = dewarpCreate(pixb, 0);
    dewarpaInsertDewarp(dewa, dew);
    debugfile = (debug) ? "/tmp/lept/singlepage_model.pdf" : NULL;
    dewarpBuildPageModel(dew, debugfile);
    dewarpaModelStatus(dewa, 0, &vsuccess, NULL);
    if (vsuccess == 0) {
        L_ERROR("failure to build model for vertical disparity\n", procName);
        *ppixd = pixCopy(NULL, pixs);
        return 0;
    }

        /* Apply the page model */
    debugfile = (debug) ? "/tmp/lept/singlepage_apply.pdf" : NULL;
    ret = dewarpaApplyDisparity(dewa, 0, pixs, 255, 0, 0, ppixd, debugfile);
    if (ret)
        L_ERROR("invalid model; failure to apply disparity\n", procName);
    return 0;
}
Пример #30
0
/*!
 *  l_autodecode_137()
 *
 *      Input:  index into array of functions
 *      Return: data struct (e.g., pixa) in memory
 */
void *
l_autodecode_137(l_int32 index)
{
l_uint8  *data1, *data2;
l_int32   size1;
size_t    size2;
void     *result = NULL;
l_int32   nfunc = 2;

    PROCNAME("l_autodecode_137");

    if (index < 0 || index >= nfunc) {
        L_ERROR("invalid index = %d; must be less than %d\n", procName,
                index, nfunc);
        return NULL;
    }

    lept_mkdir("lept/auto");

        /* Unencode selected string, write to file, and read it */
    switch (index) {
    case 0:
        data1 = decodeBase64(l_strdata_0, strlen(l_strdata_0), &size1);
        data2 = zlibUncompress(data1, size1, &size2);
        l_binaryWrite("/tmp/lept/auto/data.bin","w", data2, size2);
        result = (void *)pixaRead("/tmp/lept/auto/data.bin");
        lept_free(data1);
        lept_free(data2);
        break;
    case 1:
        data1 = decodeBase64(l_strdata_1, strlen(l_strdata_1), &size1);
        data2 = zlibUncompress(data1, size1, &size2);
        l_binaryWrite("/tmp/lept/auto/data.bin","w", data2, size2);
        result = (void *)pixaRead("/tmp/lept/auto/data.bin");
        lept_free(data1);
        lept_free(data2);
        break;
    default:
        L_ERROR("invalid index", procName);
    }

    return result;
}