Overall scale for print-out to account for print borders in dialogs etc
960618
function preview(print)
	{
		var autoOrigin = onePageCheckBox.checked || pageCountCheckBox.checked;
		var printScale = parseInt(pageScaleInput.value) / 100;
		
		if (isNaN(printScale))
		{
			printScale = 1;
			pageScaleInput.value = '100%';
		}
		
		// Workaround to match available paper size in actual print output
		printScale *= 0.75;

		var pf = graph.pageFormat || mxConstants.PAGE_FORMAT_A4_PORTRAIT;
		var scale = 1 / graph.pageScale;
		
		if (autoOrigin)
		{
    		var pageCount = (onePageCheckBox.checked) ? 1 : parseInt(pageCountInput.value);
			
			if (!isNaN(pageCount))
			{
				scale = mxUtils.getScaleForPageCount(pageCount, graph, pf);
			}
		}

		// Negative coordinates are cropped or shifted if page visible
		var gb = graph.getGraphBounds();
		var border = 0;
		var x0 = 0;
		var y0 = 0;

		// Applies print scale
		pf = mxRectangle.fromRectangle(pf);
		pf.width = Math.ceil(pf.width * printScale);
		pf.height = Math.ceil(pf.height * printScale);
		scale *= printScale;
		
		// Starts at first visible page
		if (!autoOrigin && graph.pageVisible)
		{
			var layout = graph.getPageLayout();
			x0 -= layout.x * pf.width;
			y0 -= layout.y * pf.height;
		}
		else
		{
			autoOrigin = true;
		}
		
		var preview = PrintDialog.createPrintPreview(graph, scale, pf, border, x0, y0, autoOrigin);
		preview.open();
	
		if (print)
		{
			PrintDialog.printPreview(preview);
		}
	}
1153463
def _print_figures(figures, arguments='', file_format='pdf', target_width=8.5, target_height=11.0, target_pad=0.5):
    

    for fig in figures:

        # get the temp path
        temp_path = _os.path.join(_settings.path_home, "temp")

        # make the temp folder
        _settings.MakeDir(temp_path)

        # output the figure to postscript
        path = _os.path.join(temp_path, "graph."+file_format)

        # get the dimensions of the figure in inches
        w=fig.get_figwidth()
        h=fig.get_figheight()

        # we're printing to 8.5 x 11, so aim for 7.5 x 10
        target_height = target_height-2*target_pad
        target_width  = target_width -2*target_pad

        # depending on the aspect we scale by the vertical or horizontal value
        if 1.0*h/w > target_height/target_width:
            # scale down according to the vertical dimension
            new_h = target_height
            new_w = w*target_height/h
        else:
            # scale down according to the hozo dimension
            new_w = target_width
            new_h = h*target_width/w

        fig.set_figwidth(new_w)
        fig.set_figheight(new_h)

        # save it
        fig.savefig(path, bbox_inches=_pylab.matplotlib.transforms.Bbox(
            [[-target_pad, new_h-target_height-target_pad],
             [target_width-target_pad, target_height-target_pad]]))

        # set it back
        fig.set_figheight(h)
        fig.set_figwidth(w)


        if not arguments == '':
            c = _settings['instaprint'] + ' ' + arguments + ' "' + path + '"'
        else:
            c = _settings['instaprint'] + ' "' + path + '"'

        print(c)
        _os.system(c)
22542
def print_border_only row, col, height, width, color, att=Ncurses::A_NORMAL
      if att.nil? 
        att = Ncurses::A_NORMAL
      else
        att = get_attrib att
      end
      wattron(Ncurses.COLOR_PAIR(color) | att)
      mvwaddch  row, col, Ncurses::ACS_ULCORNER
      mvwhline( row, col+1, Ncurses::ACS_HLINE, width-2)
      mvwaddch row, col+width-1, Ncurses::ACS_URCORNER
      mvwvline( row+1, col, Ncurses::ACS_VLINE, height-1)

      mvwaddch row+height-0, col, Ncurses::ACS_LLCORNER
      mvwhline(row+height-0, col+1, Ncurses::ACS_HLINE, width-2)
      mvwaddch row+height-0, col+width-1, Ncurses::ACS_LRCORNER
      mvwvline( row+1, col+width-1, Ncurses::ACS_VLINE, height-1)
      wattroff(Ncurses.COLOR_PAIR(color) | att)
    end
771665
private void createPrintContactsSubForm() {
		add(new WHeading(HeadingLevel.H3, "Print to CSV"));

		WButton printBtn = new WButton("Print");
		printBtn.setAction(new Action() {
			@Override
			public void execute(final ActionEvent event) {
				printDetails();
			}
		});
		printBtn.setImage("/image/document-print.png");
		printBtn.setImagePosition(WButton.ImagePosition.EAST);

		WFieldLayout layout = new WFieldLayout();
		add(layout);
		layout.setMargin(new Margin(Size.LARGE, null, null, null));
		layout.addField("Print output", printOutput);
		layout.addField((WLabel) null, printBtn);
		add(new WAjaxControl(printBtn, printOutput));
	}
294753
def show(self):
        
        print("StringBlock(stringsCount=0x%x, "
              "stringsOffset=0x%x, "
              "stylesCount=0x%x, "
              "stylesOffset=0x%x, "
              "flags=0x%x"
              ")" % (self.stringCount,
                     self.stringsOffset,
                     self.styleCount,
                     self.stylesOffset,
                     self.flags))

        if self.stringCount > 0:
            print()
            print("String Table: ")
            for i, s in enumerate(self):
                print("{:08d} {}".format(i, repr(s)))

        if self.styleCount > 0:
            print()
            print("Styles Table: ")
            for i in range(self.styleCount):
                print("{:08d} {}".format(i, repr(self.getStyle(i))))
358190
def repaint
      return unless @repaint_required
      bc = $datacolor
      bordercolor = @border_color || bc
      borderatt = @border_attrib || Ncurses::A_NORMAL
      @window.print_border row, col, height, width, bordercolor, borderatt
      #print_borders
      print_title
      @repaint_required = false
    end
1254638
def _printStats(self, graph, hrlinetop=False):
        
        if hrlinetop:
            self._print("----------------", "TIP")
        self._print("Ontologies......: %d" % len(graph.all_ontologies), "TIP")
        self._print("Classes.........: %d" % len(graph.all_classes), "TIP")
        self._print("Properties......: %d" % len(graph.all_properties), "TIP")
        self._print("..annotation....: %d" % len(graph.all_properties_annotation), "TIP")
        self._print("..datatype......: %d" % len(graph.all_properties_datatype), "TIP")
        self._print("..object........: %d" % len(graph.all_properties_object), "TIP")
        self._print("Concepts(SKOS)..: %d" % len(graph.all_skos_concepts), "TIP")
        self._print("----------------", "TIP")
724085
private void justificationOfRVFDatum(RVFDatum<L, F> example, PrintWriter pw) {
    int featureLength = 0;
    int labelLength = 6;
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMinimumFractionDigits(2);
    nf.setMaximumFractionDigits(2);
    if (nf instanceof DecimalFormat) {
      ((DecimalFormat) nf).setPositivePrefix(" ");
    }
    Counter<F> features = example.asFeaturesCounter();
    for (F f : features.keySet()) {
      featureLength = Math.max(featureLength, f.toString().length() + 2 +
          nf.format(features.getCount(f)).length());
    }
    // make as wide as total printout
    featureLength = Math.max(featureLength, "Total:".length());
    // don't make it ridiculously wide
    featureLength = Math.min(featureLength, MAX_FEATURE_ALIGN_WIDTH);

    for (Object l : labels()) {
      labelLength = Math.max(labelLength, l.toString().length());
    }

    StringBuilder header = new StringBuilder("");
    for (int s = 0; s < featureLength; s++) {
      header.append(' ');
    }
    for (L l : labels()) {
      header.append(' ');
      header.append(StringUtils.pad(l, labelLength));
    }
    pw.println(header);
    for (F f : features.keySet()) {
      String fStr = f.toString();
      StringBuilder line = new StringBuilder(fStr);
      line.append("[").append(nf.format(features.getCount(f))).append("]");
      fStr = line.toString();
      for (int s = fStr.length(); s < featureLength; s++) {
        line.append(' ');
      }
      for (L l : labels()) {
        String lStr = nf.format(weight(f, l));
        line.append(' ');
        line.append(lStr);
        for (int s = lStr.length(); s < labelLength; s++) {
          line.append(' ');
        }
      }
      pw.println(line);
    }
    Counter<L> scores = scoresOfRVFDatum(example);
    StringBuilder footer = new StringBuilder("Total:");
    for (int s = footer.length(); s < featureLength; s++) {
      footer.append(' ');
    }
    for (L l : labels()) {
      footer.append(' ');
      String str = nf.format(scores.getCount(l));
      footer.append(str);
      for (int s = str.length(); s < labelLength; s++) {
        footer.append(' ');
      }
    }
    pw.println(footer);
    Distribution<L> distr = Distribution.distributionFromLogisticCounter(scores);
    footer = new StringBuilder("Prob:");
    for (int s = footer.length(); s < featureLength; s++) {
      footer.append(' ');
    }
    for (L l : labels()) {
      footer.append(' ');
      String str = nf.format(distr.getCount(l));
      footer.append(str);
      for (int s = str.length(); s < labelLength; s++) {
        footer.append(' ');
      }
    }
    pw.println(footer);
  }
1340361
def _print_counts(self):
        
        print "#  ",
        for i in range(self.width):
            print "  %4d   "%i,
        print
        for L in ['A', 'C', 'T', 'G']:
            print "#%s "%L,
            for i in range(self.width):
                print  "%8.3f "%self.counts[i][L],
            print
434031
def print_table(self, items, fields):
        
        formats = []
        borders = []
        for f in fields:
            length = max(
                len(f), max([len(self.string(getattr(i, f))) for i in items]))
            justify = '>' if isinstance(getattr(
                items[0], f), int) or f == 'size' or f == 'reward' else '<'
            formats.append('{:' + justify + self.string(length + 2) + '}')
            borders.append('-' * length + '  ')
        row_format = u''.join(formats)
        headers = [f + '  ' for f in fields]
        print(row_format.format(*headers))
        print(row_format.format(*borders))
        for i in items:
            i_fields = [self.string(getattr(i, f)) + '  ' for f in fields]
            try:
                print(row_format.format(*i_fields))
            except UnicodeEncodeError:
                print(row_format.format(*i_fields).encode('utf-8'))
1108264
def render_debug_img(
    file_name,
    page_num,
    elems,
    nodes=[],
    scaler=1,
    print_segments=False,
    print_curves=True,
    print_table_bbox=True,
    print_text_as_rect=True,
):
    
    # For debugging show the boolean pixels in black white grayscale
    height = scaler * int(elems.layout.height)
    width = scaler * int(elems.layout.width)
    debug_img, draw = create_img((0, 0, width, height))
    font = lazy_load_font()
    large_font = lazy_load_font(24)

    if print_curves:
        for i, c in enumerate(elems.curves):
            if len(c.pts) > 1:
                draw.polygon(c.pts, outline=blue)
            draw.rectangle(c.bbox, fill=blue)
            # for fig in elems.figures:
            #     draw.rectangle(fig.bbox, fill = blue)

    for i, m in enumerate(elems.mentions):
        if isinstance(m, LTAnno):
            continue
        if print_text_as_rect:
            fill = "pink" if hasattr(m, "feats") and m.feats["is_cell"] else green
            #             fill = green
            draw.rectangle(m.bbox, fill=fill)
            # draw.text(center(m.bbox), str(i), black, font = font) # Draw id
            draw.text(
                m.bbox[:2], m.get_text(), black, font=font
            )  # Draw mention content
        else:
            draw.text(m.bbox[:2], m.get_text(), "black", font=font)

    if print_segments:
        # draw skeleton for all segments
        for i, s in enumerate(elems.segments):
            draw.line(s.bbox, fill="black")

    if print_table_bbox:
        for node in nodes:
            is_table = node.is_table()
            color = "red" if is_table else "green"
            draw.rectangle(node.bbox, outline=color)
            if is_table:
                # text = 'Borderless' if node.is_borderless() else 'Bordered'
                text = "Table"
                draw.rectangle(node.bbox, outline=color)
                draw.text(node.bbox[:2], text, red, font=large_font)

    # Water mark with file name so we can identify among multiple images
    if file_name and page_num is not None:
        water_mark = (
            file_name + ":page " + str(page_num + 1) + "@%dx%d" % (width, height)
        )
        draw.text((10, 10), water_mark, black, font=font)
    debug_img.show()
    return debug_img
804958
public int print(Graphics g, PageFormat pageFormat, int pageIndex) 
    {
        Graphics2D g2d = (Graphics2D)g;

        if (firstTime)
        {
            m_componentPrint = new ComponentPrint(null);
            m_componentPrint.surveyComponents(m_component);
            m_paperPrint = new PaperPrint(null);
            m_paperPrint.surveyPage(pageFormat, g2d, m_bPrintHeader);
            firstTime = false;
        }

        // Print this page
        int pageHeight = m_paperPrint.getPrintableHeight();
        double scale = Math.min(1.0, ((double)m_paperPrint.getPrintableWidth() / (double)m_componentPrint.getMaxComponentWidth()));

        m_paperPrint.setCurrentYLocation(0);
        m_componentPrint.setPageHeight((int)(pageHeight / scale));
        boolean pageDone = m_componentPrint.setCurrentYLocation(pageIndex, 0);
        
        while (!pageDone)
        {
            Component component = m_componentPrint.getCurrentComponent();
            int componentCurrentYLocation = m_componentPrint.getCurrentYLocation();
            int componentHeightOnPage = m_componentPrint.getComponentPageHeight();

            if (this.isCancelled())
                return NO_SUCH_PAGE;    // Done, No more pages
            if (component == null)
            {
                if (m_paperPrint.getCurrentYLocation() == 0)
                    return NO_SUCH_PAGE;    // No more pages
                else
                    break;  // End of components (last page)
            }

            if (m_paperPrint.getCurrentYLocation() == 0)
            {       // First time through
                if (m_bPrintHeader)
                {
                    m_paperPrint.printHeader(g2d, m_componentPrint.getTitle());
                    m_paperPrint.printFooter(g2d, "Page " + (pageIndex + 1));
                }
                this.setDialogMessage("Printing page " + (pageIndex + 1));
            }

            int xShift = m_paperPrint.getXOffset();
            int yShift = m_paperPrint.getYOffset() - (int)(componentCurrentYLocation * scale);

            g2d.setClip(m_paperPrint.getXOffset(), m_paperPrint.getYOffset(), m_paperPrint.getPrintableWidth(), (int)(componentHeightOnPage * scale));
            g2d.translate(xShift, yShift);
            g2d.scale(scale, scale);
            disableDoubleBuffering(component);
            component.paint(g2d);
            enableDoubleBuffering(component);
            g2d.scale(1 / scale, 1 / scale);
            g2d.translate(-xShift, -yShift);

            m_paperPrint.addCurrentYLocation((int)(componentHeightOnPage * scale));
            pageDone = m_componentPrint.addCurrentYLocation(componentHeightOnPage);
        }
        return PAGE_EXISTS;
    }
492369
def _do_layout(self):
        """"""

        sizer_csvoptions = wx.FlexGridSizer(5, 4, 5, 5)

        # Adding parameter widgets to sizer_csvoptions
        leftpos = wx.LEFT | wx.ADJUST_MINSIZE
        rightpos = wx.RIGHT | wx.EXPAND

        current_label_margin = 0  # smaller for left column
        other_label_margin = 15

        for label, widget in zip(self.param_labels, self.param_widgets):
            sizer_csvoptions.Add(label, 0, leftpos, current_label_margin)
            sizer_csvoptions.Add(widget, 0, rightpos, current_label_margin)

            current_label_margin, other_label_margin = \
                other_label_margin, current_label_margin

        sizer_csvoptions.AddGrowableCol(1)
        sizer_csvoptions.AddGrowableCol(3)

        self.sizer_csvoptions = sizer_csvoptions
944408
def do_printInstances(self,args):
        """"""
        parser = CommandArgumentParser("printInstances")
        parser.add_argument(dest='filters',nargs='*',default=["*"],help='Filter instances');
        parser.add_argument('-a','--addresses',action='store_true',dest='addresses',help='list all ip addresses');
        parser.add_argument('-t','--tags',action='store_true',dest='tags',help='list all instance tags');
        parser.add_argument('-d','--allDetails',action='store_true',dest='details',help='print all instance details');
        parser.add_argument('-r','--refresh',action='store_true',dest='refresh',help='refresh');
        parser.add_argument('-z','--zones',dest='availabilityZones',nargs='+',help='Only include specified availability zones');
        args = vars(parser.parse_args(args))
        
        client = AwsConnectionFactory.getEc2Client()

        filters = args['filters']
        addresses = args['addresses']
        tags = args['tags']
        details = args['details']
        availabilityZones = args['availabilityZones']
        needDescription = addresses or tags or details

        if args['refresh']:
            self.scalingGroupDescription = self.client.describe_auto_scaling_groups(AutoScalingGroupNames=[self.scalingGroup])
        
        # print "AutoScaling Group:{}".format(self.scalingGroup)
        print "=== Instances ==="
        instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances']

        instances = filter( lambda x: fnmatches(x['InstanceId'],filters),instances)
        if availabilityZones:
            instances = filter( lambda x: fnmatches(x['AvailabilityZone'],availabilityZones),instances)
        
        index = 0
        for instance in instances:
            instance['index'] = index
            print "* {0:3d} {1} {2} {3}".format(index,instance['HealthStatus'],instance['AvailabilityZone'],instance['InstanceId'])
            description = None
            if needDescription:
                description = client.describe_instances(InstanceIds=[instance['InstanceId']])
            if addresses:
                networkInterfaces = description['Reservations'][0]['Instances'][0]['NetworkInterfaces']
                number = 0
                print "      Network Interfaces:"
                for interface in networkInterfaces:
                    print "         * {0:3d} {1}".format(number, interface['PrivateIpAddress'])
                    number +=1
            if tags:
                tags = description['Reservations'][0]['Instances'][0]['Tags']
                print "      Tags:"
                for tag in tags:
                    print "        * {0} {1}".format(tag['Key'],tag['Value'])
            if details:
                pprint(description)
                
            index += 1
807393
function getDomains (display, height, width, bounds, options) {
  var xmin = bounds[0][0]
  var xmax = bounds[1][0]
  var ymin = bounds[0][1]
  var ymax = bounds[1][1]
  var xRange = xmax - xmin
  var yRange = ymax - ymin

  var paddingFactor = (options && options.paddingFactor)
    ? options.paddingFactor
    : 0.1

  var margins = getMargins(options)

  var usableHeight = height - margins.top - margins.bottom
  var usableWidth = width - margins.left - margins.right
  var displayAspect = width / height
  var usableDisplayAspect = usableWidth / usableHeight
  var graphAspect = xRange / (yRange === 0 ? -Infinity : yRange)

  var padding
  var dispX1, dispX2, dispY1, dispY2
  var dispXRange, dispYRange

  if (usableDisplayAspect > graphAspect) { // y-axis is limiting
    padding = paddingFactor * yRange
    dispY1 = ymin - padding
    dispY2 = ymax + padding
    dispYRange = yRange + 2 * padding
    var addedYRange = (height / usableHeight * dispYRange) - dispYRange
    if (margins.top > 0 || margins.bottom > 0) {
      dispY1 -= margins.bottom / (margins.bottom + margins.top) * addedYRange
      dispY2 += margins.top / (margins.bottom + margins.top) * addedYRange
    }
    dispXRange = (dispY2 - dispY1) * displayAspect
    var xOffset = (margins.left - margins.right) / width
    var xMidpoint = (xmax + xmin - dispXRange * xOffset) / 2
    dispX1 = xMidpoint - dispXRange / 2
    dispX2 = xMidpoint + dispXRange / 2
  } else { // x-axis limiting
    padding = paddingFactor * xRange
    dispX1 = xmin - padding
    dispX2 = xmax + padding
    dispXRange = xRange + 2 * padding
    var addedXRange = (width / usableWidth * dispXRange) - dispXRange
    if (margins.left > 0 || margins.right > 0) {
      dispX1 -= margins.left / (margins.left + margins.right) * addedXRange
      dispX2 += margins.right / (margins.left + margins.right) * addedXRange
    }

    dispYRange = (dispX2 - dispX1) / displayAspect
    var yOffset = (margins.bottom - margins.top) / height
    var yMidpoint = (ymax + ymin - dispYRange * yOffset) / 2
    dispY1 = yMidpoint - dispYRange / 2
    dispY2 = yMidpoint + dispYRange / 2
  }

  return [
    [dispX1, dispX2],
    [dispY1, dispY2]
  ]
}
66943
private DocInfo computeParametersForDoc(ArrayList<ArrayList<TextPiece>> wordsByPage) {
    	DocInfo docInfo = new DocInfo();

    	float docTitleFont = 0;
    	float[][] scaleListsWithTextAmount = new float[5000][2]; 
    	int scaleNum = 0;
	

    	int pageNum = 0;
    	for (ArrayList<TextPiece> wordsOfAPage : wordsByPage) {
    		pageNum++;
    		// ArrayList<TextPiece> linesOfAPage = new ArrayList<TextPiece>();
    		// TextPiece line = null;
    		for (int i = 0; i < wordsOfAPage.size(); i++)
    		{
    			// TextPiece prevWord = (i == 0) ? null : wordsOfAPage.get(i -	// 1);
    			TextPiece currentWord = wordsOfAPage.get(i);
    			// get the document title font size
    			if ( (pageNum == 1) && (currentWord.getY()<400) )
    			{
    				if (docTitleFont < currentWord.getFontSize())
    					docTitleFont = currentWord.getFontSize();
    			}
    			//get the document body text font
    			if (scaleNum==0) {
    				scaleListsWithTextAmount[0][0] = Math.max(currentWord.getXScale(), currentWord.getFontSize());
    				scaleListsWithTextAmount[0][1] = currentWord.getWidth();
    				scaleNum++;
    			}
    			else {
    				boolean notExist = true; 
    				for (int m=0; m<scaleNum; m++) {
    					if (scaleListsWithTextAmount[m][0]== Math.max(currentWord.getXScale(), currentWord.getFontSize())) {
    						scaleListsWithTextAmount[m][1] = scaleListsWithTextAmount[m][1] + currentWord.getWidth();	//calculate the text width for each scale is better than just counting the line number
    						notExist=false;
    					}
    				}
    				if (notExist==true) {
    					scaleListsWithTextAmount[scaleNum][0] =  Math.max(currentWord.getXScale(), currentWord.getFontSize());
    					scaleListsWithTextAmount[scaleNum][1] = currentWord.getWidth();
    					scaleNum++;
    				}
    			}//end else
    		}//end for()
    	}//for()
    	float maxLineNum = 0;
    	int bodyTextScaleIndex=0;
    	for (int j=0; j<scaleNum; j++) {
    		if (scaleListsWithTextAmount[j][1]>maxLineNum) {
    			maxLineNum = scaleListsWithTextAmount[j][1];
    			bodyTextScaleIndex=j;
    		}
    	}
	
    	/*
    	 * Calculates other background characters----------
    	 */
    	float ave_LineGap = (float)0.1; //this is ave_LineGap_thisPage in old version
    	float ave_X_Gap_inLine = (float)0.1;
    	int lineNumInBodyFont = 1;
    	int sameLineObj=1;
    	float minX = 1000;
        float maxX = 0;
        float minY = 1000;
        float maxY = 0;
        float aveCharWidthInDoc = (float)0.0000001;
        int charNumInWholeDoc = 1;
        
    	for (ArrayList<TextPiece> wordsOfAPage : wordsByPage) {
    		for (int i = 1; i < wordsOfAPage.size(); i++) {
    			/*
    			 * Calculates ave_LineGap
    			 */
    			TextPiece currentWord = wordsOfAPage.get(i);
    			TextPiece prevWord = wordsOfAPage.get(i-1);
    			if (Math.max(currentWord.getXScale(), currentWord.getFontSize())==scaleListsWithTextAmount[bodyTextScaleIndex][0]) { //only consider the text pieces that in the body text font
    				if ( (currentWord.getY()-prevWord.getY()-prevWord.getHeight()>(float)0.0) &&
    				(currentWord.getY()-prevWord.getY()-prevWord.getHeight()<prevWord.getHeight()) ) {//reduce the big gap noise
    					ave_LineGap = ave_LineGap + (currentWord.getY()-prevWord.getY());
    					lineNumInBodyFont++;
    				}
    			
    				/*
    				 * Gets the boundary of the doc page-
    				 */
    				if ( (currentWord.getX()<minX) && (currentWord.getX()>0) )  
    					minX = currentWord.getX();    			
    				if ( (currentWord.getX()+currentWord.getWidth()+currentWord.getWidthOfSpace())>maxX) 
    					maxX = currentWord.getX()+currentWord.getWidth()+currentWord.getWidthOfSpace();
    				if ( (currentWord.getY()<minY) && (currentWord.getY()>0) ) 
    					minY =currentWord.getY();
    				if (currentWord.getY()>maxY) maxY = currentWord.getY();
				
				
    				/*
    				 * Calculates ave_X_Gap_inLine
    				 */
    				if ( (currentWord.getY()==prevWord.getY()) && 
    					(currentWord.getX()-prevWord.getX()-prevWord.getWidth()>0) ) {
    						ave_X_Gap_inLine = ave_X_Gap_inLine + currentWord.getX()-prevWord.getX()-prevWord.getWidth();
    						sameLineObj++;
    				}
    				
    				/*
    				 * calculates the average width of each character in the whole document
    				 */
    				aveCharWidthInDoc = aveCharWidthInDoc + currentWord.getWidth();
    				charNumInWholeDoc = charNumInWholeDoc + currentWord.getText().length();
    			}//end if(lines in body text font)
			}//end (for a page)
    	}//end for(all pages)
    	ave_LineGap = ave_LineGap/(float)lineNumInBodyFont;
    	ave_X_Gap_inLine = ave_X_Gap_inLine/(float)sameLineObj;
    	aveCharWidthInDoc = aveCharWidthInDoc/(float)charNumInWholeDoc;
    	docInfo.setTitleFont(docTitleFont);
    	docInfo.setBodyTextScale(scaleListsWithTextAmount[bodyTextScaleIndex][0]);
       	docInfo.setAverageLineGap(ave_LineGap);
    	docInfo.setMinX(minX);
    	docInfo.setMaxX(maxX);
    	docInfo.setMinY(minY);
    	docInfo.setMaxY(maxY);
    	docInfo.setAverageXGap(ave_X_Gap_inLine);
	   	docInfo.setAverageCharWidth(aveCharWidthInDoc);
    	//System.out.println("The text body font size is: " + docInfo.getBodyTextScale());
    	//System.out.println("ave_LineGap: " + ave_LineGap);
    	//System.out.println("ave_X_Gap_inLine: " + ave_X_Gap_inLine);
    	//System.out.println("aveCharWidthInDoc: " + aveCharWidthInDoc);
    	//System.out.println("(MinX, maxX) (MinY, MaxY): (" + minX + "," + maxX + "); (" + minY + "," + maxY +").");
    	//System.out.println();
    	
    	/*
    	 * TODO! Unfinished
    	 * Judges whether this doc only has one column
    	 */
    	float middleX = docInfo.getMinX() + (docInfo.getMaxX()-docInfo.getMinX())/2;
        docInfo.setMiddleX(middleX);
    	docInfo.setMiddleArea_X(middleX-3);
    	docInfo.setMiddleArea_EndX(middleX+3);
    	int lineNum_blockMiddle = 0;
    	for (ArrayList<TextPiece> wordsOfAPage : wordsByPage) {
    		for (int i = 1; i < wordsOfAPage.size(); i++) {
    			TextPiece currentWord = wordsOfAPage.get(i);
    			TextPiece prevWord = wordsOfAPage.get(i-1);
    			
    			//todo
    		}
    	}
    	return docInfo;
    }
1040426
def print_to_screen(self, metrics_dict):
        """"""
        score_strings = defaultdict(list)
        for split_metric, value in metrics_dict.items():
            split, metric = split_metric.split("/", 1)

            if isinstance(value, float):
                score_strings[split].append(f"{metric}={value:0.3f}")
            else:
                score_strings[split].append(f"{metric}={value}")

        header = f"{self.unit_total} {self.log_unit[:3]}"
        if self.log_unit != "epochs":
            epochs = self.example_total / self.epoch_size
            header += f" ({epochs:0.2f} epo)"
        string = f"[{header}]:"

        if score_strings["train"]:
            train_scores = f"{', '.join(score_strings['train'])}"
            string += f" TRAIN:[{train_scores}]"
        if score_strings["valid"]:
            valid_scores = f"{', '.join(score_strings['valid'])}"
            string += f" VALID:[{valid_scores}]"
        print(string)