Minify assets in format
962830
def minify(asset, format)
      asset = asset.to_s
      # Minify JS
      return Uglifier.compile(asset) if format.eql?("js")
      # Minify CSS
      return YUI::CssCompressor.new.compress(asset) if format.eql?("css")
      # Return string representation if not minimizing
      return asset
    end
687645
def with_mhtml(css, asset_url)
      paths, index = {}, 0
      css = css.gsub(EMBED_REPLACER) do |url|
        i = paths[$1] ||= "#{index += 1}-#{File.basename($1)}"
        "url(mhtml:#{asset_url}!#{i})"
      end
      mhtml = paths.sort.map do |path, identifier|
        mime, contents = mime_type(path), encoded_contents(path)
        [MHTML_SEPARATOR, "Content-Location: #{identifier}\r\n", "Content-Type: #{mime}\r\n", "Content-Transfer-Encoding: base64\r\n\r\n", contents, "\r\n"]
      end
      [MHTML_START, mhtml, MHTML_END, css].flatten.join('')
    end
512194
function assetFile(filename, callback) {
      const data = {
        source: files[filename].source,
        destination: files[filename].destination || path.join(path.dirname(filename), '.')
      }
      delete files[filename]
      metalsmithAssets(data)(files, metalsmith, callback)
    }
1182945
function resize(img, width=0, height=0, type='png', quality=0.75) {
    let mime
    switch(type.toLowerCase()) {
    case 'jpg':
    case 'jpeg':
    case 'image/jpeg':
        mime = 'image/jpeg'
        break
    case 'png':
    case 'image/png':
    default:
        mime = 'image/png'
    }
    return resizePromise(img, width, height).then(
        canvas => canvas2Blob(canvas, { type: mime, quality })
        //canvas => canvas2DataUrl(canvas, { type: mime, quality })
    )
}
396392
function copyAssets(output, plugin) {
    var logger = output.getLogger();
    var pluginRoot = plugin.getPath();
    var options = output.getOptions();

    var outputRoot = options.get('root');
    var assetOutputFolder = path.join(outputRoot, 'gitbook');
    var prefix = options.get('prefix');

    var assetFolder = path.join(pluginRoot, ASSET_FOLDER, prefix);

    if (!fs.existsSync(assetFolder)) {
        return Promise();
    }

    logger.debug.ln('copy assets from theme', assetFolder);
    return fs.copyDir(
        assetFolder,
        assetOutputFolder,
        {
            deleteFirst: false,
            overwrite: true,
            confirm: true
        }
    );
}
752912
function minifycss($file)
    {
        $minifiedFileName = $this->checkIfFileWasUpdated($file);
        if ($minifiedFileName) {
            $fileContent = file_get_contents(ROOTPATH . $file);
            $cssmin = new CSSmin();
            file_put_contents(ROOTPATH . $minifiedFileName, $cssmin->run($fileContent));
            return $minifiedFileName;
        }
        return $file;
    }
812640
protected function combineMinify()
    {
        $type = $this->options['contentType']; // ease readability

        // when combining scripts, make sure all statements separated and
        // trailing single line comment is terminated
        $implodeSeparator = ($type === self::TYPE_JS) ? "\n;" : '';

        // allow the user to pass a particular array of options to each
        // minifier (designated by type). source objects may still override
        // these
        if (isset($this->options['minifierOptions'][$type])) {
            $defaultOptions = $this->options['minifierOptions'][$type];
        } else {
            $defaultOptions = array();
        }

        // if minifier not set, default is no minification. source objects
        // may still override this
        if (isset($this->options['minifiers'][$type])) {
            $defaultMinifier = $this->options['minifiers'][$type];
        } else {
            $defaultMinifier = false;
        }

        // process groups of sources with identical minifiers/options
        $content = array();
        $i = 0;
        $l = count($this->sources);
        $groupToProcessTogether = array();
        $lastMinifier = null;
        $lastOptions = null;
        do {
            // get next source
            $source = null;
            if ($i < $l) {
                $source = $this->sources[$i];
                $sourceContent = $source->getContent();

                // allow the source to override our minifier and options
                $minifier = $source->getMinifier();
                if (!$minifier) {
                    $minifier = $defaultMinifier;
                }
                $options = array_merge($defaultOptions, $source->getMinifierOptions());
            }
            // do we need to process our group right now?
            if ($i > 0                               // yes, we have at least the first group populated
                && (
                    ! $source                        // yes, we ran out of sources
                    || $type === self::TYPE_CSS      // yes, to process CSS individually (avoiding PCRE bugs/limits)
                    || $minifier !== $lastMinifier   // yes, minifier changed
                    || $options !== $lastOptions)) { // yes, options changed
                // minify previous sources with last settings
                $imploded = implode($implodeSeparator, $groupToProcessTogether);
                $groupToProcessTogether = array();
                if ($lastMinifier) {
                    try {
                        $content[] = call_user_func($lastMinifier, $imploded, $lastOptions);
                    } catch (Exception $e) {
                        throw new Exception("Exception in minifier: " . $e->getMessage());
                    }
                } else {
                    $content[] = $imploded;
                }
            }
            // add content to the group
            if ($source) {
                $groupToProcessTogether[] = $sourceContent;
                $lastMinifier = $minifier;
                $lastOptions = $options;
            }
            $i++;
        } while ($source);

        $content = implode($implodeSeparator, $content);

        if ($type === self::TYPE_CSS && false !== strpos($content, '@import')) {
            $content = $this->handleCssImports($content);
        }

        // do any post-processing (esp. for editing build URIs)
        if ($this->options['postprocessorRequire']) {
            require_once $this->options['postprocessorRequire'];
        }
        if ($this->options['postprocessor']) {
            $content = call_user_func($this->options['postprocessor'], $content, $type);
        }

        return $content;
    }
170636
function normalizeAssets(clientLibPath, assets) {

  var list = assets;

  // transform object to array
  if (!_.isArray(assets)) {
    list = [];
    _.keys(assets).forEach(function (assetKey) {
      var assetItem = assets[assetKey];

      // check/transform short version
      if (_.isArray(assetItem)) {
        assetItem = {
          files: assetItem
        };
      }
      if (!assetItem.base) {
        assetItem.base = assetKey;
      }
      assetItem.type = assetKey;
      list.push(assetItem);
    });
  }

  // transform files to scr-dest mapping
  list.forEach(function (asset) {

    var mapping = [];
    var flatName = typeof asset.flatten !== "boolean" ? true : asset.flatten;
    var assetPath = path.posix.join(clientLibPath, asset.base);
    var globOptions = {};
    if (asset.cwd) {
      globOptions.cwd = asset.cwd;
    }

    asset.files.forEach(function (file) {
      var fileItem = file;

      // convert simple syntax to object
      if (_.isString(file)) {
        fileItem = {
          src: file
        };
      }

      // no magic pattern -> default behaviour
      if (!glob.hasMagic(fileItem.src)) {

        // determine default dest
        if (!fileItem.dest) {
          fileItem.dest = path.posix.basename(file);
        }

        // generate full path
        fileItem.dest = path.posix.join(assetPath, fileItem.dest);
        mapping.push(fileItem);
      }

      // resolve magic pattern
      else {
        var files = glob.sync(fileItem.src, globOptions);
        var hasCwd = !!globOptions.cwd;
        var dest = fileItem.dest ? path.posix.join(assetPath, fileItem.dest) : assetPath;

        files.forEach(function (resolvedFile) {

          // check 'flatten' option -> strip dir name
          var destFile = flatName ? path.posix.basename(resolvedFile) : resolvedFile;

          var item = {
            src: resolvedFile,
            dest: path.posix.join(dest, destFile)
          };

          // check "cwd" option -> rebuild path, because it was stripped by glob.sync()
          if (hasCwd) {
            item.src = path.posix.join(globOptions.cwd, resolvedFile);
          }

          mapping.push(item);
        });
      }
    });

    asset.files = mapping;
  });

  return list;
}
258459
def minify_css_files():
    
    for k, v in CSS_FILE_MAPPING.items():
        input_files = " ".join(v["input_files"])
        output_file = v["output_file"]

        uglifyjs_command = "uglifycss {input_files} > {output_file}".format(
            input_files=input_files,
            output_file=output_file
        )
        local(uglifyjs_command)
1202345
function copyCss() {
  return gulp.src(['./src/assets/stylesheets/*.css'], {base: './src/assets/stylesheets'})
    .pipe(gulp.dest(function (file) {
      return libraryDist + '/dist/css' + file.base.slice(__dirname.length); // save directly to dist
    }));
}
1344667
private function minify($filename = false, $files, $yuicompressor, $baseDir, $width = null)
    {
        $content = '';
        if ($width === null) {
            $extra = '';
        } else {
            $extra = '--line-break '.intval($width);
        }

        foreach ($files as $file) {
            if (file_exists($baseDir.$file)) {
                $result = exec("java -jar $yuicompressor $extra $baseDir$file ");
                $content .= (defined('_MODE') && _MODE == 1 ? "/* $file */" : '')."$result\n";
                echo "\n    Add: $file";
            } else {
                echo "\n    Err: $file - not found.";
            }
        }
            //return minyfied data
        if ($filename === false) {
            return $content;
        }

            echo "\n Saving: $filename\n";
            file_put_contents($baseDir.$filename, $content);
            echo "\n Minified ..\n";
    }
1144624
function requireAssets( requireFile, assetPaths, assetUrlPaths ) {
   return function( assets ) {
      return Promise.all( Object.keys( assets ).map( key => {
         const asset = assets[ key ];

         if( ( assetPaths || [] ).indexOf( key ) >= 0 ) {
            return requireFile( asset, 'content' )
               .then( content => ( { [ key ]: { content } } ) );
         }

         if( ( assetUrlPaths || [] ).indexOf( key ) >= 0 ) {
            return requireFile( asset, 'url' )
               .then( url => ( { [ key ]: { url } } ) );
         }

         return {};
      } ) ).then( merge );
   };
}
637709
def resize!
      begin
        image = MiniMagick::Image.open(@file.path)
        image.resize("#{@width}x#{@height}")
      rescue
        # Pass on any error
      else
        image.write(@file.path) rescue nil
      end
    end
136807
function gulpResourceHints (opt) {
  var options = helpers.options(opt)
  helpers.reset()

  return new Transform({
    objectMode: true,
    transform: function (file, enc, cb) {
      if (file.isNull()) {
        helpers.logger(PLUGIN_NAME, 'no file', true)

        cb(null, file)
        return
      }

      var fileContents = String(file.contents)

      // Gather assets, keep unique values
      // Using https://www.npmjs.com/package/list-assets
      var assets = new Set(listAssets.html(
        fileContents,
        {
          absolute: true,
          protocolRelative: true
        }
      ).map(ob => ob.url))

      if (assets.size < 0) {
        // Skip file: no static assets
        cb(null, file)
        return
      }

      if (!helpers.hasInsertionPoint(file)) {
        helpers.logger(PLUGIN_NAME, 'Skipping file: no <head> or token found', true)
        cb(null, file)
        return
      }

      // Future feature! Gotta do more stream madness
      // if (options.getCSSAssets) {
      //   for (var k = 0, cssLen = assets.length; k < cssLen; k++) {
      //     if (assets[k].endsWith('.css') || assets[k].endsWith('.CSS')) {
      //       assets.push(listAssets.css(
      //         fileContents
      //       ))
      //     }
      //   }
      // }

      // Build resource hints based on user-selected assets
      var data = ['']

      assets.forEach((aVal, aKey, set) => {
        Object.keys(options.paths).forEach((key) => {
          if (options.paths[key] === '') {
            return
          }
          data.push(helpers.buildResourceHint(key, aVal, options.paths[key]))
        })
      })

      data = data.reduce((a, b) => a + b)
      var newFile = helpers.writeDataToFile(file, data, options.pageToken)

      if (!newFile) {
        helpers.logger(PLUGIN_NAME + ': Could not write data to file. ' + file.relative)
        cb(null, file)
        return
      } else {
        file.contents = new Buffer(newFile)
      }

      cb(null, file)
    }
  })
}
1158875
function stringify (elements, options = {}) {
  const {
    embedAssets = true,
    assetPath = '',
    baseUrl = '',
    assetLoader = (filename) => fs.readFileAsync(filename, 'utf-8')
  } = options

  const [headWrappers, modifiers, assets] = extractTypes(elements, [HeadWrapper, PageModifier, Asset])

  const latestById = {}
  headWrappers.forEach(w => {
    if (w.options.id) {
      latestById[w.options.id] = w
    }
  })

  const bodyClassesMap = {}
  modifiers
    .filter(m => m.options.type === 'body-classed')
    .forEach(m => {
      bodyClassesMap[m.options.class] = m.options.classed
    })

  const bodyClass = Object.keys(bodyClassesMap)
    .filter(c => bodyClassesMap[c])
    .join(' ')

  const headElements = headWrappers
    .filter(w => w.options.id ? w === latestById[w.options.id] : true)
    .map(w => w.element)
    .map(e => e.stringify ? e.stringify() : (isString(e) ? e : ''))
    .join('')

  const bodyElements = elements
    .map(e => e !== undefined && e.stringify ? e.stringify() : (isString(e) ? e : ''))
    .join('')

  // only keep unique assets
  const uniqueAssetsMap = {}
  const anonymousAssets = []
  assets.forEach(asset => {
    if (asset.url) {
      uniqueAssetsMap[asset.url] = asset
    } else {
      anonymousAssets.push(asset)
    }
  })
  const uniqueAssets = Object.keys(uniqueAssetsMap).map(k => uniqueAssetsMap[k])

  const exportAssets = []

  const stylesheets = Promise.all(uniqueAssets.filter(a => a.url.endsWith('.css')).map(s => {
    if (embedAssets) {
      if (s.content) {
        return `<style>${s.content}</style>`
      } else {
        return assetLoader(s.filename)
          .then(content => `<style>${content}</style>`)
      }
    } else {
      exportAssets.push(s)
      return `<link rel="stylesheet" href="${path.join(baseUrl, assetPath, s.url)}"></link>`
    }
  }))

  const anonymousStylesheets = anonymousAssets.filter(a => a.type === 'css').map(s => {
    if (s.content) {
      return `<style>${s.content}</style>`
    } else {
      return assetLoader(s.filename)
        .then(content => `<style>${content}</style>`)
    }
  })

  const scripts = Promise.all(uniqueAssets.filter(a => a.url.endsWith('.js')).map(s => {
    if (embedAssets) {
      if (s.content) {
        return `<script>${s.content}</script>`
      } else {
        return assetLoader(s.filename)
          .then(content => `<script>${content}</script>`)
      }
    } else {
      exportAssets.push(s)
      return `<script src="${path.join(baseUrl, assetPath, s.url)}"></script>`
    }
  }))

  const anonymousScripts = anonymousAssets.filter(a => a.type === 'js').map(s => {
    if (s.content) {
      return `<script>${s.content}</script>`
    } else {
      return assetLoader(s.filename)
        .then(content => `<script>${content}</script>`)
    }
  })

  // Also export any un-embeddable assets
  uniqueAssets.forEach(asset => {
    if (!asset.url.endsWith('.js') && !asset.url.endsWith('.css')) {
      exportAssets.push(asset)
    }
  })

  return Promise.all([stylesheets, scripts])
    .spread((stylesheets, scripts) => {
      const bodyClasses = 'qm-body-font' + (bodyClass ? ' ' + bodyClass : '')
      const head = `<head>${stylesheets.join('')}${anonymousStylesheets.join('')}${headElements}</head>`
      const body = `<body class="${bodyClasses}">${bodyElements}${scripts.join('')}${anonymousScripts.join('')}</body>`
      const html = `<!DOCTYPE html>\n<html>\n${head}\n${body}</html>`
      return {
        html: html,
        assets: exportAssets
      }
    })
}
261385
def concatenate_and_tag_assets(paths, variant=nil)
      stylesheets = [paths].flatten.map do |css_path|
        contents = read_binary_file(css_path)
        contents.gsub(EMBED_DETECTOR) do |url|
          ipath, cpath = Pathname.new($1), Pathname.new(File.expand_path(css_path))
          is_url = URI.parse($1).absolute?
          is_url ? url : "url(#{construct_asset_path(ipath, cpath, variant)})"
        end
      end
      stylesheets.join("\n")
    end
112909
function resizeTexture(texture, width, height) {
  const oldWidth = texture.width;
  const oldHeight = texture.height;
  const oldPixels = readPixelsToBuffer(texture, {});

  texture.resize({width, height});

  texture.setSubImageData({
    data: oldPixels,
    x: 0,
    y: height - oldHeight,
    width: oldWidth,
    height: oldHeight,
    parameters: DEFAULT_TEXTURE_PARAMETERS
  });

  texture.generateMipmap();

  oldPixels.delete();
  return texture;
}