Renders a dot graph into an svg

@param string $dotString The dot graph that is fed into the
@return string|bool the resulting SVG
774080
public function runDot($dotString)
    {
        $descriptorSpec = array(
            0 => array("pipe", "r"), // stdin
            1 => array("pipe", "w"), // stdout
            2 => array("pipe", "a") // stderr
        );

        $process = proc_open('dot -Tsvg', $descriptorSpec, $pipes);

        if (is_resource($process)) {
            fwrite($pipes[0], $dotString);
            fclose($pipes[0]);

            $svg = stream_get_contents($pipes[1]);
            fclose($pipes[1]);

            proc_close($process);
            $svg = explode('<svg ', $svg);

            // has it worked out?
            if (count($svg) < 2) {
                return false;
            }

            return '<svg ' . $svg[1];
        }

        return false;
    }
849509
public function graphAction($component = null)
    {
        $graphvizService = GeneralUtility::makeInstanceService('graphviz', 'svg');
        if ($graphvizService instanceof GraphvizService) {
            $graph = new Graph(Scanner::discoverAll());

            return $graphvizService->createGraph($graph($component));
        }

        return '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="30" viewBox=".2 -6.2 200 30"><text x="100" y="7" text-anchor="middle" font-family="sans-serif" font-size="11">Component graph cannot be created</text><text x="100" y="17" text-anchor="middle" font-family="sans-serif" font-size="8">Please check your GraphViz installation</text><path fill="none" stroke="#000" stroke-miterlimit="10" d="M199.73 18.133c0 2.75-2.25 5-5 5h-189c-2.75 0-5-2.25-5-5v-19c0-2.75 2.25-5 5-5h189c2.75 0 5 2.25 5 5v19z"/></svg>';
    }
591144
public function svg($str_filename = null)
    {
        $str_svg = $this->svgForHtml5();
        $str_svg = '<?xml version="1.0" encoding="utf-8"?>'. "\n". $str_svg;

        if (!is_null($str_filename)) {
            file_put_contents($str_filename, $str_svg);
        }

        return $str_svg;
    }
125503
def render_graph(result, cfg, **kwargs):
    
    # Mapping from MIME types to formats accepted by RDFlib
    rdflib_formats = {'text/rdf+n3': 'n3',
                      'text/turtle': 'turtle',
                      'application/x-turtle': 'turtle',
                      'text/turtle': 'turtle',
                      'application/rdf+xml': 'xml',
                      'text/rdf': 'xml',
                      'application/rdf+xml': 'xml'}


    try:
        got = kwargs.get('format', 'text/rdf+n3')
        fmt = rdflib_formats[got]
    except KeyError:
        raise KrnlException('Unsupported format for graph processing: {!s}', got)

    g = ConjunctiveGraph()
    g.load(StringInputSource(result), format=fmt)

    display = cfg.dis[0] if is_collection(cfg.dis) else cfg.dis
    if display in ('png', 'svg'):
        try:
            literal = len(cfg.dis) > 1 and cfg.dis[1].startswith('withlit')
            opt = {'lang': cfg.lan, 'literal': literal, 'graphviz': []}
            data, metadata = draw_graph(g, fmt=display, options=opt)
            return {'data': data,
                    'metadata': metadata}
        except Exception as e:
            raise KrnlException('Exception while drawing graph: {!r}', e)
    elif display == 'table':
        it = rdf_iterator(g, set(cfg.lan), add_vtype=cfg.typ)
        n, data = html_table(it, limit=cfg.lmt, withtype=cfg.typ)
        data += div('Shown: {}, Total rows: {}', n if cfg.lmt else 'all',
                    len(g), css="tinfo")
        data = {'text/html': div(data)}
    elif len(g) == 0:
        data = {'text/html': div(div('empty graph', css='krn-warn'))}
    else:
        data = {'text/plain': g.serialize(format='nt').decode('utf-8')}

    return {'data': data,
            'metadata': {}}
1348508
public function render($config = array())
    {
        $config = new ObjectConfigJson($config);
        $config->append(array(
            'toolbar' => null,
            'title'   => null,
        ));

        //Set a custom title
        if($config->title) {
            $config->toolbar->setTitle($config->title);
        }

        $title = $this->getObject('translator')->translate($config->toolbar->getTitle());
        $html  = '';

        if (!empty($title))
        {
            $mobile = ($config->mobile === '' || $config->mobile) ? 'k-title-bar--mobile' : '';

            $html .= '
            <div class="k-title-bar k-js-title-bar '.$mobile.'">
                <div class="k-title-bar__heading">' . $title . '</div>
            </div>';
        }

        return $html;
    }
82181
function renderToString(vnode, context, opts, inner, isSvgMode) {
	if (vnode==null || typeof vnode==='boolean') {
		return '';
	}

	let nodeName = vnode.type,
		attributes = vnode.props,
		isComponent = false;
	context = context || {};
	opts = opts || {};

	let pretty = opts.pretty,
		indentChar = typeof pretty==='string' ? pretty : '\t';

	// #text nodes
	if (typeof vnode!=='object' && !nodeName) {
		return encodeEntities(vnode);
	}

	// components
	if (typeof nodeName==='function') {
		isComponent = true;
		if (opts.shallow && (inner || opts.renderRootComponent===false)) {
			nodeName = getComponentName(nodeName);
		}
		else {
			let props = getNodeProps(vnode),
				rendered;

			if (!nodeName.prototype || typeof nodeName.prototype.render!=='function') {
				// stateless functional components
				rendered = nodeName(props, context);
			}
			else {
				// class-based components
				let c = new nodeName(props, context);
				// turn off stateful re-rendering:
				c._disable = c.__x = true;
				c.props = props;
				c.context = context;
				if (c.componentWillMount) c.componentWillMount();
				rendered = c.render(c.props, c.state, c.context);

				if (c.getChildContext) {
					context = assign(assign({}, context), c.getChildContext());
				}
			}

			return renderToString(rendered, context, opts, opts.shallowHighOrder!==false);
		}
	}

	// render JSX to HTML
	let s = '', html;

	if (attributes) {
		let attrs = objectKeys(attributes);

		// allow sorting lexicographically for more determinism (useful for tests, such as via preact-jsx-chai)
		if (opts && opts.sortAttributes===true) attrs.sort();

		for (let i=0; i<attrs.length; i++) {
			let name = attrs[i],
				v = attributes[name];
			if (name==='children') continue;

			if (name.match(/[\s\n\\/='"\0<>]/)) continue;

			if (!(opts && opts.allAttributes) && (name==='key' || name==='ref')) continue;

			if (name==='className') {
				if (attributes.class) continue;
				name = 'class';
			}
			else if (isSvgMode && name.match(/^xlink:?./)) {
				name = name.toLowerCase().replace(/^xlink:?/, 'xlink:');
			}

			if (name==='style' && v && typeof v==='object') {
				v = styleObjToCss(v);
			}

			let hooked = opts.attributeHook && opts.attributeHook(name, v, context, opts, isComponent);
			if (hooked || hooked==='') {
				s += hooked;
				continue;
			}

			if (name==='dangerouslySetInnerHTML') {
				html = v && v.__html;
			}
			else if ((v || v===0 || v==='') && typeof v!=='function') {
				if (v===true || v==='') {
					v = name;
					// in non-xml mode, allow boolean attributes
					if (!opts || !opts.xml) {
						s += ' ' + name;
						continue;
					}
				}
				s += ` ${name}="${encodeEntities(v)}"`;
			}
		}
	}

	// account for >1 multiline attribute
	let sub = s.replace(/^\n\s*/, ' ');
	if (sub!==s && !~sub.indexOf('\n')) s = sub;
	else if (pretty && ~s.indexOf('\n')) s += '\n';

	s = `<${nodeName}${s}>`;
	if (String(nodeName).match(/[\s\n\\/='"\0<>]/)) throw s;

	let isVoid = String(nodeName).match(VOID_ELEMENTS);
	if (isVoid) s = s.replace(/>$/, ' />');

	let pieces = [];
	if (html) {
		// if multiline, indent.
		if (pretty && isLargeString(html)) {
			html = '\n' + indentChar + indent(html, indentChar);
		}
		s += html;
	}
	else if (vnode.props.children) {
        let hasLarge = ~s.indexOf('\n');
        let children = vnode.props.children;
        if (!Array.isArray(children)) {
            children = [children]
        }
        for (let i=0; i< children.length; i++) {
            let child = children[i];
            if (child!=null && child!==false) {
                let childSvgMode = nodeName==='svg' ? true : nodeName==='foreignObject' ? false : isSvgMode,
                    ret = renderToString(child, context, opts, true, childSvgMode);
                if (!hasLarge && pretty && isLargeString(ret)) hasLarge = true;
                if (ret) pieces.push(ret);
            }
        }

		if (pretty && hasLarge) {
			for (let i=pieces.length; i--; ) {
				pieces[i] = '\n' + indentChar + indent(pieces[i], indentChar);
			}
		}
	}

	if (pieces.length) {
		s += pieces.join('');
	}
	else if (opts && opts.xml) {
		return s.substring(0, s.length-1) + ' />';
	}

	if (!isVoid) {
		if (pretty && ~s.indexOf('\n')) s += '\n';
		s += `</${nodeName}>`;
	}

	return s;
}
501377
public function convert($dotnetFormat)
    {
        // get string literals and replace with a placeholder to make specifier matching simpler
        $stringLiterals = [];

        $callback = function ($matches) use (&$stringLiterals) {
            $stringLiterals[] = reset($matches);
            return '%s';
        };

        $dotnetFormatPlaceholders = preg_replace_callback(
            $this->getPatternStringLiteralsDotNet(),
            $callback,
            $dotnetFormat
        );

        // match .NET specifiers
        $callback = function ($matches) use ($dotnetFormat) {
            $specifier = reset($matches);

            if (!isset($this->dotnetToPhp[$specifier])) {
                throw new UnsupportedFormatException($dotnetFormat, $specifier);
            }

            return $this->dotnetToPhp[$specifier];
        };

        $phpFormatPlaceholders = preg_replace_callback(
            $this->getPatternSpecifiersDotnet(),
            $callback,
            $dotnetFormatPlaceholders
        );

        // remove slashes from literals
        $callback = function ($value) {
            if ($value == '\\') {
                // don't remove single slashes - these are literal slashes
                return $value;
            }

            // slashes within quotes are literal slashes
            if (preg_match('/^["\'].+["\']$/', $value)) {
                return $value;
            }

            $value = stripslashes($value);

            return $value;
        };

        $stringLiterals = array_map($callback, $stringLiterals);

        // remove quotes from literals
        $stringLiterals = str_replace(['"', '\''], '', $stringLiterals);

        // escape any PHP specifier characters that appear in the string literals
        $callback = function ($matches) {
            $match = reset($matches);
            return '\\' . $match;
        };

        $stringLiterals = preg_replace_callback($this->getPatternSpecifiersPhp(), $callback, $stringLiterals);

        // replace placeholders with string literals
        return vsprintf($phpFormatPlaceholders, $stringLiterals);
    }
1365705
def draw_svg(self, svg_str):
        """"""

        try:
            import rsvg
        except ImportError:
            self.draw_text(svg_str)
            return

        svg = rsvg.Handle(data=svg_str)

        svg_width, svg_height = svg.get_dimension_data()[:2]

        transx, transy = self._get_translation(svg_width, svg_height)

        scale_x, scale_y = self._get_scalexy(svg_width, svg_height)
        scale = min(scale_x, scale_y)

        angle = float(self.code_array.cell_attributes[self.key]["angle"])

        self.context.save()
        self.context.rotate(-angle / 360 * 2 * math.pi)
        self.context.translate(transx, transy)
        self.context.scale(scale, scale)
        svg.render_cairo(self.context)
        self.context.restore()
1031208
public function createFromString($imageString)
    {
        $this->sourceImageResource = new \Imagick();

        try {

            return $this->sourceImageResource->readImageBlob($imageString);

        } catch (\ImagickException $e) {

            $this->errors[ $e->getCode() ] = $e->getMessage();

        }

        return false;
    }
464654
public static function svg_dimensions($svg) {
		ref\cast::string($svg, true);

		// Make sure this is SVG-looking.
		if (false === ($start = \strpos(\strtolower($svg), '<svg'))) {
			if (@\is_file($svg)) {
				$svg = \file_get_contents($svg);
				if (false === ($start = \strpos(\strtolower($svg), '<svg'))) {
					return false;
				}
			}
			else {
				return false;
			}
		}

		// Chop the code to the first tag.
		$svg = \substr($svg, $start);
		if (false === ($end = \strpos($svg, '>'))) {
			return false;
		}
		$svg = \strtolower(\substr($svg, 0, $end + 1));

		// Hold our values.
		$out = array(
			'width'=>null,
			'height'=>null,
		);
		$viewbox = null;

		// Search for width, height, and viewbox.
		ref\sanitize::whitespace($svg, 0);

		\preg_match_all(
			'/(height|width|viewbox)\s*=\s*(["\'])((?:(?!\2).)*)\2/',
			$svg,
			$match,
			\PREG_SET_ORDER
		);

		if (\is_array($match) && \count($match)) {
			foreach ($match as $v) {
				switch ($v[1]) {
					case 'width':
					case 'height':
						ref\cast::float($v[3], true);
						ref\sanitize::to_range($v[3], 0.0);
						if ($v[3]) {
							$out[$v[1]] = $v[3];
						}
						break;
					case 'viewbox':
						// Defer processing for later.
						$viewbox = $v[3];
						break;
				}
			}
		}

		// If we have a width and height, we're done!
		if ($out['width'] && $out['height']) {
			return $out;
		}

		// Maybe pull from viewbox?
		if (isset($viewbox)) {
			$viewbox = \trim(\str_replace(',', ' ', $viewbox));
			$viewbox = \explode(' ', $viewbox);
			foreach ($viewbox as $k=>$v) {
				ref\cast::float($viewbox[$k], true);
				ref\sanitize::to_range($viewbox[$k], 0.0);
			}
			if (\count($viewbox) === 4) {
				$out['width'] = $viewbox[2];
				$out['height'] = $viewbox[3];
				return $out;
			}
		}

		return false;
	}
281348
public void drawString(String pString) {
        setupForText();
        graphics.drawString(pString, (float) getPenPosition().getX(), (float) getPenPosition().getY());
    }
160350
public function svg()
    {
        if (count($this->arr_points) < 3) {
            throw new \RuntimeException('Before exporting to SVG, you must give at least 3 points!');
        }

        $arr = array();

        foreach ($this->arr_points as $point) {
            $arr[] = implode(',', $point);
        }

        $str_attr_points = implode(' ', $arr);

        return sprintf('<polygon points="%s" style="fill:%s" />', $str_attr_points, $this->color);
    }
546323
private function attrs_to_string($attrs)
    {
        $attrs_string ='';

        foreach($attrs as $name => $node)
        {
            $attrs_string.= sprintf(' %s="%s"',$name,$node->nodeValue);
        }

        return $attrs_string;
    }
868562
public function dumpDot()
	{
		$dot = '';
		foreach ($this->parents as $x => $r) {
			$dot .= sprintf("\"[UF] %s\" [fillcolor=\"#%x\"];\n", $x, crc32($x) & 0xffffff | 0x808080);
			$dot .= "\"[UF] $r\" -> \"[UF] $x\" [arrowhead=none,arrowtail=vee];\n";
		}
		return $dot;
	}
925076
public function svg()
    {
        $str_g = '';

        foreach ($this->arr_units as $k => $u) {
            $int_dx = 0;
            $int_dy = 0;

            if ($k == self::TOP_RIGHT) {
                $int_dx = Unit::SIZE;
            } elseif ($k == self::BOTTOM_RIGHT) {
                $int_dx = Unit::SIZE;
                $int_dy = Unit::SIZE;
            } elseif ($k == self::BOTTOM_LEFT) {
                $int_dy = Unit::SIZE;
            }

            $str_attr_translate = sprintf(
                ' transform="translate(%d, %d)"',
                $int_dx,
                $int_dy
            );

            if ($int_dx || $int_dy) {
                $str_g .= sprintf('<g%s>%s</g>', $str_attr_translate, $u->svg()) . "\n";
            } else {
                $str_g .= $u->svg() . "\n";
            }
        }

        $str_attr = '';

        if ($this->type != self::TOP_LEFT) {
            $int_dx = 0;
            $int_dy = 0;

            if ($this->type == self::TOP_RIGHT) {
                $int_dx = self::SIZE;
            } elseif ($this->type == self::BOTTOM_RIGHT) {
                $int_dx = self::SIZE;
                $int_dy = self::SIZE;
            } elseif ($this->type == self::BOTTOM_LEFT) {
                $int_dy = self::SIZE;
            }

            $int_way = $this->bool_rotate_way ? -1 : 1;
            $str_attr = sprintf(
                ' transform="translate(%d, %d) rotate(%d, %d, %d)"',
                $int_dx,
                $int_dy,
                $this->type * 90 * $int_way,
                Unit::SIZE,
                Unit::SIZE
            );
        }

        return sprintf(
            '<g id="quarter-%d"%s>%s</g>'."\n",
            $this->type,
            $str_attr,
            $str_g
        );
    }
546350
public function encodeString($sString)
    {
        //If shop is running in UTF-8 nothing to do here
        if ($this->getConfig()->isUtf() === true) {
            return $sString;
        }

        $sShopEncoding = $this->getLanguage()->translateString('charset');
        return iconv('UTF-8', $sShopEncoding, $sString);
    }
1015766
public function svg()
    {
        if (is_null($this->center) || is_null($this->radius)) {
            throw new \RuntimeException('Before exporting to SVG, you must give center and radius!');
        }

        if ($this->isCircle()) {
            return sprintf(
                '<circle cx="%d" cy="%d" r="%d" fill="%s" />',
                $this->center->x,
                $this->center->y,
                $this->radius->r,
                $this->color
            );
        }

        return sprintf(
            '<ellipse cx="%d" cy="%d" rx="%d" ry="%d" fill="%s" />',
            $this->center->x,
            $this->center->y,
            $this->radius->rx,
            $this->radius->ry,
            $this->color
        );
    }