Prepare screenshot filename for use with phantomcss.
        ie, append 'diff' to the end of the file if a baseline exists
489598
def _build_filepath_for_phantomcss(filepath):
    
    try:
        if os.path.exists(filepath):
            new_root = '.'.join((os.path.splitext(filepath)[0], 'diff'))
            ext = os.path.splitext(filepath)[1]
            diff_filepath = ''.join((new_root, ext))
            if os.path.exists(diff_filepath):
                print 'removing stale diff: {0}'.format(diff_filepath)
                os.remove(diff_filepath)
            return diff_filepath
        else:
            return filepath
    except OSError, e:
        print e
666246
def _candidate_filenames():
    
    while True:
        random_stub = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for _ in range(5)
        ])
        yield 'specktre_%s.png' % random_stub
1147081
public boolean compareOneScreenshot(File baseImg, File targetImg, int rows, int columns) {

        boolean match = true;
        BufferedImage[][] baseBfImg = splitImage(baseImg, rows, columns);
        BufferedImage[][] targetBfImg = splitImage(targetImg, rows, columns);

        BufferedImage[][] diffImg = new BufferedImage[rows][columns];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {

                byte[] baseImgBytes = toByteArray(baseBfImg[i][j]);
                byte[] targetImgBytes = toByteArray(targetBfImg[i][j]);

                if (Arrays.equals(baseImgBytes, targetImgBytes)) {
                    diffImg[i][j] = darken(targetBfImg[i][j]);
                } else {
                    match = false;
                    diffImg[i][j] = targetBfImg[i][j];
                }
            }
        }

        if (match) {
            LOG.info("screenshot.match", targetImg.getName());
        } else {
            LOG.error("screenshot.unmatch", targetImg.getName());
            writeDiffImg(targetImg, diffImg);
        }

        return match;
    }
608320
function getScreenshotName(basePath) {
    return function(context) {
        var testName = context.test.title.replace(/\s+/g, '-');
        var browserName = context.browser.name;
        var browserVersion = parseInt(context.browser.version, 10);
        var subDir = browserName + '_v' + browserVersion;
        var fileName = testName + '.png';

        return path.join(basePath, subDir, fileName);
    };
}
1133993
def create_screenshot(name, data, path, font, is_module):
    
    desktop_color = get_color_for_name(name)

    # if this screenshot is for a module then add modules name etc
    if is_module:
        data.append(
            {"full_text": name.split("-")[0], "color": desktop_color, "separator": True}
        )
        data.append(
            {"full_text": "py3status", "color": COLOR_PY3STATUS, "separator": True}
        )

    img = Image.new("RGB", (WIDTH, HEIGHT), COLOR_BG)
    d = ImageDraw.Draw(img)

    # top bar
    d.rectangle((0, 0, WIDTH, TOP_BAR_HEIGHT), fill=desktop_color)
    x = X_OFFSET

    # add text and separators
    for part in reversed(data):
        text = part.get("full_text")
        color = part.get("color", COLOR)
        background = part.get("background")
        separator = part.get("separator")
        urgent = part.get("urgent")

        # urgent background
        if urgent:
            color = COLOR_URGENT
            background = COLOR_URGENT_BG

        size = font.getsize(text)

        if background:
            d.rectangle(
                (
                    WIDTH - x - (size[0] // SCALE),
                    TOP_BAR_HEIGHT + PADDING,
                    WIDTH - x - 1,
                    HEIGHT - PADDING,
                ),
                fill=background,
            )

        x += size[0] // SCALE

        txt = Image.new("RGB", size, background or COLOR_BG)
        d_text = ImageDraw.Draw(txt)
        d_text.text((0, 0), text, font=font, fill=color)
        # resize to actual size wanted and add to image
        txt = txt.resize((size[0] // SCALE, size[1] // SCALE), Image.ANTIALIAS)
        img.paste(txt, (WIDTH - x, TOP_BAR_HEIGHT + PADDING))

        if separator:
            x += SEP_PADDING_RIGHT
            d.line(
                (
                    (WIDTH - x, TOP_BAR_HEIGHT + PADDING),
                    (WIDTH - x, TOP_BAR_HEIGHT + 1 + PADDING + FONT_SIZE),
                ),
                fill=COLOR_SEP,
                width=1,
            )
            x += SEP_PADDING_LEFT

    img.save(os.path.join(path, "%s.png" % name))
    print(" %s.png" % name)
1152748
def png_workaround(self, filepath, width=1200, height=800):
        
        sys.stdout = sys.__stdout__
        cmd.feedback('disable', 'movie', 'everything')
        cmd.viewport(width, height)
        cmd.zoom('visible', 1.5)  # Adapt the zoom to the viewport
        cmd.set('ray_trace_frames', 1)  # Frames are raytraced before saving an image.
        cmd.mpng(filepath, 1, 1)  # Use batch png mode with 1 frame only
        cmd.mplay()  # cmd.mpng needs the animation to 'run'
        cmd.refresh()
        originalfile = "".join([filepath, '0001.png'])
        newfile = "".join([filepath, '.png'])

        #################################################
        # Wait for file for max. 1 second and rename it #
        #################################################

        attempts = 0
        while not os.path.isfile(originalfile) and attempts <= 10:
            sleep(0.1)
            attempts += 1
        if os.name == 'nt':  # In Windows, make sure there is no file of the same name, cannot be overwritten as in Unix
            if os.path.isfile(newfile):
                os.remove(newfile)
        os.rename(originalfile, newfile)  # Remove frame number in filename

        #  Check if imagemagick is available and crop + resize the images
        if subprocess.call("type convert", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0:
            attempts, ecode = 0, 1
            # Check if file is truncated and wait if that's the case
            while ecode != 0 and attempts <= 10:
                ecode = subprocess.call(['convert', newfile, '/dev/null'], stdout=open('/dev/null', 'w'),
                                        stderr=subprocess.STDOUT)
                sleep(0.1)
                attempts += 1
            trim = 'convert -trim ' + newfile + ' -bordercolor White -border 20x20 ' + newfile + ';'  # Trim the image
            os.system(trim)
            getwidth = 'w=`convert ' + newfile + ' -ping -format "%w" info:`;'  # Get the width of the new image
            getheight = 'h=`convert ' + newfile + ' -ping -format "%h" info:`;'  # Get the hight of the new image
            newres = 'if [ "$w" -gt "$h" ]; then newr="${w%.*}x$w"; else newr="${h%.*}x$h"; fi;'  # Set quadratic ratio
            quadratic = 'convert ' + newfile + ' -gravity center -extent "$newr" ' + newfile  # Fill with whitespace
            os.system(getwidth + getheight + newres + quadratic)
        else:
            sys.stderr.write('Imagemagick not available. Images will not be resized or cropped.')
824857
function getAfterScreenshotStep(step) {
        var template = grunt.file.read(templates.screenshotTemplate),
            stepTemplate;
        stepTemplate = grunt.template.process(template, {
            data: {
                screenshot: step.embeddings && step.embeddings[0] ? step.embeddings[0].data : ''
            }
        });
        return stepTemplate;
    }
377044
function (url, baseDir, done) {
  resolve(url, {
    basedir: baseDir,
    extensions: [ '.scss', '.sass', '.css' ],
    pathFilter: function (pkg, absPath, relativePath) {
      var globbedPath = buildSassGlob(absPath);
      var paths = glob.sync(globbedPath);
      var resolvedPath = paths && paths[0];
      if (resolvedPath) {
        return path.join(path.dirname(relativePath), path.basename(resolvedPath));
      }
    }
  }, function (err, file) {
    if (err) return done(err);

    // Strip the extension so .css gets evaluated properly as .scss
    file = file.replace(/\.(js|(sa|sc|c)ss)$/, '');
    done(null, file);
  });
}
1202264
def diff_prettyHtml(self, diffs):
    
    html = []
    for (op, data) in diffs:
      text = (data.replace("&", "&amp;").replace("<", "&lt;")
                 .replace(">", "&gt;").replace("\n", "&para;<br>"))
      if op == self.DIFF_INSERT:
        html.append("<ins style=\"background:#e6ffe6;\">%s</ins>" % text)
      elif op == self.DIFF_DELETE:
        html.append("<del style=\"background:#ffe6e6;\">%s</del>" % text)
      elif op == self.DIFF_EQUAL:
        html.append("<span>%s</span>" % text)
    return "".join(html)
37689
function compareSnapshotCommand() {
  Cypress.Commands.add('compareSnapshot', (name, errorThreshold = 0.0) => {
    // get image title from the 'type' environment variable
    let title = 'actual';
    if (Cypress.env('type') === 'base') {
      title = 'base';
    }

    // take snapshot
    cy.screenshot(`${name}-${title}`);

    // run visual tests
    if (Cypress.env('type') === 'actual') {
      const options = {
        fileName: name,
        specDirectory: Cypress.spec.name,
      };
      cy.task('compareSnapshotsPlugin', options).then((results) => {
        if (results.percentage > errorThreshold) throw new Error(`${name} images are different`);
      });
    }
  });
}
1192598
function() {
      'use strict';
      var filesToCopy = {
         'widget.json': 'widget.json',
         'gitignore': '.gitignore',
         'spec/spec_runner.html': 'spec/spec_runner.html',
         'spec/spec_runner.js': 'spec/spec_runner.js',
         'spec/widget.spec.js': 'spec/' + this.placeholder.name + '.spec.js'
      };
      var integrationTechnology = this.placeholder.laxarIntegrationTechnology;
      var widget = !this.options.activity;

      if( widget && integrationTechnology !== 'react' ) {
         filesToCopy[ 'default.theme/widget.html' ] = 'default.theme/' + this.placeholder.name + '.html';
      }
      if( widget ) {
         filesToCopy[ 'default.theme/css/widget.css' ] = 'default.theme/css/' + this.placeholder.name + '.css';
      }

      if( integrationTechnology === 'plain' ) {
         if( !widget ) {
            filesToCopy[ 'controller.plain.activity.js' ] = this.placeholder.name + '.js';
         }
         else {
            filesToCopy[ 'controller.plain.widget.js' ] = this.placeholder.name + '.js';
         }
      }
      else if( integrationTechnology === 'angular' ) {
         filesToCopy[ 'controller.angular.js' ] = this.placeholder.name + '.js';
      }
      else if( integrationTechnology === 'react' ) {
         filesToCopy[ 'controller.react.jsx' ] = this.placeholder.name + '.jsx';
      }

      if( this.placeholder.infrastructure ) {
         filesToCopy[ 'README.md' ] = 'README.md';
         if( widget && integrationTechnology !== 'react') {
            filesToCopy[ 'bower.widget.json' ] = 'bower.json';
         }
         else if ( widget && integrationTechnology === 'react' ) {
            filesToCopy[ 'bower.react.widget.json' ] = 'bower.json';
         }
         else {
            filesToCopy[ 'bower.activity.json' ] = 'bower.json';
         }
      }
      for( var file in filesToCopy ) {
         if( filesToCopy.hasOwnProperty( file ) ) {
            this.fs.copyTpl(
               this.templatePath( file ),
               this.destinationPath(
                  path.join( this.widgetDirname, this.placeholder.name, filesToCopy[ file ] )
               ),
               this.placeholder
            );
         }
      }
   }
663067
function diffFile(existing, proposed, options) {
  let { ensureContents, exists, readChunk } = utils;
  let opts = options || {};

  let contentsA = existing.contents;
  let contentsB = proposed.contents;

  if (!contentsA && exists(existing)) {
    contentsA = readChunk(existing.path, 0, 4 + 4096);
  }

  if (!contentsB && exists(proposed)) {
    contentsB = readChunk(proposed.path, 0, 4 + 4096);
  }

  if ((contentsA && isBuffer(contentsA)) || (contentsB && isBuffer(contentsB))) {
    return diffBinary(existing, proposed);
  }

  ensureContents(existing);
  ensureContents(proposed);
  if (opts.diffText === true) {
    return diffText(existing.contents.toString(), proposed.contents.toString(), opts);
  }
  return diffChars(existing.contents.toString(), proposed.contents.toString(), opts);
}
5704
def diffs
      params[:sort] ||= "image_file_size desc"
      @diffs = UiChanged::Screenshot.search(params[:search]).not_in_ignored.where(:diff_found => true).paginate(:page => params[:page],
                                                                                  :per_page => params[:per_page],
                                                                                  :order => params[:sort])
      @all_screenshots = []
      @diffs.each do |diff|
        control = UiChanged::Screenshot.find(diff.control_id)
        test = UiChanged::Screenshot.find(diff.test_id)
        @all_screenshots << UiChanged::AllScreenshot.new(control, test, diff)
      end
    end
709917
def tweak_css(repo_dir):
    ''''''
    print_msg("* don't capitalize titles (no uppercase headings)")
    files = [
        'beige.css', 'black.css', 'blood.css', 'league.css', 'moon.css',
        'night.css', 'serif.css', 'simple.css', 'sky.css', 'solarized.css',
        'white.css',
    ]
    line = '  text-transform: uppercase;'
    for file_ in files:
        update_or_append_line(filename=flo('{repo_dir}/css/theme/{file_}'),
                              prefix=line, new_line=flo('/*{line}*/'))

    print_msg('* images without border')
    data = [
        {'file': 'beige.css',     'line': '  border: 4px solid #333;'},
        {'file': 'black.css',     'line': '  border: 4px solid #fff;'},
        {'file': 'blood.css',     'line': '  border: 4px solid #eee;'},
        {'file': 'league.css',    'line': '  border: 4px solid #eee;'},
        {'file': 'moon.css',      'line': '  border: 4px solid #93a1a1;'},
        {'file': 'night.css',     'line': '  border: 4px solid #eee;'},
        {'file': 'serif.css',     'line': '  border: 4px solid #000;'},
        {'file': 'simple.css',    'line': '  border: 4px solid #000;'},
        {'file': 'sky.css',       'line': '  border: 4px solid #333;'},
        {'file': 'solarized.css', 'line': '  border: 4px solid #657b83;'},
        {'file': 'white.css',     'line': '  border: 4px solid #222;'},
    ]
    for item in data:
        file_ = item['file']
        lines = [item['line'], ]
        lines.extend(['  box-shadow: 0 0 10px rgba(0, 0, 0, 0.15); }',
                      '  box-shadow: 0 0 20px rgba(0, 0, 0, 0.55); }'])
        for line in lines:
            update_or_append_line(filename=flo('{repo_dir}/css/theme/{file_}'),
                                  prefix=line, new_line=flo('/*{line}*/'))
520874
function loadPageCss(cssFile) {
    var cssFileName;

    // Eliminate the ./ on the file if present so that we can add the full path
    if (cssFile.startsWith("./")) {
        cssFile = cssFile.substring(2);
    }

    if (cssFile.startsWith(UpdaterSingleton.currentAppPath())) {
        cssFileName = cssFile;
    } else {
        cssFileName = fs.path.join(UpdaterSingleton.currentAppPath(), cssFile);
    }

    var applicationCss;
    if (FSA.fileExists(cssFileName)) {
        FSA.readText(cssFileName, function (r) { applicationCss = r; });

        // Add New CSS to Current Page
        var f = frameCommon.topmost();
        if (f && f.currentPage) {
            f.currentPage._resetCssValues();
            f.currentPage._styleScope = new styleScope.StyleScope();
            //noinspection JSUnusedAssignment
            f.currentPage._addCssInternal(applicationCss, cssFileName);
            f.currentPage._refreshCss();
        }
    }
}
1186645
function cssTemplate (params) {
  // Localize parameters
  var items = params.items;
  var options = params.options;
  var tmplParams = {
    sprite: null,
    retina: null,
    items: [],
    options: options
  };

  var classFn = function (name, sep) {
    if (options.cssClass) {
      return '.' + cssesc(options.cssClass + sep + name, {isIdentifier: true});
    }
    else {
      return '.icon' + cssesc(sep + name, {isIdentifier: true});
    }
  };

  // Add class to each of the options
  items.forEach(function saveClass (item) {
    if (item.type === 'sprite') {
      item['class'] = classFn('', '');
      tmplParams.sprite = item;
    }
    else if (item.type === 'retina') {
      item['class'] = classFn('', '');
      tmplParams.retina = item;
    }
    else {
      item['class'] = classFn(item.name, '-');
      tmplParams.items.push(item);
    }
  });
  // Render and return CSS
  var tmplFile = options.template ?
    fs.readFileSync(path.resolve(process.cwd(), options.template), 'utf8') :
    tmpl[options.processor];
  var css = mustache.render(tmplFile, tmplParams);
  return css;
}
160618
function(css,retinaobject,properties){
        var _tmpSlice = retinaobject.slicekey;
        var _retinaCSSCode = "";
        var _sprite ;
            _retinaCSSCode +='\n\n@media only screen and (-webkit-min-device-pixel-ratio: 1.5),only screen and (min--moz-device-pixel-ratio: 1.5),only screen and (min-resolution: 240dpi){';
            for(var key in _tmpSlice){
                _sprite = _tmpSlice[key].code;
                _retinaCSSCode += _tmpSlice[key].className;
                _retinaCSSCode += "{background-image:url(.";
                _retinaCSSCode += _outSpritePath.slice(_outSpritePath.lastIndexOf("/"),_outSpritePath.length);
                _retinaCSSCode += "/";
                _retinaCSSCode += _outSpriteName.replace(".png","@2x.png")+");";
                _retinaCSSCode += "background-position: -";
                _retinaCSSCode += (_sprite.x) / 2;
                _retinaCSSCode += "px -";
                _retinaCSSCode += (_sprite.y) / 2;
                _retinaCSSCode += "px;background-size:";
                _retinaCSSCode += (properties.width) / 2 + 'px;}';
            }
            _retinaCSSCode += '\n}\n';
        css = css + _retinaCSSCode;
        return css;
    }