Get the pageId for a ocrd_file
509984
def get_physical_page_for_file(self, ocrd_file):
        
        ret = self._tree.getroot().xpath(
            '/mets:mets/mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div[@TYPE="page"][./mets:fptr[@FILEID="%s"]]/@ID' %
            ocrd_file.ID, namespaces=NS)
        if ret:
            return ret[0]
1293378
protected String getOCRText(String filename, int pageNum) {
        if (filename != null && !filename.isEmpty()) {
            api.TessBaseAPISetInputName(handle, filename);
        }

        Pointer utf8Text = renderedFormat == RenderedFormat.HOCR ? api.TessBaseAPIGetHOCRText(handle, pageNum - 1) : api.TessBaseAPIGetUTF8Text(handle);
        String str = utf8Text.getString(0);
        api.TessDeleteText(utf8Text);
        return str;
    }
518495
def get_page_content(id):
    
    data = _json.loads(_api.rest("/" + str(id) + "?expand=body.storage"))
    return data["body"]["storage"]["value"]
414084
def _get_nb_pages(self):
        
        try:
            filelist = self.fs.listdir(self.path)
            count = 0
            for filepath in filelist:
                filename = self.fs.basename(filepath)
                if (filename[-4:].lower() != "." + ImgPage.EXT_IMG or
                    (filename[-10:].lower() == "." + ImgPage.EXT_THUMB) or
                    (filename[:len(ImgPage.FILE_PREFIX)].lower() !=
                        ImgPage.FILE_PREFIX)):
                    continue
                count += 1
            return count
        except IOError as exc:
            logger.debug("Exception while trying to get the number of"
                         " pages of '%s': %s", self.docid, exc)
            return 0
        except OSError as exc:
            if exc.errno != errno.ENOENT:
                logger.error("Exception while trying to get the number of"
                             " pages of '%s': %s", self.docid, exc)
                raise
            return 0
599486
def get_pageinfo(input_file, context):
    ""
    pageno = page_number(input_file) - 1
    pageinfo = context.get_pdfinfo()[pageno]
    return pageinfo
493700
public int getDocId(String url) {
        synchronized (mutex) {
            OperationStatus result = null;
            DatabaseEntry value = new DatabaseEntry();
            try {
                DatabaseEntry key = new DatabaseEntry(url.getBytes());
                result = docIDsDB.get(null, key, value, null);

            } catch (RuntimeException e) {
                if (config.isHaltOnError()) {
                    throw e;
                } else {
                    logger.error("Exception thrown while getting DocID", e);
                    return -1;
                }
            }

            if ((result == OperationStatus.SUCCESS) && (value.getData().length > 0)) {
                return Util.byteArray2Int(value.getData());
            }

            return -1;
        }
    }
496177
def get_page_object_by_id(context, object_type, oid):
    
    if type(oid) != int:
        raise template.TemplateSyntaxError('page_object_by_id tag requires a integer argument')

    selected_object = None

    try:
        try:
            for obj in context['page']['content'][object_type]:
                sid = '{0:>s}:{1:>s}:{2:>s}:{3:>d}'.format(
                    obj.language, context['page']['page'].name, obj.type, oid
                )
                if obj.sid == sid:
                    selected_object = obj
                    break
        except TypeError:
            pass
    except KeyError:
        try:
            try:
                for obj in context['page']['ext_content'][object_type]:
                    sid = '{0:>s}:{1:>s}:{2:>s}:{3:>d}'.format(
                        obj.language, context['page']['page'].name, obj.type, oid
                    )
                    if obj.sid == sid:
                        selected_object = obj
                        break
            except TypeError:
                pass
        except KeyError:
            raise template.TemplateSyntaxError('wrong content type: {0:>s}'.format(object_type))
    return selected_object
531238
@InterfaceAudience.Public
    public String getDocumentRevisionId() {
        // Get the revision id from either the embedded document contents,
        // or the '_rev' or 'rev' value key:
        String rev = null;
        if (documentRevision != null)
            rev = documentRevision.getRevID();
        if (rev == null) {
            if (value instanceof Map) {
                Map<String, Object> mapValue = (Map<String, Object>) value;
                rev = (String) mapValue.get("_rev");
                if (rev == null) {
                    rev = (String) mapValue.get("rev");
                }
            }
        }
        return rev;
    }
600995
def get_page_properties(self, page_id):
        
        url = 'rest/api/content/{page_id}/property'.format(page_id=page_id)
        return self.get(path=url)
474920
private String stringId() throws RecognitionException {
        if ( input.LA( 1 ) == DRL5Lexer.ID ) {
            Token id = match( input,
                              DRL5Lexer.ID,
                              null,
                              null,
                              DroolsEditorType.IDENTIFIER );
            if ( state.failed ) return null;
            return id.getText();
        } else if ( input.LA( 1 ) == DRL5Lexer.STRING ) {
            Token id = match( input,
                              DRL5Lexer.STRING,
                              null,
                              null,
                              DroolsEditorType.IDENTIFIER );
            if ( state.failed ) return null;
            return StringUtils.unescapeJava( safeStripStringDelimiters( id.getText() ) );
        } else {
            throw new MismatchedTokenException( DRL5Lexer.ID,
                                                input );
        }
    }
152181
def get_page_export(self, page_id):
        
        try:
            result = self._request('/getpageexport/',
                                   {'pageid': page_id})
            return TildaPage(**result)
        except NetworkError:
            return []
1182145
private int getPid() {

	PageContext pc = ThreadLocalPageContext.get();
	if (pc == null) {
	    pc = CFMLEngineFactory.getInstance().getThreadPageContext();
	    if (pc == null) throw new RuntimeException("cannot get pid for current thread");
	}
	return pc.getId();
    }
96442
def get_page_from_string_or_id(page_string, lang=None):
    """"""
    if type(page_string) == int:
        return Page.objects.get(pk=int(page_string))
    # if we have a string coming from some templates templates
    is_text = isinstance(page_string, SafeText)
    import sys
    PY3 = sys.version > '3'
    if PY3:
        is_string = isinstance(page_string, str)
    else:
        is_string = isinstance(page_string, unicode) or isinstance(page_string, str)
    if is_text or is_string:
        if page_string.isdigit():
            return Page.objects.get(pk=int(page_string))
        return Page.objects.from_path(page_string, lang)
    # in any other case we return the input becasue it's probably
    # a Page object.
    return page_string
628241
def select_ocr_image(infiles, output_file, log, context):
    """"""

    image = infiles[0]
    options = context.get_options()
    pageinfo = get_pageinfo(image, context)

    with Image.open(image) as im:
        from PIL import ImageColor
        from PIL import ImageDraw

        white = ImageColor.getcolor('#ffffff', im.mode)
        # pink = ImageColor.getcolor('#ff0080', im.mode)
        draw = ImageDraw.ImageDraw(im)

        xres, yres = im.info['dpi']
        log.debug('resolution %r %r', xres, yres)

        if not options.force_ocr:
            # Do not mask text areas when forcing OCR, because we need to OCR
            # all text areas
            mask = None  # Exclude both visible and invisible text from OCR
            if options.redo_ocr:
                mask = True  # Mask visible text, but not invisible text

            for textarea in pageinfo.get_textareas(visible=mask, corrupt=None):
                # Calculate resolution based on the image size and page dimensions
                # without regard whatever resolution is in pageinfo (may differ or
                # be None)
                bbox = [float(v) for v in textarea]
                xscale, yscale = float(xres) / 72.0, float(yres) / 72.0
                pixcoords = [
                    bbox[0] * xscale,
                    im.height - bbox[3] * yscale,
                    bbox[2] * xscale,
                    im.height - bbox[1] * yscale,
                ]
                pixcoords = [int(round(c)) for c in pixcoords]
                log.debug('blanking %r', pixcoords)
                draw.rectangle(pixcoords, fill=white)
                # draw.rectangle(pixcoords, outline=pink)

        if options.mask_barcodes or options.threshold:
            pix = leptonica.Pix.frompil(im)
            if options.threshold:
                pix = pix.masked_threshold_on_background_norm()
            if options.mask_barcodes:
                barcodes = pix.locate_barcodes()
                for barcode in barcodes:
                    decoded, rect = barcode
                    log.info('masking barcode %s %r', decoded, rect)
                    draw.rectangle(rect, fill=white)
            im = pix.topil()

        del draw
        # Pillow requires integer DPI
        dpi = round(xres), round(yres)
        im.save(output_file, dpi=dpi)
1016130
def get_params_from_page(path, file_name, method_count):
    
    # open the rendered file.
    file_name = file_name.replace(".rst", "")
    file_path = "{0}/../_build/html/endpoints/{1}/index.html".format(
        path, file_name)
    soup = bs4.BeautifulSoup(open(file_path))

    # Pull out the relevant section
    section = soup.find_all('div', class_='section')[method_count]

    # get the tbody of the params table
    tbody = section.find('tbody')
    params = []
    if tbody is not None:
        for row in tbody.find_all('tr'):
            name, param_type, required, description = row.find_all('td')
            required = required.text == 'Yes'
            param = dict(
                name=name.text,
                type=param_type.text,
                required=required,
                description=description.text
            )
            params.append(param)
    params = sorted(params, key=lambda k: not k['required'])
    return params
1023932
def parse_page(raw_page):
  
  ret = {"title": get_title(raw_page), "id": get_id(raw_page)}
  if ":" in ret["title"]:
    return None
  ret["revisions"] = get_revisions(raw_page)
  return ret
996756
public OvhDocument document_documentId_GET(String documentId) throws IOException {
		String qPath = "/store/document/{documentId}";
		StringBuilder sb = path(qPath, documentId);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhDocument.class);
	}