copy svg4everybody into directory
351387
function copySvg4Everybody(dir) {
  gulp.src(src.svg4everybody)
    .pipe(gulp.dest(dir));
}
525736
function copyFileIntoDirectory(srcPath, destPath) {
        return ensureDestinationDirectory(destPath).then(function () {
            return new Promise(function (resolve, reject) {
                fs.readFile(srcPath, 'utf8', function (err, contents) {
                    if (!err) {
                        resolve();
                    } else {
                        reject(err);
                    }
                    fs.outputFile(destPath + '/' + path.basename(srcPath), contents, function (err) {
                        if (!err) {
                            resolve();
                        } else {
                            reject(err);
                        }
                    });
                });
            });
        });
    }
1041419
def save_figure_tofile(fig, fmt, fname):
    """"""
    root, ext = osp.splitext(fname)
    if ext == '.png' and fmt == 'image/svg+xml':
        qimg = svg_to_image(fig)
        qimg.save(fname)
    else:
        if fmt == 'image/svg+xml' and is_unicode(fig):
            fig = fig.encode('utf-8')

        with open(fname, 'wb') as f:
            f.write(fig)
1363864
def main(argv=None, force_utf8=True, patch_svg=True):
    
    if force_utf8 and sys.version_info[0] == 2:
        reload(sys)  # noqa
        sys.setdefaultencoding('utf-8')
    if patch_svg and sys.version_info[0] == 2 and sys.version_info[1] <= 6:
        mimetypes.add_type('image/svg+xml', '.svg')

    if argv is None:
        argv = sys.argv[1:]

    # Show specific errors
    if '-a' in argv or '--address' in argv:
        print('Use grip [options] <path> <address> instead of -a')
        print('See grip -h for details')
        return 2
    if '-p' in argv or '--port' in argv:
        print('Use grip [options] [<path>] [<hostname>:]<port> instead of -p')
        print('See grip -h for details')
        return 2

    # Parse options
    args = docopt(usage, argv=argv, version=version)

    # Handle printing version with -V (docopt handles --version)
    if args['-V']:
        print(version)
        return 0

    # Clear the cache
    if args['--clear']:
        clear_cache()
        return 0

    # Get password from prompt if necessary
    password = args['--pass']
    if args['--user'] and not password:
        password = getpass()

    # Export to a file instead of running a server
    if args['--export']:
        try:
            export(args['<path>'], args['--user-content'], args['--context'],
                   args['--user'], password, False, args['--wide'],
                   not args['--no-inline'], args['<address>'],
                   args['--api-url'], args['--title'], args['--quiet'])
            return 0
        except ReadmeNotFoundError as ex:
            print('Error:', ex)
            return 1

    # Parse arguments
    path, address = resolve(args['<path>'], args['<address>'])
    host, port = split_address(address)

    # Validate address
    if address and not host and port is None:
        print('Error: Invalid address', repr(address))

    # Run server
    try:
        serve(path, host, port, args['--user-content'], args['--context'],
              args['--user'], password, False, args['--wide'], False,
              args['--api-url'], args['--title'], not args['--norefresh'],
              args['--browser'], args['--quiet'], None)
        return 0
    except ReadmeNotFoundError as ex:
        print('Error:', ex)
        return 1
    except socket.error as ex:
        print('Error:', ex)
        if ex.errno == errno.EADDRINUSE:
            print('This port is in use. Is a grip server already running? '
                  'Stop that instance or specify another port here.')
        return 1
471178
async function collecticonsBundle (params) {
  const {
    dirPath,
    destFile
  } = params;

  await validateDirPath(dirPath);

  const resultFiles = await collecticonsCompile({
    dirPath,
    styleFormats: ['css'],
    styleDest: './styles',
    fontDest: './',
    fontTypes: ['woff', 'woff2'],
    previewDest: './',
    noFileOutput: true
  });

  if (resultFiles === null) return;

  // Create zip.
  let zip = new JSZip();

  // Add generated files.
  resultFiles.forEach(file => {
    zip.file(file.path, file.contents);
  });

  // Add the icons.
  const dir = await fs.readdir(dirPath);
  const svgs = await Promise.all(dir.map(async file => {
    return file.endsWith('.svg')
      ? (
        {
          path: `icons/${file}`,
          contents: await fs.readFile(path.resolve(dirPath, file))
        }
      )
      : null;
  }));

  svgs.forEach(file => {
    zip.file(file.path, file.contents);
  });

  await fs.ensureDir(path.dirname(destFile));
  await fs.writeFile(destFile, zip.generate({ base64: false, compression: 'DEFLATE' }), 'binary');
}
1302210
def _copy_or_render_source(ext, f, output_dir, render_callback,
                           skip_copy=False):
    
    # Either render a template or copy the source
    dirname = os.path.dirname(f)
    filename = os.path.basename(f)
    for pattern, target, subsd in ext.template_regexps:
        if re.match(pattern, filename):
            tgt = os.path.join(dirname, re.sub(
                pattern, target, filename))
            rw = MetaReaderWriter('.metadata_subsd')
            try:
                prev_subsd = rw.get_from_metadata_file(output_dir, f)
            except (FileNotFoundError, KeyError):
                prev_subsd = None

            render_callback(
                get_abspath(f),
                os.path.join(output_dir, tgt),
                subsd,
                only_update=ext.only_update,
                prev_subsd=prev_subsd,
                create_dest_dirs=True,
                logger=ext.logger)
            rw.save_to_metadata_file(output_dir, f, subsd)
            return tgt
    else:
        if not skip_copy:
            copy(f,
                 os.path.join(output_dir,
                              os.path.dirname(f)),
                 only_update=ext.only_update,
                 dest_is_dir=True,
                 create_dest_dirs=True,
                 logger=ext.logger)
        return f
883994
function svgShapesToPathRectToPath(attributes) {
  const x = 'undefined' !== typeof attributes.x ? parseFloat(attributes.x) : 0;
  const y = 'undefined' !== typeof attributes.y ? parseFloat(attributes.y) : 0;
  const width =
    'undefined' !== typeof attributes.width ? parseFloat(attributes.width) : 0;
  const height =
    'undefined' !== typeof attributes.height
      ? parseFloat(attributes.height)
      : 0;
  const rx =
    'undefined' !== typeof attributes.rx
      ? parseFloat(attributes.rx)
      : 'undefined' !== typeof attributes.ry ? parseFloat(attributes.ry) : 0;
  const ry =
    'undefined' !== typeof attributes.ry ? parseFloat(attributes.ry) : rx;

  return (
    '' +
    // start at the left corner
    'M' +
    (x + rx) +
    ' ' +
    y +
    // top line
    'h' +
    (width - rx * 2) +
    // upper right corner
    (rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx + ' ' + ry : '') +
    // Draw right side
    'v' +
    (height - ry * 2) +
    // Draw bottom right corner
    (rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx * -1 + ' ' + ry : '') +
    // Down the down side
    'h' +
    (width - rx * 2) * -1 +
    // Draw bottom right corner
    (rx || ry
      ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx * -1 + ' ' + ry * -1
      : '') +
    // Down the left side
    'v' +
    (height - ry * 2) * -1 +
    // Draw bottom right corner
    (rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx + ' ' + ry * -1 : '') +
    // Close path
    'z'
  );
}
864729
def export_graphics_to_svg(widget, filename):
    
    generator = QSvgGenerator()
    generator.setFileName(filename)
    generator.setSize(widget.size())
    generator.setViewBox(widget.rect())

    painter = QPainter()
    painter.begin(generator)
    widget.render(painter)
    painter.end()
613231
def svg_compress(image, compress='auto'):
    '''  '''

    # Check availability of svgo and cwebp
    has_compress = all((which('svgo'), which('cwebp')))
    if compress is True and not has_compress:
        raise RuntimeError('Compression is required, but svgo or cwebp are not installed')
    else:
        compress = (compress is True or compress == 'auto') and has_compress

    # Compress the SVG file using SVGO
    if compress:
        cmd = 'svgo -i - -o - -q -p 3 --pretty --disable=cleanupNumericValues'
        try:
            pout = subprocess.run(cmd, input=image.encode('utf-8'), stdout=subprocess.PIPE,
                                  shell=True, check=True, close_fds=True).stdout
        except OSError as e:
            from errno import ENOENT
            if compress is True and e.errno == ENOENT:
                raise e
        else:
            image = pout.decode('utf-8')

    # Convert all of the rasters inside the SVG file with 80% compressed WEBP
    if compress:
        new_lines = []
        with StringIO(image) as fp:
            for line in fp:
                if "image/png" in line:
                    tmp_lines = [line]
                    while "/>" not in line:
                        line = fp.readline()
                        tmp_lines.append(line)
                    content = ''.join(tmp_lines).replace('\n', '').replace(
                        ',  ', ',')

                    left = content.split('base64,')[0] + 'base64,'
                    left = left.replace("image/png", "image/webp")
                    right = content.split('base64,')[1]
                    png_b64 = right.split('"')[0]
                    right = '"' + '"'.join(right.split('"')[1:])

                    cmd = "cwebp -quiet -noalpha -q 80 -o - -- -"
                    pout = subprocess.run(
                        cmd, input=base64.b64decode(png_b64), shell=True,
                        stdout=subprocess.PIPE, check=True, close_fds=True).stdout
                    webpimg = base64.b64encode(pout).decode('utf-8')
                    new_lines.append(left + webpimg + right)
                else:
                    new_lines.append(line)
        lines = new_lines
    else:
        lines = image.splitlines()

    svg_start = 0
    for i, line in enumerate(lines):
        if '<svg ' in line:
            svg_start = i
            continue

    image_svg = lines[svg_start:]  # strip out extra DOCTYPE, etc headers
    return ''.join(image_svg)
87425
function missingGlyphs(glyphs, svgDir, cb) {
  async.reject(glyphs, function(glyph, cb) {
    var filenames = glyph.filenames().map(function(filename) {
      return svgDir + '/' + filename;
    });
    async.every(filenames, fs.exists, cb);
  }, cb);
}
767387
function (src, x, y, width, height) {
		var attribs = {
				preserveAspectRatio: NONE
			},
			elemWrapper;

		// optional properties
		if (arguments.length > 1) {
			extend(attribs, {
				x: x,
				y: y,
				width: width,
				height: height
			});
		}

		elemWrapper = this.createElement('image').attr(attribs);

		// set the href in the xlink namespace
		if (elemWrapper.element.setAttributeNS) {
			elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
				'href', src);
		} else {
			// could be exporting in IE
			// using href throws "not supported" in ie7 and under, requries regex shim to fix later
			elemWrapper.element.setAttribute('hc-svg-href', src);
	}

		return elemWrapper;
	}
1261724
def svg(opts = {})
      key   = Args::EmbedKey.new.validate_key(opts[:key])
      range = Args::CardRange.new(opts[:range], deck_size: @deck_size)
      paint = Args::Paint.new(@custom_colors).load!(opts, expand_by: @deck_size, layout: @layout)
      box   = Args::Box.new(self, { width: :native, height: :native }).load!(opts, expand_by: @deck_size, layout: @layout, dpi: @dpi)
      adjust = Args::EmbedAdjust.new.load!(opts, expand_by: @deck_size, layout: @layout, dpi: @dpi)
      trans = Args::Transform.new.load!(opts, expand_by: @deck_size, layout: @layout, dpi: @dpi)
      ifile = Args::InputFile.new.load!(opts, expand_by: @deck_size, layout: @layout, dpi: @dpi)
      svg_args = Args::SvgSpecial.new.load!(opts, expand_by: @deck_size, layout: @layout, dpi: @dpi)
      rule = { type: :svg, file: ifile, box: box, paint: paint, trans: trans,
               adjust: adjust, svg_args: svg_args }
      rule[:draw] = Proc.new do |card, x, y|
        i = card.index
        b = box[i]
        b.x, b.y = x, y
        Dir.chdir(@img_dir) do
          card.svg(ifile[i].file, svg_args[i], b, paint[i], trans[i])
        end
      end
      @rules[key] = rule
    end
1303852
def dot(src, **kw):
    
    cmd = "dot -T%s" % kw.pop('T', 'svg')
    for k, v in list(kw.items()):
        if v is True:
            cmd += " -%s" % k
        else:
            cmd += " -%s%s" % (k, v)

    return pipe(cmd, to_bytes(src))
415581
function createD3Tree(root, config){

	config = config || {};

	var fileRoot = config.root || '';

	var width = $(window).width();
	var height = $(window).height();
	var cluster = d3.layout.cluster().size([height , width - 220]);
	var diagonal = d3.svg.diagonal().projection(function(d) { return [d.y, d.x]; });

	var nodes = cluster.nodes(root);
	var links = cluster.links(nodes);

	var x = d3.scale.linear().domain([0, width]).range([width, 0]);
	var y = d3.scale.linear().domain([0, height]).range([height, 0]);
	
	var zoom = d3.behavior.zoom().x(x).y(y)
		.scaleExtent([0.1, 2.5])
		.on("zoom", function(a, b, c) {
			var t = zoom.translate();
			svg.attr("transform", "translate(" + (t[0]) + "," + (t[1]) + ") scale( " + zoom.scale() + ")");
		});

	var svg = d3
		.select("#canvas")
		.append("svg")
		.call(zoom)
		.attr("width", width)
		.attr("height", height)
		.append("g");

	d3.select(self.frameElement).style("height", height + "px");

	var link = svg.selectAll(".link")
		.data(links)
		.enter().append("path")
		.attr("class", "link")
		.attr("d", diagonal);

	svg.selectAll(".link").filter(function(d, i){
		return !d.target.isDecision && !d.target.isChance && !d.target.name;
	}).remove();

	var node = svg.selectAll(".node")
		.data(nodes)
		.enter().append("g")
		.attr("class", "step")
		.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

	svg.selectAll(".step").filter(function(d, i){
		return !d.isDecision && !d.isChance && !d.name;
	}).remove();

	svg.selectAll(".step").filter(function(d, i){
		return d.isDecision;
	}).attr("class", "decision");

	svg.selectAll(".step").filter(function(d, i){
		return d.isChanceRoot;
	}).attr("class", "chanceRoot");

	svg.selectAll(".step").filter(function(d, i){
		return d.isDecisionRoot;
	}).attr("class", "decisionRoot");

	svg.selectAll(".step").filter(function(d, i){
		return d.isChance;
	}).attr("class", "chance");

	svg.selectAll(".step").filter(function(d, i){
		return d.isActive;
	}).classed('active',true);

	svg.selectAll(".active")
		.filter(function(d, i){
			return d.isFailed;
		})
		.classed('fail',true);

	var tooltip = d3.select("#canvas")
		.append("div")
		.attr("class", "tooltip")
		.style("position", "absolute")
		.style("z-index", "10")
		.style("visibility", "hidden")
		.text("");

	var tooltipText = tooltip.append("div");
	var tooltipImg = tooltip.append("img");

	node.append("circle").attr("r", 8);

	svg.selectAll(".step")
		.filter(function(d, i){
			var _this = this;
			var failedScreenshot;

			if(d.screenshot && d.screenshot.original){
				d.originalScreenshot = d.screenshot.original;
				if(d.screenshot.failure){
					d.failedScreenshot = d.screenshot.failure;
					d.latestScreenshot = d.screenshot.latest;  
					_this.setAttribute("class", _this.className.baseVal + ' screenshotFail');
				}
			}
			return !!d.screenshot;
		})
		.classed('screenshot',true)
		.on("mouseover", function(e){
			$( "body" ).trigger({
				type:"screenshot",
				name: e.name,
				src: e.screenshot.src,
				diff: e.failedScreenshot,
				latest: e.latestScreenshot,
				original: e.originalScreenshot,
				element: this
			});
		});

	var dy = !!window.chrome ? 6 : 22;

	node.append("text")
		.attr("dx", function(d,e, f) { return d.isBranchRoot ? 8 : d.children ? -15 : 15; })
		.attr("dy", function(d) { return d.isBranchRoot ? 22 : d.children ? dy  : dy ; })
		.attr("class", function(d) { return d.isDecisionRoot ? 'text decisiontext' : d.isChanceRoot ? 'text chancetext' : d.children ? 'text steptext' : 'text endtext'; })
		.attr("transform",  function(d) { return (d.children && !d.isBranchRoot) ? "rotate(330)" : "rotate(0)"; })
		.text(function(d) { return d.name.replace('.json', ''); });

	zoom.scale(1);
	zoom.translate([50, 50]);
	zoom.event(svg);
}
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
    };
}
126587
def copy_figure(self):
        """"""
        if self.fmt in ['image/png', 'image/jpeg']:
            qpixmap = QPixmap()
            qpixmap.loadFromData(self.fig, self.fmt.upper())
            QApplication.clipboard().setImage(qpixmap.toImage())
        elif self.fmt == 'image/svg+xml':
            svg_to_clipboard(self.fig)
        else:
            return

        self.blink_figure()
585919
function copyTemplateDir (srcDir, outDir, vars, cb) {
  if (!cb) {
    if (!vars) vars = noop
    cb = vars
    vars = {}
  }

  assert.equal(typeof srcDir, 'string')
  assert.equal(typeof outDir, 'string')
  assert.equal(typeof vars, 'object')
  assert.equal(typeof cb, 'function')

  // create directory
  mkdirp(outDir, function (err) {
    if (err) return cb(err)

    const rs = readdirp({ root: srcDir })
    const streams = []
    const createdFiles = []

    // create a new stream for every file emitted
    rs.on('data', function (file) {
      createdFiles.push(path.join(outDir, maxstache(removeUnderscore(file.path), vars)))
      streams.push(writeFile(outDir, vars, file))
    })

    // delegate errors & close streams
    eos(rs, function (err) {
      if (err) return cb(err)
      parallel(streams, function (err) {
        if (err) return cb(err)
        cb(null, createdFiles)
      })
    })
  })
}