DSL method. See http://squib.readthedocs.io
15306
def hand(opts = {})
      range = Args::CardRange.new(opts[:range], deck_size: size)
      hand  = Args::HandSpecial.new(height).load!(opts, expand_by: size, layout: layout, dpi: dpi)
      sheet = Args::Sheet.new(custom_colors, { file: 'hand.png', trim_radius: 0 }).load!(opts, expand_by: size, layout: layout, dpi: dpi)
      render_hand(range, sheet, hand)
    end
246096
def render_tree(self, data):
        
        # TODO: find a way to make this localization aware...
        # because ATM it formats texts using French style numbers...
        # best way would be to let the user inject its own vars...
        # but this would not work on fusion servers...
        # so we must find a way to localize this a bit... or remove it and
        # consider our caller must pre - render its variables to the desired
        # locale...?
        new_data = dict(
            decimal=decimal,
            format_float=(
                lambda val: (
                    isinstance(
                        val, decimal.Decimal
                    ) or isinstance(
                        val, float
                    )
                ) and str(val).replace('.', ',') or val
            ),
            format_percentage=(
                lambda val: ("%0.2f %%" % val).replace('.', ',')
            )
        )

        # Soft page breaks are hints for applications for rendering a page
        # break. Soft page breaks in for loops may compromise the paragraph
        # formatting especially the margins. Open-/LibreOffice will regenerate
        # the page breaks when displaying the document. Therefore it is save to
        # remove them.
        self.remove_soft_breaks()

        # first we need to transform the py3o template into a valid
        # Genshi template.
        starting_tags, closing_tags = self.handle_instructions(
            self.content_trees,
            self.namespaces
        )
        parents = [tag[0].getparent() for tag in starting_tags]
        linknum = len(parents)
        parentnum = len(set(parents))
        if not linknum == parentnum:
            raise TemplateException(
                "Every py3o link instruction should be on its own line"
            )

        for link, py3o_base in starting_tags:
            self.handle_link(
                link,
                py3o_base,
                closing_tags[id(link)]
            )

        self.__prepare_userfield_decl()
        self.__prepare_usertexts()

        self.__replace_image_links()
        self.__add_images_to_manifest()

        for fnum, content_tree in enumerate(self.content_trees):
            content = lxml.etree.tostring(content_tree.getroot())
            if self.ignore_undefined_variables:
                template = MarkupTemplate(content, lookup='lenient')
            else:
                template = MarkupTemplate(content)

            # then we need to render the genshi template itself by
            # providing the data to genshi

            template_dict = {}
            template_dict.update(data.items())
            template_dict.update(new_data.items())

            self.output_streams.append(
                (
                    self.templated_files[fnum],
                    template.generate(**template_dict)
                )
            )
683997
def display(obj, raw_output=False, **kwargs):
    
    if not Store.loaded_backends() and isinstance(obj, Dimensioned):
        raise RuntimeError('To use display on a HoloViews object ensure '
                           'a backend is loaded using the holoviews '
                           'extension.')

    raw = True
    if isinstance(obj, GridSpace):
        with option_state(obj):
            output = grid_display(obj)
    elif isinstance(obj, (CompositeOverlay, ViewableElement)):
        with option_state(obj):
            output = element_display(obj)
    elif isinstance(obj, (Layout, NdLayout, AdjointLayout)):
        with option_state(obj):
            output = layout_display(obj)
    elif isinstance(obj, (HoloMap, DynamicMap)):
        with option_state(obj):
            output = map_display(obj)
    elif isinstance(obj, Plot):
        output = render(obj)
    else:
        output = obj
        raw = kwargs.pop('raw', False)

    if raw_output:
        return output
    elif isinstance(output, tuple):
        data, metadata = output
    else:
        data, metadata = output, {}
    return IPython.display.display(data, raw=raw, metadata=metadata, **kwargs)
395169
def get_3Ddata(self, start=0, stop=None, step=1):
        
        data3d = []
        dcmlist = self.files_in_serie
        # print('stsp ', start, stop, step)

        # raw_max = None
        # raw_min = None
        # slope = None
        # inter = None

        # get shape 2d

        # sometimes there is render in series
        if len(self.files_in_serie) > 1:
            data = self._read_file(dcmlist[0])
            data2d1 = data.pixel_array
            data = self._read_file(dcmlist[1])
            data2d2 = data.pixel_array
            if (data2d1.shape[0] == data2d2.shape[0]) and (data2d1.shape[1] == data2d2.shape[1]):
                pass
            else:
                dcmlist.pop(0)

        if stop is None:
            stop = len(dcmlist)

        # printRescaleWarning = False
        for i in xrange(start, stop, step):
            onefile = dcmlist[i]
            data = self._read_file(onefile)
            new_data2d = data.pixel_array
            # new_data2d, slope, inter = dcmtools.get_pixel_array_from_pdcm(data)
            # mport pdb; pdb.set_trace()

            if len(data3d) == 0:
                shp2 = new_data2d.shape
                data3d = np.zeros([len(dcmlist), shp2[0], shp2[1]],
                                  dtype=new_data2d.dtype)
                slope, inter = dcmtools.get_slope_and_intercept_from_pdcm(data)



            # first readed slide is at the end

            if (data3d.shape[1] == new_data2d.shape[0]) and (data3d.shape[2] == new_data2d.shape[1]):
                data3d[-i - 1, :, :] = new_data2d
            else:
                msg = "Problem with shape " + \
                      "Data size: " + str(data3d.nbytes) + \
                      ', shape: ' + str(shp2) + 'x' + str(len(dcmlist)) + \
                      ' file ' + onefile
                logger.warning(msg)
                print(msg)

            logger.debug("Data size: " + str(data3d.nbytes)
                         + ', shape: ' + str(shp2) + 'x' + str(len(dcmlist))
                         + ' file ' + onefile)
        data3d = misc.use_economic_dtype(data3d, slope=slope, inter=inter)
        # if original_dtype == np.uint16 and data3d.dtype == np.int16:
        #     data3d = data3d.astype(np.int32)
            # or just force set slope=0.5, inter = 0
        # new_data2d = rescale_pixel_array(data2d, slope, inter)
        # if printRescaleWarning:
        #     print("Automatic Rescale with slope 0.5")
        #     logger.warning("Automatic Rescale with slope 0.5")
        # data3d = dcmtools.rescale_pixel_array(data3d, slope=slope, inter=inter)

        return data3d
1127634
def text(embed, para, box, trans, draw, dpi)
      Squib.logger.debug {"Rendering text with: \n#{para} \nat:\n #{box} \ndraw:\n #{draw} \ntransform: #{trans}"}
      extents = nil
      use_cairo do |cc|
        cc.set_source_squibcolor(draw.color)
        cc.translate(box.x, box.y)
        cc.rotate(trans.angle)
        cc.move_to(0, 0)

        font_desc      = Pango::FontDescription.new(para.font)
        font_desc.size = para.font_size * Pango::SCALE unless para.font_size.nil?
        layout         = cc.create_pango_layout
        layout.font_description = font_desc
        layout.text = para.str.to_s
        layout.context.resolution = dpi
        if para.markup
          para.str = @deck.typographer.process(layout.text)
          layout.markup = para.str.to_s
        end

        set_font_rendering_opts!(layout)
        set_wh!(layout, box.width, box.height)
        layout.wrap      = para.wrap
        layout.ellipsize = para.ellipsize
        layout.alignment = para.align

        layout.justify = para.justify unless para.justify.nil?
        layout.spacing = para.spacing unless para.spacing.nil?

        embed_images!(embed, para.str, layout, para.valign)

        vertical_start = compute_valign(layout, para.valign, 0)
        cc.move_to(0, vertical_start)

        stroke_outline!(cc, layout, draw) if draw.stroke_strategy == :stroke_first
        cc.move_to(0, vertical_start)

        cc.show_pango_layout(layout)
        stroke_outline!(cc, layout, draw) if draw.stroke_strategy == :fill_first
        draw_text_hint(cc, box.x, box.y, layout, para.hint)
        extents = { width: layout.extents[1].width / Pango::SCALE,
                    height: layout.extents[1].height / Pango::SCALE }
        warn_if_ellipsized layout
      end
      return extents
    end
1254320
def preview(self, limit=None, width=None):
        
        heading = self.heading
        rel = self.proj(*heading.non_blobs)
        if limit is None:
            limit = config['display.limit']
        if width is None:
            width = config['display.width']
        tuples = rel.fetch(limit=limit+1, format="array")
        has_more = len(tuples) > limit
        tuples = tuples[:limit]
        columns = heading.names
        widths = {f: min(max([len(f)] +
            [len(str(e)) for e in tuples[f]] if f in tuples.dtype.names else [len('=BLOB=')]) + 4, width) for f in columns}
        templates = {f: '%%-%d.%ds' % (widths[f], widths[f]) for f in columns}
        return (
            ' '.join([templates[f] % ('*' + f if f in rel.primary_key else f) for f in columns]) + '\n' +
            ' '.join(['+' + '-' * (widths[column] - 2) + '+' for column in columns]) + '\n' +
            '\n'.join(' '.join(templates[f] % (tup[f] if f in tup.dtype.names else '=BLOB=')
                for f in columns) for tup in tuples) +
            ('\n   ...\n' if has_more else '\n') +
            (' (Total: %d)\n' % len(rel) if config['display.show_tuple_count'] else ''))
597627
function (sText, bSkipParagraphs) {
		let oSelf = this._oTopicData,
			oOwnLibrary = this._oOwnLibrary,
			oDependencyLibs = oChainObject.oDependentAPIs,
				oOptions = {
				linkFormatter: function (sTarget, sText) {
					let aMatch,
						aTarget;

					// keep the full target in the fallback text
					sText = sText || sTarget;

						// If the link has a protocol, do not modify, but open in a new window
					if (/:\/\//.test(sTarget)) {
						return this.handleExternalUrl(sTarget, sText);
						}

					// topic:xxx Topic
					aMatch = sTarget.match(/^topic:(\w{32})$/);
					if (aMatch) {
						return '<a target="_self" href="#/topic/' + aMatch[1] + '">' + sText + '</a>';
					}

					// sap.x.Xxx.prototype.xxx - In case of prototype we have a link to method
					aMatch = sTarget.match(/([a-zA-Z0-9.$_]+?)\.prototype\.([a-zA-Z0-9.$_]+)$/);
						if (aMatch) {
						return this.createLink({
							name: aMatch[2],
							type: "methods",
							className: aMatch[1],
							text: sText
						});
					}

					// Heuristics: Extend is always a static method
					// sap.x.Xxx.extend
					// module:sap/x/Xxx.extend
					aMatch = sTarget.match(/^(module:)?([a-zA-Z0-9.$_\/]+?)\.extend$/);
					if (aMatch) {
						let [, sModule, sClass] = aMatch;
						return this.createLink({
							name: sTarget.replace(/^module:/, ""),
							type: "methods",
							className: (sModule ? sModule : "") + sClass,
							text: sText
						});
					}

					// Constructor links are handled in special manner by the SDK
					// sap.x.Xxx.constructor
					// sap.x.Xxx#constructor
					// module:sap/x/Xxx.constructor
					// #constructor
					aMatch = sTarget.match(/^(module:)?([a-zA-Z0-9.$_\/]+?)?[\.#]constructor$/i);
					if (aMatch) {
						let [, sModule, sClass] = aMatch,
							sName;

						if (sClass) {
							sName = (sModule ? sModule : "") + sClass;
						} else {
							sName = oSelf.name
										}

						return this.createLink({
							name: sName,
							hrefAppend: "/constructor",
							text: sText
						});
										}

					// #.setText - local static method
					// #setText - local instance method
					// #.setText.from - local nested method
					aMatch = sTarget.match(/^#(\.)?([a-zA-Z0-9.$_]+)$/);
					if (aMatch) {
						return this.createLink({
							name: aMatch[1] ? `${oSelf.name}.${aMatch[2]}` : aMatch[2],
							type: "methods",
							className: oSelf.name,
							local: true,
							text: sText
						});
					}

					// #event:press - local event
					aMatch = sTarget.match(/^#event:([a-zA-Z0-9$_]+)$/);
					if (aMatch) {
						return this.createLink({
							name: aMatch[1],
							type: "events",
							className: oSelf.name,
							local: true,
							text: sText
						});
					}
					// Event links
					// sap.m.Button#event:press
					// sap.m.Button.event:press
					// module:sap/m/Button.event:press
					// module:sap/m/Button#event:press
					aMatch = sTarget.match(/^(module:)?([a-zA-Z0-9.$_\/]+?)[.#]event:([a-zA-Z0-9$_]+)$/);
					if (aMatch) {
						let [, sModule, sClass, sEvent] = aMatch;
						return this.createLink({
							name: sEvent,
							type: "events",
							className: (sModule ? sModule : "") + sClass,
							text: sText
						});
					}

					// sap.m.Button#setText - instance method
					// module:sap/m/Button#setText
					aMatch = sTarget.match(/^(module:)?([a-zA-Z0-9.$_\/]+)#([a-zA-Z0-9.$_]+)$/);
					if (aMatch) {
						let [, sModule, sClass, sMethod] = aMatch;
						return this.createLink({
							name: sMethod,
							type: "methods",
							className: (sModule ? sModule : "") + sClass,
							text: sText
						});
					}

					// Unresolved type - try to discover target type
					// sap.x.Xxx.xxx
					// module:sap/x/Xxx.xxx
					if (/^(?:module:)?([a-zA-Z0-9.$_\/]+?)\.([a-zA-Z0-9$_]+)$/.test(sTarget)) {
						let [,sClass, sName] = sTarget.match(/^((?:module:)?[a-zA-Z0-9.$_\/]+?)\.([a-zA-Z0-9$_]+)$/),
							sResult = this.createLinkFromTargetType({
								className: sClass,
								methodName: sName,
								target: sTarget,
								self: oSelf,
								ownLibrary: oOwnLibrary,
								dependencyLibs: oDependencyLibs,
								text: sText
							});
						if (sResult) {
							return sResult;
								}
					}

					// Possible nested functions discovery - currently we do this only for regular symbols
					aTarget = sTarget.split(".");
					if (aTarget.length >= 3) {
						let sResult = this.createLinkFromTargetType({
							methodName: aTarget.splice(-2).join("."),
							className: aTarget.join("."),
							target: sTarget,
							self: oSelf,
							ownLibrary: oOwnLibrary,
							dependencyLibs: oDependencyLibs,
							text: sText
						});
						if (sResult) {
							return sResult;
						}
					}

					// Possible forward reference - we will treat them as symbol link
					return this.createLink({
						name: sTarget,
						text: sText
					});

					}.bind(this)
				};

			if (bSkipParagraphs) {
				oOptions.beforeParagraph = "";
				oOptions.afterParagraph = "";
			}

			return this.JSDocUtil().formatTextBlock(sText, oOptions);
		}
1074943
def display(self):
        ''''''
        try:
            from IPython.display import HTML
            import uuid
        except ImportError:
            raise IPythonDisplayImportError

        sequence_json = self.json()

        d3cdn = '//d3js.org/d3.v3.min.js'
        div_id = 'sequence_{}'.format(uuid.uuid1())

        cur_dir = os.path.abspath(os.path.dirname(__file__))
        d3_plasmid_path = os.path.join(cur_dir, 'd3-plasmid.js')
        with open(d3_plasmid_path) as f:
            d3_plasmid_js = f.read()

        html = '<div id={div_id}></div>'.format(div_id=div_id)
        js_databind = '''
        <script>
        require([\'{d3_cdn}\'], function(lib) {{
            window.data = {data};'''.format(div_id=div_id, d3_cdn=d3cdn,
                                            data=sequence_json)

        js_viz = '''
            d3sequence(window.data, \'{div_id}\')
        }});
        </script>
        '''.format(div_id=div_id)

        return HTML(html + js_databind + d3_plasmid_js + js_viz)
180259
def as_html(self):
        """"""
        if not self._folium_map:
            self.draw()
        return self._inline_map(self._folium_map, self._width, self._height)
975688
function() {

        var planes = {
            'px': createPlane('px', this.depthSegments, this.heightSegments),
            'nx': createPlane('nx', this.depthSegments, this.heightSegments),
            'py': createPlane('py', this.widthSegments, this.depthSegments),
            'ny': createPlane('ny', this.widthSegments, this.depthSegments),
            'pz': createPlane('pz', this.widthSegments, this.heightSegments),
            'nz': createPlane('nz', this.widthSegments, this.heightSegments),
        };

        var attrList = ['position', 'texcoord0', 'normal'];
        var vertexNumber = 0;
        var faceNumber = 0;
        for (var pos in planes) {
            vertexNumber += planes[pos].vertexCount;
            faceNumber += planes[pos].indices.length;
        }
        for (var k = 0; k < attrList.length; k++) {
            this.attributes[attrList[k]].init(vertexNumber);
        }
        this.indices = new vendor.Uint16Array(faceNumber);
        var faceOffset = 0;
        var vertexOffset = 0;
        for (var pos in planes) {
            var plane = planes[pos];
            for (var k = 0; k < attrList.length; k++) {
                var attrName = attrList[k];
                var attrArray = plane.attributes[attrName].value;
                var attrSize = plane.attributes[attrName].size;
                var isNormal = attrName === 'normal';
                for (var i = 0; i < attrArray.length; i++) {
                    var value = attrArray[i];
                    if (this.inside && isNormal) {
                        value = -value;
                    }
                    this.attributes[attrName].value[i + attrSize * vertexOffset] = value;
                }
            }
            var len = plane.indices.length;
            for (var i = 0; i < plane.indices.length; i++) {
                this.indices[i + faceOffset] = vertexOffset + plane.indices[this.inside ? (len - i - 1) : i];
            }
            faceOffset += plane.indices.length;
            vertexOffset += plane.vertexCount;
        }

        this.boundingBox = new BoundingBox();
        this.boundingBox.max.set(1, 1, 1);
        this.boundingBox.min.set(-1, -1, -1);
    }
772945
def pretty_view(graph, oriented=False, construction=False,
                graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
    """"""
    layout = create_layout(graph, graphviz_prog=graphviz_prog)
    matrix_view = defaultdict(lambda: ' ')

    # Add the edge to the view

    # print('GRAPH EDGES:', tuple(graph.edges()))
    # print('LAYOUT:', layout)

    edges = ((layout[source], layout[target])
             for source, target in graph.edges())
    # print('EDGES:', tuple(edges))

    for source, target in edges:
        previous_edge_char = None
        previous_position = source
        while source != target:
            for is_dir, transform, edge_char in DIRECTIONS:
                first_loop = previous_edge_char is None
                if is_dir(source, target):
                    previous_source = source
                    source = transform(source)
                    if not first_loop:  # first loop: no previous char
                        char = CHARACTER[previous_edge_char, edge_char]
                        if not isinstance(char, str):
                            char = char.value
                        matrix_view[previous_source] = char
                        if construction:
                            old = defaultdict(lambda: ' ', matrix_view)
                            yield view.build(matrix_view)
                        assert isinstance(matrix_view[previous_source], str)
                    if source != target:
                        previous_edge_char = edge_char
                    previous_position = previous_source
                    break  # for loop ; don't test the remain directions

        if oriented:
            matrix_view[previous_position] = ORIENTATION[previous_edge_char, edge_char]
        if construction:
            yield view.build(matrix_view)

    # mark the place where nodes labels will be added
    # for node, coords in layout.items():
        # matrix_view[coords] = node[0]
    # Add the node labels to the view
    # matrix_view = view.clean(matrix_view)
    for node, (x, y) in layout.items():
        if len(node) == 1:
            matrix_view[x, y] = node
            continue
        row_min, row_max = (view.previous_unwrittable_on_row(matrix_view, (x, y)),
                            view.next_unwrittable_on_row(matrix_view, (x, y)))
        col_min, col_max = (view.previous_unwrittable_on_col(matrix_view, (x, y)),
                              view.next_unwrittable_on_col(matrix_view, (x, y)))
        # print('NODE ' + node + ':',
              # '→row: [{};{}]'.format(row_min, row_max).ljust(20),
              # '↓col: [{};{}]'.format(col_min, col_max))
        print_coords = [itertools.count(x), itertools.cycle((y,))]
        if row_min is None:  # write left to right, end at (x, y)
            if row_max is None or row_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords[0] = tuple(
                x - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            )
            # print('DEBUG 1:', y, len(node), print_coords[0])
        elif row_max is None:  # write left to right, beginning at (x, y)
            if row_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords[0] = tuple(
                x + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            )
            # print('DEBUG 2:', print_coords[0])
        elif (row_max - row_min) > len(node) + 1:  # write left to right, if enough place
            print_coords[0] = tuple(
                x + offset
                for offset in range(len(node))
            )
            # print('DEBUG 3:', print_coords[0])

        elif col_min is None:  # write up to down, end at (x, y)
            if col_max is None or col_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords = (itertools.cycle((x,)), tuple(
                y - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            ))
            # print('DEBUG 4:', y, len(node), print_coords[1])
        elif col_max is None:  # write up to down, beginning at (x, y)
            if col_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            ))
            # print('DEBUG 5:', print_coords[1])
        elif (col_max - col_min) > len(node) + 1:  # write up to down, if enough place
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset
                for offset in range(len(node))
            ))
            # print('DEBUG 6:', print_coords[1])
        else:  # not enough space
            if (row_max - row_min) > (col_max - col_min):
                # more space on Y axis
                node = node[:row_max - row_min]  # cut the node
                print_coords = (itertools.cycle((x,)), tuple(
                    x + offset
                    for offset in range(len(node))
                ))
                # print('DEBUG 7:', print_coords[1])
            else:
                # more space on X axis
                node = node[:col_max - col_min]  # cut the node
                print_coords[0] = tuple(
                    x + offset
                    for offset in range(len(node))
                )
                # print('DEBUG 8:', print_coords[0])

        for letter, i, j in zip(node, *print_coords):
            matrix_view[i, j] = letter




    if construction:
        yield view.build(matrix_view)
    else:
        yield from view.build(matrix_view)
1354663
@Override
  public StreamImpl openReadImpl() throws IOException
  {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    
    if (loader == null) {
      loader = ClassLoader.getSystemClassLoader();
    }

    InputStream is = loader.getResourceAsStream(getTrimPath());

    if (is == null) {
      throw new FileNotFoundException(getURL());
    }
    
    return new VfsStreamOld(is, null);
  }
825653
function blockDelta(blot, filter = true) {
  return blot
    .descendants(LeafBlot)
    .reduce((delta, leaf) => {
      if (leaf.length() === 0) {
        return delta;
      }
      return delta.insert(leaf.value(), bubbleFormats(leaf, {}, filter));
    }, new Delta())
    .insert('\n', bubbleFormats(blot));
}
1305897
def define_dsl_for(subclass)
      class_name = subclass.to_s.split("::").last.camelcase.underscore

      # Allows us to call methods like site.blogs and blog.blog_posts
      define_method("get_#{class_name.pluralise}") do
        self.dup.delete_if do |child|
          !self[child].is_a? subclass
        end
      end

      # Allows us to call methods like site.get_blog which will return the first blog
      define_method("get_#{class_name}") do |url=nil|
        send("get_#{class_name.pluralise}")[url]
      end

      # Allows us to call methods like site.add_blog and blog.add_blog_posts
      define_method "add_#{class_name}" do |key=nil, &block|
        content_class = ContentDriven.const_get class_name.to_s.camelcase
        child = content_class.new &block
        add_child(key, child)
      end
    end
216140
def cfn_viz(template, parameters={}, outputs={}, out=sys.stdout):
    
    known_sg, open_sg = _analyze_sg(template['Resources'])
    (graph, edges) = _extract_graph(template.get('Description', ''),
                                    template['Resources'], known_sg, open_sg)
    graph['edges'].extend(edges)
    _handle_terminals(template, graph, 'Parameters', 'source', parameters)
    _handle_terminals(template, graph, 'Outputs', 'sink', outputs)
    graph['subgraphs'].append(_handle_pseudo_params(graph['edges']))

    _render(graph, out=out)
493403
def display(self):
        '''
        
        '''
        w, h = (0, 0)
        for line in self.shell('dumpsys', 'display').splitlines():
            m = _DISPLAY_RE.search(line, 0)
            if not m:
                continue
            w = int(m.group('width'))
            h = int(m.group('height'))
            o = int(m.group('orientation'))
            w, h = min(w, h), max(w, h)
            return self.Display(w, h, o)

        output = self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-i')
        try:
            data = json.loads(output)
            (w, h, o) = (data['width'], data['height'], data['rotation']/90)
            return self.Display(w, h, o)            
        except ValueError:
            pass
1211301
def _view(self, filepath, format):
        """"""
        methodnames = [
            '_view_%s_%s' % (format, backend.PLATFORM),
            '_view_%s' % backend.PLATFORM,
        ]
        for name in methodnames:
            view_method = getattr(self, name, None)
            if view_method is not None:
                break
        else:
            raise RuntimeError('%r has no built-in viewer support for %r '
                'on %r platform' % (self.__class__, format, backend.PLATFORM))
        view_method(filepath)