For all text objects find alignment that causes the least overlap with
    points and other texts and apply it
12232
def optimally_align_text(x, y, texts, expand, renderer=None, ax=None,
                         direction='xy'):
    
    if ax is None:
        ax = plt.gca()
    if renderer is None:
        r = ax.get_figure().canvas.get_renderer()
    else:
        r = renderer
    bboxes = get_bboxes(texts, r, expand)
    if 'x' not in direction:
        ha = ['']
    else:
        ha = ['left', 'right', 'center']
    if 'y' not in direction:
        va = ['']
    else:
        va = ['bottom', 'top', 'center']
    alignment = list(product(ha, va))
    for i, text in enumerate(texts):
        counts = []
        for h, v in alignment:
            if h:
                text.set_ha(h)
            if v:
                text.set_va(v)
            bbox = text.get_window_extent(r).expanded(*expand).\
                transformed(ax.transData.inverted())
            c = get_points_inside_bbox(x, y, bbox)
            counts.append(len(c) + bbox.count_overlaps(bboxes) - 1)
        a = np.argmin(counts)
        if 'x' in direction:
            text.set_ha(alignment[a][0])
        if 'y' in direction:
            text.set_va(alignment[a][1])
        bboxes[i] = text.get_window_extent(r).expanded(*expand).\
            transformed(ax.transData.inverted())
    return texts
621812
def offset_overlays(self, text, offset=0, run_deps=True, **kw):
        

        if run_deps and self.dependencies:
            text.overlay(self.dependencies)

        for ovlf in self.matchers[0].offset_overlays(text,
                                                     goffset=offset,
                                                     **kw):
            for ovll in self._fit_overlay_lists(text, ovlf.end,
                                                self.matchers[1:]):
                yield self._merge_ovls([ovlf] + ovll)
1371498
def get_align(text):
    ""
    (x1, x2, h, v, a) = unaligned_get_dimension(text)
    return (h, v, a)
362178
function updateTextPadding() {
			var styles = wrapper.styles,
				textAlign = styles && styles.textAlign,
				x = paddingLeft + padding * (1 - alignFactor),
				y;

			// determin y based on the baseline
			y = baseline ? 0 : baselineOffset;

			// compensate for alignment
			if (defined(width) && (textAlign === 'center' || textAlign === 'right')) {
				x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
			}

			// update if anything changed
			if (x !== text.x || y !== text.y) {
				text.attr({
					x: x,
					y: y
				});
			}

			// record current values
			text.x = x;
			text.y = y;
		}
325020
static final int match(String text, int pos, String str) {
        for (int i = 0; i < str.length() && pos >= 0;) {
            int ch = UTF16.charAt(str, i);
            i += UTF16.getCharCount(ch);
            if (isBidiMark(ch)) {
                continue;
            }
            pos = match(text, pos, ch);
            if (PatternProps.isWhiteSpace(ch)) {
                i = skipPatternWhiteSpace(str, i);
            }
        }
        return pos;
    }
714345
def justify(texts, max_len, mode='right'):
    
    if mode == 'left':
        return [x.ljust(max_len) for x in texts]
    elif mode == 'center':
        return [x.center(max_len) for x in texts]
    else:
        return [x.rjust(max_len) for x in texts]
761235
def align_lines(lines: list, column_separator: str='|') -> list:
    
    rows = []
    col_len = []
    for line in lines:
        line = str(line)
        cols = []
        for col_index, col in enumerate(line.split(column_separator)):
            col = str(col).strip()
            cols.append(col)
            if col_index >= len(col_len):
                col_len.append(0)
            col_len[col_index] = max(col_len[col_index], len(col))
        rows.append(cols)

    lines_out = []
    for row in rows:
        cols_out = []
        for col_index, col in enumerate(row):
            if col_index == 0:
                col = col.ljust(col_len[col_index])
            else:
                col = col.rjust(col_len[col_index])
            cols_out.append(col)
        lines_out.append(' '.join(cols_out))
    return lines_out
1233043
def line_alignment(self):
        """"""
        key = self._data.get(b'strokeStyleLineAlignment').enum
        return self.STROKE_STYLE_LINE_ALIGNMENTS.get(key, str(key))
707779
def check_text_similarity(a_dom, b_dom, cutoff):
    """"""
    a_words = list(tree_words(a_dom))
    b_words = list(tree_words(b_dom))

    sm = WordMatcher(a=a_words, b=b_words)
    if sm.text_ratio() >= cutoff:
        return True
    return False
786586
def get_texts_box(texts, fs):
    """"""
    max_len = max(map(len, texts))
    return (fs, text_len(max_len, fs))
259134
def generate_align_subparser(subparsers):
    """"""
    parser = subparsers.add_parser(
        'align', description=constants.ALIGN_DESCRIPTION,
        epilog=constants.ALIGN_EPILOG,
        formatter_class=ParagraphFormatter, help=constants.ALIGN_HELP)
    parser.set_defaults(func=align_results)
    utils.add_common_arguments(parser)
    parser.add_argument('-m', '--minimum', default=20,
                        help=constants.ALIGN_MINIMUM_SIZE_HELP, type=int)
    utils.add_corpus_arguments(parser)
    parser.add_argument('output', help=constants.ALIGN_OUTPUT_HELP,
                        metavar='OUTPUT')
    parser.add_argument('results', help=constants.RESULTS_RESULTS_HELP,
                        metavar='RESULTS')
849051
def findLastCharIndexMatching(text, func):
    
    for i in range(len(text) - 1, -1, -1):
      if func(text[i]):
        return i
248385
function (el, width, height) {
        // FIXME Text element not consider textAlign and textVerticalAlign.

        // TODO, inner text, shadow
        var rect = el.getBoundingRect();

        // FIXME aspect ratio
        if (width == null) {
            width = rect.width;
        }
        if (height == null) {
            height = rect.height;
        }
        width *= this.dpr;
        height *= this.dpr;

        this._fitElement(el, width, height);

        // var aspect = el.scale[1] / el.scale[0];
        // Adjust aspect ratio to make the text more clearly
        // FIXME If height > width, width is useless ?
        // width = height * aspect;
        // el.position[0] *= aspect;
        // el.scale[0] = el.scale[1];

        var x = this._x;
        var y = this._y;

        var canvasWidth = this.width * this.dpr;
        var canvasHeight = this.height * this.dpr;
        var gap = this.gap;

        if (x + width + gap > canvasWidth) {
            // Change a new row
            x = this._x = 0;
            y += this._rowHeight + gap;
            this._y = y;
            // Reset row height
            this._rowHeight = 0;
        }

        this._x += width + gap;

        this._rowHeight = Math.max(this._rowHeight, height);

        if (y + height + gap > canvasHeight) {
            // There is no space anymore
            return null;
        }

        // Shift the el
        el.position[0] += this.offsetX * this.dpr + x;
        el.position[1] += this.offsetY * this.dpr + y;

        this._zr.add(el);

        var coordsOffset = [
            this.offsetX / this.width,
            this.offsetY / this.height
        ];
        var coords = [
            [x / canvasWidth + coordsOffset[0], y / canvasHeight + coordsOffset[1]],
            [(x + width) / canvasWidth + coordsOffset[0], (y + height) / canvasHeight + coordsOffset[1]]
        ];

        return coords;
    }
1257746
def fit_overlays(self, text, run_matchers=None, **kw):
        
        self._maybe_run_matchers(text, run_matchers)
        for i in self._list_match.fit_overlay(text, **kw):
            yield i
255156
def text_align(alignment)
      Kernel.raise ArgumentError, "Unknown alignment constant: #{alignment}" unless ALIGN_TYPE_NAMES.key?(alignment.to_i)
      primitive "text-align #{ALIGN_TYPE_NAMES[alignment.to_i]}"
    end
572312
def _find_quote_position(text):
        """"""
        pos = {}
        is_found_left_quote = False

        for idx, character in enumerate(text):
            if is_found_left_quote is False:
                if character == "'" or character == '"':
                    is_found_left_quote = True
                    quote = character
                    left_pos = idx
            else:
                if character == quote and text[idx - 1] != '\\':
                    pos[left_pos] = idx
                    is_found_left_quote = False

        if is_found_left_quote:
            raise IndexError("No matching close quote at: " + str(left_pos))

        return pos
217734
def textalign(text, maxlength, align='left'):
    
    if align == 'left':
        return text
    elif align == 'centre' or align == 'center':
        spaces = ' ' * (int((maxlength - len(text)) / 2))
    elif align == 'right':
        spaces = (maxlength - len(text))
    else:
        raise ValueError("Invalid alignment specified.")
    return spaces + text