Converts the SVG into a data URI.
@private
541817
function process (svg, { prefix }) {
  // Inject a <style> in the SVG document to allow changing colors
  svg = svg.replace(/<(path|circle) /gi, (_, tag) => `<${tag} fill="__COLOR__" `)

  // Since this is a data: URI, we want to encode it with %23 and such
  svg = encodeURIComponent(svg)

  // We want the #{...} interpolation to be outside the URI encoding
  svg = svg.replace(/__COLOR__/g, '#{' + prefix + '-fix-color($color)}')

  svg = 'data:image/svg+xml;charset=utf-8,' + svg

  return svg
}
1038674
def svg2rlg(path, **kwargs):
    ""

    # unzip .svgz file into .svg
    unzipped = False
    if isinstance(path, str) and os.path.splitext(path)[1].lower() == ".svgz":
        with gzip.open(path, 'rb') as f_in, open(path[:-1], 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
        path = path[:-1]
        unzipped = True

    svg_root = load_svg_file(path)
    if svg_root is None:
        return

    # convert to a RLG drawing
    svgRenderer = SvgRenderer(path, **kwargs)
    drawing = svgRenderer.render(svg_root)

    # remove unzipped .svgz file (.svg)
    if unzipped:
        os.remove(path)

    return drawing
752696
function() {
      var markup = [
        '<?xml version="1.0" standalone="no" ?>',
          '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" ',
            '"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">',
          '<svg ',
            'xmlns="http://www.w3.org/2000/svg" ',
            'xmlns:xlink="http://www.w3.org/1999/xlink" ',
            'version="1.1" ',
            'width="', this.width, '" ',
            'height="', this.height, '" ',
            'xml:space="preserve">',
          '<desc>Created with Fabric.js ', fabric.version, '</desc>',
          fabric.createSVGFontFacesMarkup(this.getObjects())
      ];

      if (this.backgroundImage) {
        markup.push(
          '<image x="0" y="0" ',
            'width="', this.width,
            '" height="', this.height,
            '" preserveAspectRatio="', (this.backgroundImageStretch ? 'none' : 'defer'),
            '" xlink:href="', this.backgroundImage.src,
            '" style="opacity:', this.backgroundImageOpacity,
          '"></image>'
        );
      }

      for (var i = 0, objects = this.getObjects(), len = objects.length; i < len; i++) {
        markup.push(objects[i].toSVG());
      }
      markup.push('</svg>');

      return markup.join('');
    }
650133
function(path, opt) {

        // Once a property is removed from the `attrs` attribute
        // the cellView will recognize a `dirty` flag and rerender itself
        // in order to remove the attribute from SVG element.
        opt = opt || {};
        opt.dirty = true;

        var pathArray = Array.isArray(path) ? path : path.split('/');

        if (pathArray.length === 1) {
            // A top level property
            return this.unset(path, opt);
        }

        // A nested property
        var property = pathArray[0];
        var nestedPath = pathArray.slice(1);
        var propertyValue = joint.util.cloneDeep(this.get(property));

        joint.util.unsetByPath(propertyValue, nestedPath, '/');

        return this.set(property, propertyValue, opt);
    }
443054
function supportsSvgPathArgument(window) {
  const canvas = window.document.createElement('canvas');
  const g = canvas.getContext('2d');
  const p = new window.Path2D('M0 0 L1 1');
  g.strokeStyle = 'red';
  g.lineWidth = 1;
  g.stroke(p);
  const imgData = g.getImageData(0, 0, 1, 1);
  return imgData.data[0] === 255; // Check if pixel is red
}
457642
function (svg) {
		return svg
			.replace(/zIndex="[^"]+"/g, '')
			.replace(/isShadow="[^"]+"/g, '')
			.replace(/symbolName="[^"]+"/g, '')
			.replace(/jQuery[0-9]+="[^"]+"/g, '')
			.replace(/url\([^#]+#/g, 'url(#')
			.replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ')
			.replace(/ (NS[0-9]+\:)?href=/g, ' xlink:href=') // #3567
			.replace(/\n/, ' ')
			// Any HTML added to the container after the SVG (#894)
			.replace(/<\/svg>.*?$/, '</svg>') 
			// Batik doesn't support rgba fills and strokes (#3095)
			.replace(/(fill|stroke)="rgba\(([ 0-9]+,[ 0-9]+,[ 0-9]+),([ 0-9\.]+)\)"/g, '$1="rgb($2)" $1-opacity="$3"')
			/* This fails in IE < 8
			.replace(/([0-9]+)\.([0-9]+)/g, function(s1, s2, s3) { // round off to save weight
				return s2 +'.'+ s3[0];
			})*/

			// Replace HTML entities, issue #347
			.replace(/&nbsp;/g, '\u00A0') // no-break space
			.replace(/&shy;/g,  '\u00AD') // soft hyphen

			// IE specific
			.replace(/<IMG /g, '<image ')
			.replace(/height=([^" ]+)/g, 'height="$1"')
			.replace(/width=([^" ]+)/g, 'width="$1"')
			.replace(/hc-svg-href="([^"]+)">/g, 'xlink:href="$1"/>')
			.replace(/ id=([^" >]+)/g, 'id="$1"') // #4003
			.replace(/class=([^" >]+)/g, 'class="$1"')
			.replace(/ transform /g, ' ')
			.replace(/:(path|rect)/g, '$1')
			.replace(/style="([^"]+)"/g, function (s) {
				return s.toLowerCase();
			});
	}
192775
function parseSVG(s) {
	  var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
	  div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
	  var frag= document.createDocumentFragment();
	  while (div.firstChild.firstChild)
	    frag.appendChild(div.firstChild.firstChild);
	  return frag;
	}
569155
function svg2ttfTransform(options) {
  // Return a callback function handling the buffered content
  return function svg2ttfTransformCb(err, buf, cb) {

    // Handle any error
    if(err) {
      cb(new gutil.PluginError(PLUGIN_NAME, err, { showStack: true }));
      return;
    }

    // Use the buffered content
    try {
      buf = Buffer.from(svg2ttf(String(buf), {
        ts: options.timestamp,
        copyright: options.copyright,
        version: options.version,
      }).buffer);
    } catch (err2) {
      cb(new gutil.PluginError(PLUGIN_NAME, err2, { showStack: true }));
      return;
    }
    cb(null, buf);
  };
}
1283172
function xhrSimpleDataSerializer(data) {
  var uri = [];
  var key;
  for (key in data) {
    uri.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
  }
  return uri.join('&');
}
1003337
function transformAttrs (data, tag) {
  let { attrs, directives } = data
  if (!attrs) {
    attrs = data.attrs = {}
  }
  attrs['weex-type'] = tag
  if (tag === 'image' || tag === 'gif') {
    const { src, resize } = attrs
    if (src) {
      attrs['data-img-src'] = src
    }
    if (resize) {
      if (!directives) {
        directives = data.directives = []
      }
      directives.push({
        name: 'weex-resize',
        value: attrs.resize
      })
    }
  }
}
62590
function SVGLoader(loadItem, preferXHR) {
		this.AbstractLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.SVG);

		// public properties
		this.resultFormatter = this._formatResult;

		// protected properties
		this._tagSrcAttribute = "data";

		if (preferXHR) {
			this.setTag(document.createElement("svg"));
		} else {
			this.setTag(document.createElement("object"));
			this.getTag().type = "image/svg+xml";
		}
	}
102459
function normalizeHtml(src, options) {
    var $ = cheerio.load(src, {
        // We should parse html without trying to normalize too much
        xmlMode: false,

        // SVG need some attributes to use uppercases
        lowerCaseAttributeNames: false,
        lowerCaseTags: false
    });
    var toConvert = [];
    var svgContent = {};
    var outputRoot = options.book.options.output;

    imgConversionCache[outputRoot] = imgConversionCache[outputRoot] || {};

    // Find svg images to extract and process
    if (options.convertImages) {
        $('svg').each(function() {
            var content = renderDom($, $(this));
            var svgId = _.uniqueId('svg');
            var dest = svgId+'.svg';

            // Generate filename
            dest = '/'+fs.getUniqueFilename(outputRoot, dest);

            svgContent[dest] = '<?xml version="1.0" encoding="UTF-8"?>'+content;
            $(this).replaceWith($('<img>').attr('src', dest));
        });
    }

    // Generate ID for headings
    $('h1,h2,h3,h4,h5,h6').each(function() {
        if ($(this).attr('id')) return;

        $(this).attr('id', slug($(this).text()));
    });

    // Find images to normalize
    $('img').each(function() {
        var origin;
        var src = $(this).attr('src');

        if (!src) return;
        var isExternal = links.isExternal(src);

        // Transform as relative to the bases
        if (links.isRelative(src)) {
            src = links.toAbsolute(src, options.base, options.output);
        }

        // Convert if needed
        if (options.convertImages) {
            // If image is external and ebook, then downlaod the images
            if (isExternal) {
                origin = src;
                src = '/'+crc.crc32(origin).toString(16)+path.extname(url.parse(origin).pathname);
                src = links.toAbsolute(src, options.base, options.output);
                isExternal = false;
            }

            var ext = path.extname(src);
            var srcAbs = links.join('/', options.base, src);

            // Test image extension
            if (_.contains(imgUtils.INVALID, ext)) {
                if (imgConversionCache[outputRoot][srcAbs]) {
                    // Already converted
                    src = imgConversionCache[outputRoot][srcAbs];
                } else {
                    // Not converted yet
                    var dest = '';

                    // Replace extension
                    dest = links.join(path.dirname(srcAbs), path.basename(srcAbs, ext)+'.png');
                    dest = dest[0] == '/'? dest.slice(1) : dest;

                    // Get a name that doesn't exists
                    dest = fs.getUniqueFilename(outputRoot, dest);

                    options.book.log.debug.ln('detect invalid image (will be converted to png):', srcAbs);

                    // Add to cache
                    imgConversionCache[outputRoot][srcAbs] = '/'+dest;

                    // Push to convert
                    toConvert.push({
                        origin: origin,
                        content: svgContent[srcAbs],
                        source: isExternal? srcAbs : path.join('./', srcAbs),
                        dest: path.join('./', dest)
                    });

                    src = links.join('/', dest);
                }

                // Reset as relative to output
                src = links.toAbsolute(src, options.base, options.output);
            }

            else if (origin) {
                // Need to downlaod image
                toConvert.push({
                    origin: origin,
                    source: path.join('./', srcAbs)
                });
            }
        }

        $(this).attr('src', src);
    });

    // Normalize links
    $('a').each(function() {
        var href = $(this).attr('href');
        if (!href) return;

        if (links.isAnchor(href)) {
            // Keep it as it is
        } else if (links.isRelative(href)) {
            var parts = url.parse(href);
            var absolutePath = links.join(options.base, parts.pathname);
            var anchor = parts.hash || '';


            // If is in navigation relative: transform as content
            if (options.navigation[absolutePath]) {
                absolutePath = options.book.contentLink(absolutePath);
            }

            // If md/adoc/rst files is not in summary
            // or for ebook, signal all files that are outside the summary
            else if (_.contains(parsableExtensions, path.extname(absolutePath)) ||
            _.contains(['epub', 'pdf', 'mobi'], options.book.options.generator)) {
                options.book.log.warn.ln('page', options.input, 'contains an hyperlink to resource outside spine \''+href+'\'');
            }

            // Transform as absolute
            href = links.toAbsolute('/'+absolutePath, options.base, options.output)+anchor;
        } else {
            // External links
            $(this).attr('target', '_blank');
        }

        // Transform extension
        $(this).attr('href', href);
    });

    // Highlight code blocks
    $('code').each(function() {
        // Normalize language
        var lang = _.chain(
                ($(this).attr('class') || '').split(' ')
            )
            .map(function(cl) {
                // Markdown
                if (cl.search('lang-') === 0) return cl.slice('lang-'.length);

                // Asciidoc
                if (cl.search('language-') === 0) return cl.slice('language-'.length);

                return null;
            })
            .compact()
            .first()
            .value();

        var source = $(this).text();
        var blk = options.book.template.applyBlock('code', {
            body: source,
            kwargs: {
                language: lang
            }
        });

        if (blk.html === false) $(this).text(blk.body);
        else $(this).html(blk.body);
    });

    // Replace glossary terms
    var glossary = _.sortBy(options.glossary, function(term) {
        return -term.name.length;
    });

    _.each(glossary, function(term) {
        var r =  new RegExp( '\\b(' + pregQuote(term.name.toLowerCase()) + ')\\b' , 'gi' );
        var includedInFiles = false;

        $('*').each(function() {
            // Ignore codeblocks
            if (_.contains(['code', 'pre', 'a', 'script'], this.name.toLowerCase())) return;

            replaceText($, this, r, function(match) {
                // Add to files index in glossary
                if (!includedInFiles) {
                    includedInFiles = true;
                    term.files = term.files || [];
                    term.files.push(options.navigation[options.input]);
                }
                return '<a href=\''+links.toAbsolute('/GLOSSARY.html', options.base, options.output) + '#' + term.id+'\' class=\'glossary-term\' title=\''+_.escape(term.description)+'\'>'+match+'</a>';
            });
        });
    });

    return {
        html: renderDom($),
        images: toConvert
    };
}
739506
function(element) {
      // For SVG or Symbol elements, innerHTML returns `undefined` in IE.
      // Reference: https://stackoverflow.com/q/28129956/633107
      // The XMLSerializer API is supported on IE11 and is the recommended workaround.
      var serializer = new XMLSerializer();

      return Array.prototype.map.call(element.childNodes, function (child) {
        return serializer.serializeToString(child);
      }).join('');
    }
285618
function(src) {
	var canvas = document.createElement('canvas'),
		ctx = canvas.getContext('2d'),
		imgObj = new Image();
	
	imgObj.src = src;
	canvas.width = imgObj.width;
	canvas.height = imgObj.height; 
	
	ctx.drawImage(imgObj, 0, 0); 
	var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);

	for(var y = 0; y < imgPixels.height; y++){
		for(var x = 0; x < imgPixels.width; x++){
			var i = (y * 4) * imgPixels.width + x * 4;
			var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
			imgPixels.data[i] = avg; 
			imgPixels.data[i + 1] = avg; 
			imgPixels.data[i + 2] = avg;
		}
	}
	
	ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
	return canvas.toDataURL();
}
1087050
function getImageSrcHTML(node) {
	const srcAttr = getAttribute(node, 'src');
	if (!srcAttr) {
		console.warn('No "src" attribute in', node && node.open);
		return;
	}

	return srcAttr.value.value;
}
395008
def svg_asset_data_uri(asset)
      svg = asset.source.dup
      optimize_svg_for_uri_escaping!(svg)
      data = Rack::Utils.escape(svg)
      optimize_quoted_uri_escapes!(data)
      "\"data:#{asset.content_type};charset=utf-8,#{data}\""
    end
834635
function Svg(props) {
  const { title, ...rest } = props;

  if (title) {
    return (
      <svg role='img' aria-label='[title]' { ...prepare(rest) }>
        <title>{ title }</title>
        { props.children }
      </svg>
    );
  }

  return <svg { ...prepare(rest) } />;
}