text:
"""Low level command interface to LVM"""

import os
import csv
import logging
from subprocess import Popen, PIPE, list2cmdline, call
from cStringIO import StringIO

LOG = logging.getLogger(__name__)

class CalledProcessError(Exception):
    """This exception is raised when a process run by check_call() returns
    a non-zero exit status.  The exit status will be stored in the
    returncode attribute."""
    def __init__(self, returncode, cmd):
        self.returncode = returncode
        self.cmd = cmd
        Exception.__init__()

    def __str__(self):
        return "Command '%s' returned non-zero exit status %d" % \
                (self.cmd, self.returncode)

def check_call(*popenargs, **kwargs):
    """Run command with arguments.  Wait for command to complete.  If
    the exit code was zero then return, otherwise raise
    CalledProcessError.  The CalledProcessError object will have the
    return code in the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    check_call(["ls", "-l"])
    """
    LOG.debug("%s", list2cmdline(popenargs[0]))
    retcode = call(*popenargs, **kwargs)
    cmd = kwargs.get("args")
    if cmd is None:
        cmd = popenargs[0]
    if retcode:
        raise CalledProcessError(retcode, cmd)
    return retcode

__all__ = [
    'is_lvm_device',
    'lvs',
    'vgs',
    'pvs',
    'lvcreate',
    'lvsnapshot',
    'lvremove',
    'mount',
    'unmount',
    'lvm_dict',
    'lvm_cmd',
]

PVS_ATTRIBUTES = [
    'pv_fmt',
    'pv_uuid',
    'pv_size',
    'dev_size',
    'pv_free',
    'pv_used',
    'pv_name',
    'pv_attr',
    'pv_pe_count',
    'pv_pe_alloc_count',
    'pv_tags',
    # segment info introduces duplicate records
    # (with differing seginfo data)
    #'pvseg_start',
    #'pvseg_size',
    'pe_start',
    'vg_name'
]

VGS_ATTRIBUTES = [
    'vg_fmt',
    'vg_uuid',
    'vg_name',
    'vg_attr',
    'vg_size',
    'vg_free',
    'vg_sysid',
    'vg_extent_size',
    'vg_extent_count',
    'vg_free_count',
    'max_lv',
    'max_pv',
    'pv_count',
    'lv_count',
    'snap_count',
    'vg_seqno',
    'vg_tags'
]

LVS_ATTRIBUTES = [
    'lv_uuid',
    'lv_name',
    'lv_attr',
    'lv_major',
    'lv_minor',
    'lv_kernel_major',
    'lv_kernel_minor',
    'lv_size',
    'seg_count',
    'origin',
    'snap_percent',
    'copy_percent',
    'move_pv',
    'lv_tags',
# segment information break 1:1 mapping
#    'segtype',
#    'stripes',
#    'stripesize',
#    'chunksize',
#   'seg_start',
#   'seg_size',
#   'seg_tags',
#   'devices',
#    'regionsize',
    'mirror_log',
    'modules',
    'vg_name'
]

def is_lvm_device(dev_path):
    """Check if a device path refers to an LVM physical volume
    :param dev_path: path to the device to check
    :returns: True if dev_path is a pv and False otherwise
    """
    args = [
        'pvs',
        '--noheadings',
        '--options', 'pv_name',
    ]
    data = str(lvm_cmd(*args))
    devices = [line.strip() for line in data.splitlines()]
    return dev_path in devices

def pvs(name=None):
    """List available physical volumes and return a dictionary of attributes"""
    args = [
        'pvs',
        '--noheadings',
        '--nosuffix',
        '--separator=,',
        '--units=b',
        '--options', ','.join(PVS_ATTRIBUTES)
    ]
    if name:
        args.append(name)
    data = lvm_cmd(*args)
    return lvm_dict(PVS_ATTRIBUTES, data)

def vgs(name=None):
    """List available volume groups and return a dictionary of attributes"""
    args = [
        'vgs',
        '--noheadings',
        '--nosuffix',
        '--separator=,',
        '--units=b',
        '--options', ','.join(VGS_ATTRIBUTES)
    ]
    if name:
        args.append(name)
    data = lvm_cmd(*args)
    return lvm_dict(VGS_ATTRIBUTES, data)

def lvs(name=None):
    """List available logical volumes and return a dictionary of attributes

    If a name parameter is specified, only matching logical volumes
    will be returned.
    """
    args = [
        'lvs',
        '--noheadings',
        '--nosuffix',
        '--separator=,',
        '--units=b',
        '--options', ','.join(LVS_ATTRIBUTES)
    ]
    if name:
        args.append(name)
    data = lvm_cmd(*args)
    return lvm_dict(LVS_ATTRIBUTES, data)

def lvcreate(lv_name, lv_size, vg_name):
    """Create a new logical volume in the specified volume group"""
    args = [
        'lvcreate',
        '--name', lv_name,
        '--size', str(lv_size),
        vg_name
    ]
    check_call(args)

def lvsnapshot(lv_name, snapshot_name, snapshot_extents):
    """Snapshot an existing logical volume using the specified
    snapshot name and snapshot size.

    snapshot_size should be a valid LVM size string.
    """
    args = [
        'lvcreate',
        '--snapshot',
        '--name', snapshot_name,
        '--extents', str(int(snapshot_extents)),
        lv_name
    ]
    check_call(args)

def lvremove(name):
    """Forcibly remove a logical volume.

    WARNING: This is dangerous and care should be taken before
    calling this method.
    """
    device = os.path.join(os.sep, 'dev', name)
    args = [
        'lvremove',
        '-f',
        device
    ]
    check_call(args)

def mount(device, path, options=None):
    """Mount the specified path or device"""
    #   mount exit status on linux defined by mount(1)
    #   0      success
    #   1      incorrect invocation or permissions
    #   2      system error (out of memory, cannot fork, no more loop devices)
    #   4      internal mount bug or missing nfs support in mount
    #   8      user interrupt
    #   16     problems writing or locking /etc/mtab
    #   32     mount failure
    #   64     some mount succeeded
    if not device:
        raise ValueError("No device specified to mount")
    if not path:
        raise ValueError("No path specified to mount")

    args = [
        'mount',
        device,
        path,
    ]
    if options:
        args.insert(1, options)
        args.insert(1, '-o')

    check_call(*args)

def unmount(path_or_device):
    """Unmount the specified path or device."""
    check_call(['umount', path_or_device])

def lvm_cmd(cmd, *args):
    """Run a LVM command and return the output.

    If a command returns non-zero status, an OSError is raised and the
    errno is set to the returncode of the command.

    For LVM, we also detect the string 'WARNING:' in output, which also
    tends to imply a failure.
    """
    pid = Popen([cmd] + list(args), stdout=PIPE, stderr=PIPE, close_fds=True)
    stdoutdata, stderrdata = pid.communicate()
    if pid.returncode != 0:
        raise CalledProcessError(pid.returncode, cmd)

    # WARNING: Likely means something is seriously broken - either we're not
    # root or the base LVM setup needs fixing. To err on safety we raise
    # an EnvironmentError in this case.
    if "WARNING:" in stderrdata:
        raise CalledProcessError(0, cmd)

    return stdoutdata

def lvm_dict(keys, values):
    """Convert LVM tool output into a dictionary"""
    stream = StringIO(values)
    kwargs = dict(delimiter=',', skipinitialspace=True)
    for row in csv.reader(stream, **kwargs):
        yield dict(zip(keys, row))


text:
package plotter

import (
	"errors"
	"fmt"
	"image/color"
	"math"

	"code.google.com/p/plotinum/plot"
)

// Histogram implements the Plotter interface,
// drawing a histogram of the data.
type Histogram struct {
	// Bins is the set of bins for this histogram.
	Bins []HistogramBin

	// Width is the width of each bin.
	Width float64

	// FillColor is the color used to fill each
	// bar of the histogram.  If the color is nil
	// then the bars are not filled.
	FillColor color.Color

	// LineStyle is the style of the outline of each
	// bar of the histogram.
	plot.LineStyle
}

// NewHistogram returns a new histogram
// that represents the distribution of values
// using the given number of bins.
//
// Each y value is assumed to be the frequency
// count for the corresponding x.
//
// If the number of bins is non-positive than
// a reasonable default is used.
func NewHistogram(xy XYer, n int) (*Histogram, error) {
	if n <= 0 {
		return nil, errors.New("Histogram with non-positive number of bins")
	}
	bins, width := binPoints(xy, n)
	return &Histogram{
		Bins:      bins,
		Width:     width,
		FillColor: color.Gray{128},
		LineStyle: DefaultLineStyle,
	}, nil
}

// NewHist returns a new histogram, as in
// NewHistogram, except that it accepts a Valuer
// instead of an XYer.
func NewHist(vs Valuer, n int) (*Histogram, error) {
	return NewHistogram(unitYs{vs}, n)
}

type unitYs struct {
	Valuer
}

func (u unitYs) XY(i int) (float64, float64) {
	return u.Value(i), 1.0
}

// Plot implements the Plotter interface, drawing a line
// that connects each point in the Line.
func (h *Histogram) Plot(da plot.DrawArea, p *plot.Plot) {
	trX, trY := p.Transforms(&da)

	for _, bin := range h.Bins {
		pts := []plot.Point{
			{trX(bin.Min), trY(0)},
			{trX(bin.Max), trY(0)},
			{trX(bin.Max), trY(bin.Weight)},
			{trX(bin.Min), trY(bin.Weight)},
		}
		if h.FillColor != nil {
			da.FillPolygon(h.FillColor, da.ClipPolygonXY(pts))
		}
		pts = append(pts, plot.Pt(trX(bin.Min), trY(0)))
		da.StrokeLines(h.LineStyle, da.ClipLinesXY(pts)...)
	}
}

// DataRange returns the minimum and maximum X and Y values
func (h *Histogram) DataRange() (xmin, xmax, ymin, ymax float64) {
	xmin = math.Inf(1)
	xmax = math.Inf(-1)
	ymax = math.Inf(-1)
	for _, bin := range h.Bins {
		if bin.Max > xmax {
			xmax = bin.Max
		}
		if bin.Min < xmin {
			xmin = bin.Min
		}
		if bin.Weight > ymax {
			ymax = bin.Weight
		}
	}
	return
}

// Normalize normalizes the histogram so that the
// total area beneath it sums to a given value.
func (h *Histogram) Normalize(sum float64) {
	mass := 0.0
	for _, b := range h.Bins {
		mass += b.Weight
	}
	for i := range h.Bins {
		h.Bins[i].Weight *= sum / (h.Width * mass)
	}
}

// binPoints returns a slice containing the
// given number of bins, and the width of
// each bin.
//
// If the given number of bins is not positive
// then a reasonable default is used.  The
// default is the square root of the sum of
// the y values.
func binPoints(xys XYer, n int) ([]HistogramBin, float64) {
	xmin, xmax := Range(XValues{xys})
	if n <= 0 {
		m := 0.0
		for i := 0; i < xys.Len(); i++ {
			_, y := xys.XY(i)
			m += math.Max(y, 1.0)
		}
		n = int(math.Ceil(math.Sqrt(m)))
	}
	if n < 1 || xmax <= xmin {
		n = 1
	}

	bins := make([]HistogramBin, n)

	w := (xmax - xmin) / float64(n)
	for i := range bins {
		bins[i].Min = xmin + float64(i)*w
		bins[i].Max = xmin + float64(i+1)*w
	}

	for i := 0; i < xys.Len(); i++ {
		x, y := xys.XY(i)
		bin := int((x - xmin) / w)
		if x == xmax {
			bin = n - 1
		}
		if bin < 0 || bin >= n {
			panic(fmt.Sprintf("%g, xmin=%g, xmax=%g, w=%g, bin=%d, n=%d\n",
				x, xmin, xmax, w, bin, n))
		}
		bins[bin].Weight += y
	}
	return bins, w
}

// A HistogramBin approximates the number of values
// within a range by a single number (the weight).
type HistogramBin struct {
	Min, Max float64
	Weight   float64
}

redpajama_set_name: RedPajamaGithub


text:
var namespaceorg_1_1onosproject_1_1messagingperf =
[
    [ "MessagingPerfApp", "classorg_1_1onosproject_1_1messagingperf_1_1MessagingPerfApp.html", "classorg_1_1onosproject_1_1messagingperf_1_1MessagingPerfApp" ]
];


text:
package com.tomtom.speedtools.utils;

import javax.annotation.Nonnull;

/**
 * Util class for byte relate operations and conversions.
 */
public final class ByteUtils {

    private ByteUtils() {
        // Prevent instantiation.
    }

    /**
     * Method converts given byte array of 4 bytes into a signed integer.
     *
     * @param bytes Byte array of 4 that needs to be converted to a signed integer.
     * @return Integer value that is represented by the 4 given bytes.
     * @throws IllegalArgumentException In case the byte length is not equal to 4.
     */
    public static int fromBytesToInt(@Nonnull final byte[] bytes) {
        assert bytes != null;

        if (bytes.length != 4) {
            throw new IllegalArgumentException("Can only convert 4 bytes to an integer");
        }

        return fromBytesToInt(bytes[0], bytes[1], bytes[2], bytes[3]);
    }

    /**
     * Method converts given 4 bytes into a signed integer.
     *
     * @param byte1 First byte.
     * @param byte2 Second byte.
     * @param byte3 Third byte.
     * @param byte4 Fourth byte.
     * @return Integer value that is represented by the 4 given bytes.
     */
    public static int fromBytesToInt(final byte byte1, final byte byte2, final byte byte3, final byte byte4) {
        int i = 0;

        i += unsignedByteToInt(byte1) << 24;
        i += unsignedByteToInt(byte2) << 16;
        i += unsignedByteToInt(byte3) << 8;
        i += unsignedByteToInt(byte4);

        return i;
    }

    /**
     * Converts a byte to an unsigned integer.
     *
     * @param b The byte to convert.
     * @return an unsigned integer.
     */
    public static int unsignedByteToInt(final byte b) {
        return (int) b & 0xFF;
    }

    /**
     * Method converts given integer into a byte array.
     *
     * @param value The integer value to convert to 4 bytes
     * @return An array of 4 bytes representing the given signed integer.
     */
    @SuppressWarnings("NumericCastThatLosesPrecision")
    @Nonnull
    public static byte[] intToByteArray(final int value) {
        return new byte[]{
                (byte) (value >>> 24),
                (byte) (value >>> 16),
                (byte) (value >>> 8),
                (byte) value};
    }
}


text:
const assert = require('assert');
const path = require('path');
const fs = require('fs');

const webpack = require('webpack');

describe('Tests', () => {
  fs.readdirSync(path.join(__dirname, 'cases')).forEach((testCase) => {
    it(testCase, () => {
      const testDir = path.join(__dirname, 'cases', testCase);
      const outputDir = path.join(__dirname, 'js', testCase);
      const configFile = path.join(testDir, 'webpack.config.js');

      // eslint-disable-next-line import/no-dynamic-require,global-require
      const webpackConfig = require(configFile);
      webpackConfig.context = testDir;
      webpackConfig.output.path = outputDir;

      webpack(webpackConfig, (err, stats) => {
        if (err) {
          throw err;
        }

        if (stats.hasErrors()) {
          throw new Error(stats.toString());
        }

        const expectedDir = path.join(testDir, 'expected');
        fs.readdirSync(expectedDir).forEach((expectedFile) => {
          const expected = fs.readFileSync(path.resolve(expectedDir, expectedFile), 'utf8');
          const actual = fs.readFileSync(path.resolve(outputDir, expectedFile), 'utf8');

          assert.strictEqual(actual, expected);
        });
      });
    });
  })
});


text:
const logger = require('./logger').plugins;
const eventBus = require('./eventBus');
const schemas = require('./schemas');
const parentRequire = require('parent-require');
const engineVersion = '1.2.0';
const semver = require('semver');
const prefix = 'express-gateway-plugin-'; // TODO make configurable
module.exports.load = function ({ config }) {
  config = config || require('./config');
  const pluginsSettings = config.systemConfig.plugins || {};

  const loadedPlugins = [];
  logger.debug(`Loading plugins. Plugin engine version: ${engineVersion}`);
  for (const pluginName in pluginsSettings) {
    const settings = pluginsSettings[pluginName] || {};
    let requireName = pluginName;
    if (settings.package) {
      requireName = settings.package;
    } else if (pluginName.indexOf(prefix) !== 0) {
      requireName = prefix + pluginName;
    }

    try {
      logger.debug(`Loading plugin ${requireName}`);
      let plugin;
      try {
        plugin = require(requireName); // EG loaded as main module
      } catch (err) {
        plugin = parentRequire(requireName); // EG loaded as library (after eg gateway create)
      }
      if (semver.lt(engineVersion, plugin.version)) { // TODO: versioning of plugins
        logger.warn(`${plugin.version} is higher than engine version: ${engineVersion}; trying to load`);
      }

      // register schema and validate settings
      const validate = schemas.register('plugin', pluginName, plugin.schema);
      const { isValid, error } = validate(settings);
      if (!isValid) {
        // Stop loading plugin.
        throw new Error(`Failed to validate settings: ${error}`);
      }

      const services = require('./services');
      const context = new PluginContext({ settings, config, services });
      plugin.init(context);
      loadedPlugins.push(context);
      logger.info(`Loaded plugin ${pluginName} from package ${requireName}`);
    } catch (err) {
      logger.error(`Failed to load plugin ${requireName}: ${err}`);
    }
  }

  // Note: All logic to handle different plugin version should be here
  // Note: Rest of EG code must use only one standard interface
  return {
    policies: extract(loadedPlugins, 'policies'),
    conditions: extract(loadedPlugins, 'conditions'),
    gatewayRoutes: extract(loadedPlugins, 'gatewayRoutes'),
    adminRoutes: extract(loadedPlugins, 'adminRoutes'),
    cliExtensions: extract(loadedPlugins, 'cliExtensions')
  };
};

class PluginContext {
  constructor ({ settings, config, services }) {
    this.logger = logger;
    this.services = services;
    this.settings = settings || {};
    this.config = config;
    this.policies = [];
    this.conditions = [];
    this.gatewayRoutes = [];
    this.adminRoutes = [];
    this.cliExtensions = [];
    this.eventBus = eventBus;
  }

  registerPolicy (policy) {
    this.policies.push(policy);
  }

  registerCondition (condition) {
    this.conditions.push(condition);
  }

  registerGatewayRoute (gatewayRoutesDeclaration) {
    this.gatewayRoutes.push(gatewayRoutesDeclaration);
  }

  registerAdminRoute (adminRoutesDeclaration) {
    this.adminRoutes.push(adminRoutesDeclaration);
  }

  registerCLIExtension (cliExtension) {
    this.cliExtensions.push(cliExtension);
  }
}

function extract (loadedPlugins, propName) {
  return loadedPlugins.reduce((result, current) => {
    return result.concat(current[propName] || []);
  }, []);
};


text:
Quick Navigation

FIDELITY HOME ENERGY Map

FIDELITY HOME ENERGY Video

Get Approved

Energy Use

{{$index + 1}}

{{mpaeu.title}}

Upgrades

{{$index + 7}}

{{mpau.title}}

Payments

{{$index + 12}}

{{mpap.title}}

Home

Quick Reference Guide

Pro Pitch Demo Videos

Feedback

FAQs

Logout

                                By how much do you the think the price of electricity will increase each year?

                        <button ng-click="energyBill.percentChange=energyBill.percentChange + 0.5" class=" btn-proposal">∧</button>
                        <input type="text" perc-model-formatter="" style="width: 90px;" ng-model="energyBill.percentChange" class="ng-pristine ng-untouched ng-valid">
                        <button ng-click="energyBill.percentChange=energyBill.percentChange - 0.5" class=" btn-proposal">∨</button>

                        <button ng-click="energyBill.yearChange=energyBill.yearChange + 5" class=" btn-proposal">∧</button>
                        <input type="text" year-model-formatter="" style="width: 90px;" ng-model="energyBill.yearChange" class="ng-pristine ng-untouched ng-valid" yrs-model-formatter="">
                        <button ng-click="energyBill.yearChange=energyBill.yearChange - 5" class=" btn-proposal">∨</button>

                 BACK

			NEXT


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Asylo: asylo/identity/platform/sgx/attributes_util.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="/favicons/favicon.ico" rel="shortcut icon" type="image/x-icon"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Asylo

asylo

identity

platform

sgx

Namespaces |
Functions

attributes_util.h File Reference

This library implements operations and utility functions on Attributes messages.
More...

#include <vector>

#include "absl/strings/string_view.h"

#include "asylo/identity/platform/sgx/architecture_bits.h"

#include "asylo/identity/platform/sgx/attributes.pb.h"

#include "asylo/util/status.h"

#include "asylo/util/statusor.h"

Include dependency graph for attributes_util.h:

<map name="asylo_2identity_2platform_2sgx_2attributes__util_8h" id="asylo_2identity_2platform_2sgx_2attributes__util_8h">
<area shape="rect" id="node4" href="architecture__bits_8h.html" title="asylo/identity/platform\l/sgx/architecture_bits.h" alt="" coords="1083,95,1257,136"/>
<area shape="rect" id="node8" href="status_8h.html" title="asylo/util/status.h" alt="" coords="1306,184,1445,211"/>
<area shape="rect" id="node34" href="statusor_8h.html" title="asylo/util/statusor.h" alt="" coords="2545,102,2696,129"/>
<area shape="rect" id="node21" href="logging_8h.html" title="asylo/util/logging.h" alt="" coords="2835,266,2982,293"/>
<area shape="rect" id="node27" href="error__space_8h.html" title="asylo/util/error_space.h" alt="" coords="449,266,624,293"/>
</map>

Go to the source code of this file.

Namespaces

  	asylo

  	asylo::sgx

Functions

Attributes 	asylo::sgx::operator & (const Attributes &lhs, const Attributes &rhs)

 	Computes the bitwise AND of two Attributes protos.  More...

bool 	asylo::sgx::operator== (const Attributes &lhs, const Attributes &rhs)

 	Checks two Attributes protos for equality.  More...

bool 	asylo::sgx::operator!= (const Attributes &lhs, const Attributes &rhs)

 	Checks two Attributes protos for inequality.  More...

Status 	asylo::sgx::SetAttributeBit (AttributeBit bit, Attributes *attributes)

 	Sets the given bit of attributes to true, or returns a non-OK Status if the bit was invalid.  More...

Status 	asylo::sgx::ClearAttributeBit (AttributeBit bit, Attributes *attributes)

 	Sets the given bit of attributes to false, or returns a non-OK Status if the bit was invalid.  More...

StatusOr< bool > 	asylo::sgx::IsAttributeBitSet (AttributeBit bit, const Attributes &attributes)

 	Returns whether the given bit of attributes is set, or a non-OK Status if the bit was invalid.  More...

std::vector< absl::string_view > 	asylo::sgx::GetPrintableAttributeList (const Attributes &attributes)

 	Returns a printable list of the bits set in attributes.  More...

Detailed Description

This library implements operations and utility functions on Attributes messages.


text:
<?php

namespace Assetic\Factory\Worker;

use Assetic\Asset\AssetInterface;

/**
 * Adds cache busting code
 *
 * @author Kris Wallsmith <kris.wallsmith@gmail.com>
 */
class CacheBustingWorker implements WorkerInterface
{
    const STRATEGY_CONTENT = 1;
    const STRATEGY_MODIFICATION = 2;

    private $strategy;

    public function __construct($strategy = self::STRATEGY_CONTENT)
    {
        $this->strategy = $strategy;
    }

    public function process(AssetInterface $asset)
    {
        $hash = hash_init('sha1');

        switch($this->strategy) {
            case self::STRATEGY_MODIFICATION:
                hash_update($hash, $asset->getLastModified());
                break;
            case self::STRATEGY_CONTENT:
                hash_update($hash, $asset->dump());
                break;
        }

        foreach ($asset as $i => $leaf) {
            if ($sourcePath = $leaf->getSourcePath()) {
                hash_update($hash, $sourcePath);
            } else {
                hash_update($hash, $i);
            }
        }

        $hash = substr(hash_final($hash), 0, 7);
        $url = $asset->getTargetPath();

        $oldExt = pathinfo($url, PATHINFO_EXTENSION);
        $newExt = '-'.$hash.'.'.$oldExt;

        if (!$oldExt || 0 < preg_match('/'.preg_quote($newExt, '/').'$/', $url)) {
            return;
        }

        $asset->setTargetPath(substr($url, 0, (strlen($oldExt) + 1) * -1).$newExt);
    }

    public function getStrategy()
    {
        return $this->strategy;
    }

    public function setStrategy($strategy)
    {
        $this->strategy = $strategy;

        return $this;
    }
}


text:
<!DOCTYPE html>

	<title>ajax_pagination</title>

    <link href="assets/css/bootstrap.min.css" rel="stylesheet">

AJAX


text:
<?php

declare(strict_types=1);

namespace Marein\Nchan\Http;

use Marein\Nchan\Exception\NchanException;

interface Client
{
    /**
     * @throws NchanException
     */
    public function get(Request $request): Response;

    /**
     * @throws NchanException
     */
    public function post(Request $request): Response;

    /**
     * @throws NchanException
     */
    public function delete(Request $request): Response;
}


text:
@interface PauseGameCommand : CommandBase
{
}

@end


text:
namespace Appccelerate.IO.Access
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Security;

    /// <summary>
    /// Factory interface for factories which are responsible to create IO
    /// components.
    /// </summary>
    public interface IAccessFactory
    {
        IDirectory CreateDirectory();

        IFile CreateFile();

        IPath CreatePath();

        IEnvironment CreateEnvironment();

        IDrive CreateDrive();

        IFileInfo CreateFileInfo(FileInfo fileInfo);

        /// <summary>
        /// Creates the file info.
        /// </summary>
        /// <param name="pathToFile">The file path.</param>
        /// <exception cref="ArgumentNullException"><paramref name="pathToFile"/> is null.
        /// </exception>
        /// <exception cref="SecurityException">The caller does not have the required
        /// permission.</exception>
        /// <exception cref="ArgumentException">The file name is empty, contains only white
        /// spaces, or contains invalid characters.</exception>
        /// <exception cref="UnauthorizedAccessException">Access to
        /// <paramref name="pathToFile"/> is denied.</exception>
        /// <exception cref="PathTooLongException">The specified path, file name, or both
        /// exceed the system-defined maximum length. For example, on Windows-based
        /// platforms, paths must be less than 248 characters, and file names must be less
        /// than 260 characters.</exception>
        /// <exception cref="NotSupportedException"><paramref name="pathToFile"/> contains
        /// a colon (:) in the middle of the string.</exception>
        /// <returns>An instance implementing <see cref="IFileInfo"/>.</returns>
        IFileInfo CreateFileInfo(string pathToFile);

        /// <summary>
        /// Creates the directory info.
        /// </summary>
        /// <param name="directoryInfo">The directory info.</param>
        /// <returns>An instance implementing <see cref="IDirectoryInfo"/>.</returns>
        IDirectoryInfo CreateDirectoryInfo(DirectoryInfo directoryInfo);

        /// <summary>
        /// Creates the directory info.
        /// </summary>
        /// <param name="pathToDirectory">The directory path.</param>
        /// <exception cref="ArgumentNullException">path is null.</exception>
        /// <exception cref="SecurityException">The caller does not have the required
        /// permission.</exception>
        /// <exception cref="ArgumentException">path contains invalid characters.</exception>
        /// <exception cref="PathTooLongException">The specified path, file name, or both
        /// exceed the system-defined maximum length. For example, on Windows-based
        /// platforms, paths must be less than 248 characters, and file names must be less
        /// than 260 characters. The specified path, file name, or both are too long.
        /// </exception>
        /// <returns>An instance implementing <see cref="IDirectoryInfo"/>.</returns>
        IDirectoryInfo CreateDirectoryInfo(string pathToDirectory);

        /// <summary>
        /// Creates the drive info.
        /// </summary>
        /// <param name="driveInfo">The drive info.</param>
        /// <returns>An instance implementing <see cref="IDriveInfo"/>.</returns>
        IDriveInfo CreateDriveInfo(DriveInfo driveInfo);

        /// <summary>
        /// Creates the drive info.
        /// </summary>
        /// <param name="driveName">A valid drive path or drive letter. This can be either
        /// uppercase or lowercase, 'a' to 'z'. A null value is not valid.</param>
        /// <exception cref="ArgumentNullException">The drive letter cannot be null.
        /// </exception>
        /// <exception cref="ArgumentException">The first letter of
        /// <paramref name="driveName"/> is not an uppercase or lowercase letter from 'a'
        /// to 'z'.  -or-
        /// <paramref name="driveName"/> does not refer to a valid drive.</exception>
        /// <returns>An instance implementing <see cref="IDriveInfo"/>.</returns>
        IDriveInfo CreateDriveInfo(string driveName);

        /// <summary>
        /// Registers an extensions provider for file extensions. The extensions provider is called on each
        /// CreateFile request.
        /// </summary>
        /// <param name="extensionsProvider">The file extension provider</param>
        void RegisterFileExtensionsProvider(Func<IEnumerable<IFileExtension>> extensionsProvider);

        /// <summary>
        /// Registers an extensions provider for directory extensions. The extensions provider is called on each
        /// CreateDirectory request.
        /// </summary>
        /// <param name="extensionsProvider">The directory extension provider</param>
        void RegisterDirectoryExtensionsProvider(Func<IEnumerable<IDirectoryExtension>> extensionsProvider);

        /// <summary>
        /// Registers an extensions provider for drive extensions. The extensions provider is called on each
        /// CreateDrive request.
        /// </summary>
        /// <param name="extensionsProvider">The drive extension provider</param>
        void RegisterDriveExtensionsProvider(Func<IEnumerable<IDriveExtension>> extensionsProvider);

        /// <summary>
        /// Registers an extensions provider for path extensions. The extensions provider is called on each
        /// CreatePath request.
        /// </summary>
        /// <param name="extensionsProvider">The path extension provider</param>
        void RegisterPathExtensionsProvider(Func<IEnumerable<IPathExtension>> extensionsProvider);

        /// <summary>
        /// Registers an extensions provider for environment extensions. The extensions provider is called on each
        /// CreateEnvironment request.
        /// </summary>
        /// <param name="extensionsProvider">The environment extension provider</param>
        void RegisterEnvironmentExtensionsProvider(Func<IEnumerable<IEnvironmentExtension>> extensionsProvider);
    }
}


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE BangPatterns #-}
-- |  This module converts 'GHC.ApiAnns' into 'Anns' by traversing a
-- structure created by the "Annotate" modue.
--
-- == Structure of an Annotation
--
-- As a rule of thumb, every located element in the GHC AST will have
-- a corresponding entry in 'Anns'. An 'Annotation' contains 6 fields which
-- can be modifed to change how the AST is printed.
--
-- == Layout Calculation
--
-- Certain expressions such as do blocks and let bindings obey
-- <https://en.wikibooks.org/wiki/Haskell/Indentation layout rules>. We
-- calculate the 'annEntryDelta' slightly differently when such rules
-- apply.
--
-- 1. The first element which the layout rule applies to is given
-- a 'annEntryDelta' as normal.
-- 2. Further elements which must obey the rules are then given
-- 'annEntryDelta's relative to the LHS of the first element.
--
-- For example, in the following expression the statement corresponding to
-- `baz` will be given a 'annEntryDelta' of @DP (1, 2)@ as it appears
-- 1 line and 2 columns after the @do@ keyword. On the other hand, @bar@
-- will be given a 'annEntryDelta' of @DP (1,0)@ as it appears 1 line
-- further than @baz@ but in the same column as the start of the layout
-- block.
--
-- @
-- foo = do
--   baz
--   bar
-- @
--
-- A useful way to think of these rules is that the 'DeltaPos' is relative
-- to the further left an expression could have been placed. In the
-- previous example, we could have placed @baz@ anywhere on the line as its
-- position determines where the other statements must be. @bar@ could have
-- not been placed any further left without resulting in a syntax error
-- which is why the relative column is 0.
--
-- === annTrueEntryDelta
-- A very useful function is 'annTrueEntryDelta' which calculates the
-- offset from the last synctactic element (ignoring comments). This is
-- different to 'annEntryDelta' which does not ignore comments.
--
--
--
module Language.Haskell.GHC.ExactPrint.Delta
  ( relativiseApiAnns
  , relativiseApiAnnsWithComments
  , relativiseApiAnnsWithOptions

  -- * Configuration
  , DeltaOptions(drRigidity)
  , deltaOptions
  , normalLayout
  ) where

import Control.Monad.RWS
import Control.Monad.Trans.Free

import Data.Data (Data)
import Data.List (sort, nub, partition, sortBy)

import Data.Ord

import Language.Haskell.GHC.ExactPrint.Utils
#if __GLASGOW_HASKELL__ <= 710
import Language.Haskell.GHC.ExactPrint.Lookup
#endif
import Language.Haskell.GHC.ExactPrint.Types
import Language.Haskell.GHC.ExactPrint.Annotate (AnnotationF(..), Annotated
                                                , annotate, Annotate(..))

import qualified GHC
import qualified SrcLoc        as GHC

import qualified Data.Map as Map
#if __GLASGOW_HASKELL__ <= 710
import qualified Data.Set as Set
#endif

-- import Debug.Trace

-- ---------------------------------------------------------------------
-- | Transform concrete annotations into relative annotations which are
-- more useful when transforming an AST.
relativiseApiAnns :: Annotate ast
                  => GHC.Located ast
                  -> GHC.ApiAnns
                  -> Anns
relativiseApiAnns = relativiseApiAnnsWithComments []

-- | Exactly the same as 'relativiseApiAnns' but with the possibilty to
-- inject comments. This is typically used if the source has been preprocessed
-- by e.g. CPP, and the parts stripped out of the original source are re-added
-- as comments so they are not lost for round tripping.
relativiseApiAnnsWithComments ::
                     Annotate ast
                  => [Comment]
                  -> GHC.Located ast
                  -> GHC.ApiAnns
                  -> Anns
relativiseApiAnnsWithComments =
    relativiseApiAnnsWithOptions normalLayout

relativiseApiAnnsWithOptions ::
                     Annotate ast
                  => DeltaOptions
                  -> [Comment]
                  -> GHC.Located ast
                  -> GHC.ApiAnns
                  -> Anns
relativiseApiAnnsWithOptions opts cs modu ghcAnns
   = runDeltaWithComments
      opts cs (annotate modu) ghcAnns
      (ss2pos $ GHC.getLoc modu)

-- ---------------------------------------------------------------------
--
-- | Type used in the Delta Monad.
type Delta a = RWS DeltaOptions DeltaWriter DeltaState a

runDeltaWithComments :: DeltaOptions -> [Comment] -> Annotated () -> GHC.ApiAnns -> Pos -> Anns
runDeltaWithComments opts cs action ga priorEnd =
  mkAnns . snd
  . (\next -> execRWS next opts (defaultDeltaState cs priorEnd ga))
  . deltaInterpret $ action
  where
    mkAnns :: DeltaWriter -> Anns
    mkAnns = f . dwAnns
    f :: Monoid a => Endo a -> a
    f = ($ mempty) . appEndo

-- ---------------------------------------------------------------------

data DeltaOptions = DeltaOptions
       {
         -- | Current `SrcSpan, part of current AnnKey`
         curSrcSpan  :: !GHC.SrcSpan

         -- | Constuctor of current AST element, part of current AnnKey
       , annConName       :: !AnnConName

        -- | Whether to use rigid or normal layout rules
       , drRigidity :: Rigidity

       }

data DeltaWriter = DeltaWriter
       { -- | Final list of annotations, and sort keys
         dwAnns :: Endo (Map.Map AnnKey Annotation)

         -- | Used locally to pass Keywords, delta pairs relevant to a specific
         -- subtree to the parent.
       , annKds         :: ![(KeywordId, DeltaPos)]
       , sortKeys       :: !(Maybe [GHC.SrcSpan])
       , dwCapturedSpan :: !(First AnnKey)
       }

data DeltaState = DeltaState
       { -- | Position reached when processing the last element
         priorEndPosition    :: !Pos

         -- | Ordered list of comments still to be allocated
       , apComments :: ![Comment]

         -- | The original GHC Delta Annotations
       , apAnns :: !GHC.ApiAnns

       , apMarkLayout :: Bool
       , apLayoutStart :: LayoutStartCol

       }

-- ---------------------------------------------------------------------

deltaOptions :: Rigidity -> DeltaOptions
deltaOptions ridigity =
  DeltaOptions
    { curSrcSpan = GHC.noSrcSpan
    , annConName = annGetConstr ()
    , drRigidity = ridigity
    }

normalLayout :: DeltaOptions
normalLayout = deltaOptions NormalLayout

defaultDeltaState :: [Comment] -> Pos -> GHC.ApiAnns -> DeltaState
defaultDeltaState injectedComments priorEnd ga =
    DeltaState
      { priorEndPosition    = priorEnd
      , apComments = cs ++ injectedComments
      , apAnns     = ga
      , apLayoutStart = 1
      , apMarkLayout = False
      }
  where
    cs :: [Comment]
    cs = flattenedComments ga

    flattenedComments :: GHC.ApiAnns -> [Comment]
    flattenedComments (_,cm) =
      map tokComment . GHC.sortLocated . concat $ Map.elems cm

-- Writer helpers

tellFinalAnn :: (AnnKey, Annotation) -> Delta ()
tellFinalAnn (k, v) =
  -- tell (mempty { dwAnns = Endo (Map.insertWith (<>) k v) })
  tell (mempty { dwAnns = Endo (Map.insert k v) })

tellSortKey :: [GHC.SrcSpan] -> Delta ()
tellSortKey xs = tell (mempty { sortKeys = Just xs } )

tellCapturedSpan :: AnnKey -> Delta ()
tellCapturedSpan key = tell ( mempty { dwCapturedSpan = First $ Just key })

tellKd :: (KeywordId, DeltaPos) -> Delta ()
tellKd kd = tell (mempty { annKds = [kd] })

instance Monoid DeltaWriter where
  mempty = DeltaWriter mempty mempty mempty mempty
  (DeltaWriter a b e g) `mappend` (DeltaWriter c d f h)
    = DeltaWriter (a <> c) (b <> d) (e <> f) (g <> h)

-----------------------------------
-- Free Monad Interpretation code

deltaInterpret :: Annotated a -> Delta a
deltaInterpret = iterTM go
  where
    go :: AnnotationF (Delta a) -> Delta a
    go (MarkEOF next)                   = addEofAnnotation >> next
    go (MarkPrim kwid _ next)           = addDeltaAnnotation kwid >> next
    go (MarkOutside akwid kwid next)    = addDeltaAnnotationsOutside akwid kwid >> next
    go (MarkInside akwid next)          = addDeltaAnnotationsInside akwid >> next
    go (MarkMany akwid next)            = addDeltaAnnotations akwid >> next
    go (MarkOffsetPrim akwid n _ next)  = addDeltaAnnotationLs akwid n >> next
    go (WithAST lss prog next)          = withAST lss (deltaInterpret prog) >> next
    go (CountAnns kwid next)            = countAnnsDelta kwid >>= next
    go (SetLayoutFlag r action next)    = do
      rigidity <- asks drRigidity
      (if (r <= rigidity) then setLayoutFlag else id) (deltaInterpret action)
      next
    go (MarkExternal ss akwid _ next)    = addDeltaAnnotationExt ss akwid >> next
    go (StoreOriginalSrcSpan key next)   = storeOriginalSrcSpanDelta key >>= next
    go (GetSrcSpanForKw kw next)         = getSrcSpanForKw kw >>= next
#if __GLASGOW_HASKELL__ <= 710
    go (StoreString s ss next)           = storeString s ss >> next
#endif
    go (AnnotationsToComments kws next)  = annotationsToCommentsDelta kws >> next
    go (WithSortKey kws next)            = withSortKey kws >> next

withSortKey :: [(GHC.SrcSpan, Annotated b)] -> Delta ()
withSortKey kws =
  let order = sortBy (comparing fst) kws
  in do
    tellSortKey (map fst order)
    mapM_ (deltaInterpret . snd) order

setLayoutFlag :: Delta () -> Delta ()
setLayoutFlag action = do
  oldLay <- gets apLayoutStart
  modify (\s -> s { apMarkLayout = True } )
  let reset = do
                modify (\s -> s { apMarkLayout = False
                                , apLayoutStart = oldLay })
  action <* reset

-- ---------------------------------------------------------------------

storeOriginalSrcSpanDelta :: AnnKey -> Delta AnnKey
storeOriginalSrcSpanDelta key = do
  tellCapturedSpan key
  return key

#if __GLASGOW_HASKELL__ <= 710
storeString :: String -> GHC.SrcSpan -> Delta ()
storeString s ss = addAnnotationWorker (AnnString s) ss
#endif

-- ---------------------------------------------------------------------

-- |In order to interleave annotations into the stream, we turn them into
-- comments.
annotationsToCommentsDelta :: [GHC.AnnKeywordId] -> Delta ()
annotationsToCommentsDelta kws = do
  ga <- gets apAnns
  ss <- getSrcSpan
  cs <- gets apComments
  let
    doOne :: GHC.AnnKeywordId -> [Comment]
    doOne kw = comments
      where
        spans = GHC.getAnnotation ga ss kw
        comments = map (mkKWComment kw) spans
    -- TODO:AZ make sure these are sorted/merged properly when the invariant for
    -- allocateComments is re-established.
    newComments = concatMap doOne kws
  putUnallocatedComments (cs ++ newComments)

-- ---------------------------------------------------------------------

-- | This function exists to overcome a shortcoming in the GHC AST for 7.10.1
getSrcSpanForKw :: GHC.AnnKeywordId -> Delta GHC.SrcSpan
getSrcSpanForKw kw = do
    ga <- gets apAnns
    ss <- getSrcSpan
    case GHC.getAnnotation ga ss kw of
      []     -> return GHC.noSrcSpan
      (sp:_) -> return sp

-- ---------------------------------------------------------------------

getSrcSpan :: Delta GHC.SrcSpan
getSrcSpan = asks curSrcSpan

withSrcSpanDelta :: Data a => GHC.Located a -> Delta b -> Delta b
withSrcSpanDelta (GHC.L l a) =
  local (\s -> s { curSrcSpan = l
                 , annConName = annGetConstr a
                 })

getUnallocatedComments :: Delta [Comment]
getUnallocatedComments = gets apComments

putUnallocatedComments :: [Comment] -> Delta ()
putUnallocatedComments cs = modify (\s -> s { apComments = cs } )

-- ---------------------------------------------------------------------

adjustDeltaForOffsetM :: DeltaPos -> Delta DeltaPos
adjustDeltaForOffsetM dp = do
  colOffset <- gets apLayoutStart
  return (adjustDeltaForOffset colOffset dp)

adjustDeltaForOffset :: LayoutStartCol -> DeltaPos -> DeltaPos
adjustDeltaForOffset _colOffset              dp@(DP (0,_)) = dp -- same line
adjustDeltaForOffset (LayoutStartCol colOffset) (DP (l,c)) = DP (l,c - colOffset)

-- ---------------------------------------------------------------------

getPriorEnd :: Delta Pos
getPriorEnd = gets priorEndPosition

setPriorEnd :: Pos -> Delta ()
setPriorEnd pe =
  modify (\s -> s { priorEndPosition = pe })

setPriorEndAST :: GHC.SrcSpan -> Delta ()
setPriorEndAST pe = do
  setLayoutStart (snd (ss2pos pe))
  modify (\s -> s { priorEndPosition    = (ss2posEnd pe) } )

setLayoutStart :: Int -> Delta ()
setLayoutStart p = do
  DeltaState{apMarkLayout} <- get
  when apMarkLayout (
                      modify (\s -> s { apMarkLayout = False
                                     , apLayoutStart = LayoutStartCol p}))

-- -------------------------------------

peekAnnotationDelta :: GHC.AnnKeywordId -> Delta [GHC.SrcSpan]
peekAnnotationDelta an = do
    ga <- gets apAnns
    ss <- getSrcSpan
#if __GLASGOW_HASKELL__ <= 710
    return $ GHC.getAnnotation ga ss an
#else
    let unicodeAnns = case unicodeEquivalent an of
          [] -> []
          [kw] -> GHC.getAnnotation ga ss kw
    return $ unicodeAnns ++ GHC.getAnnotation ga ss an
#endif

getAnnotationDelta :: GHC.AnnKeywordId -> Delta ([GHC.SrcSpan],GHC.AnnKeywordId)
getAnnotationDelta an = do
    ss <- getSrcSpan
    getAndRemoveAnnotationDelta ss an

getAndRemoveAnnotationDelta :: GHC.SrcSpan -> GHC.AnnKeywordId -> Delta ([GHC.SrcSpan],GHC.AnnKeywordId)
getAndRemoveAnnotationDelta sp an = do
    ga <- gets apAnns
#if __GLASGOW_HASKELL__ <= 710
    let (r,ga') = GHC.getAndRemoveAnnotation ga sp an
        kw = an
#else
    let (r,ga',kw) = case GHC.getAndRemoveAnnotation ga sp an of
                    ([],_) -> (ss,g,k)
                      where
                        k = GHC.unicodeAnn an
                        (ss,g) = GHC.getAndRemoveAnnotation ga sp k
                    (ss,g)  -> (ss,g,an)
#endif
    modify (\s -> s { apAnns = ga' })
    return (r,kw)

getOneAnnotationDelta :: GHC.AnnKeywordId -> Delta ([GHC.SrcSpan],GHC.AnnKeywordId)
getOneAnnotationDelta an = do
    ss <- getSrcSpan
    getAndRemoveOneAnnotationDelta ss an

getAndRemoveOneAnnotationDelta :: GHC.SrcSpan -> GHC.AnnKeywordId -> Delta ([GHC.SrcSpan],GHC.AnnKeywordId)
getAndRemoveOneAnnotationDelta sp an = do
    (anns,cs) <- gets apAnns
#if __GLASGOW_HASKELL__ <= 710
    let (r,ga',kw) = case Map.lookup (sp,an) anns of
                    Nothing -> ([],(anns,cs),an)
                    Just []     -> ([], (Map.delete (sp,an)    anns,cs),an)
                    Just (s:ss) -> ([s],(Map.insert (sp,an) ss anns,cs),an)
#else
    let getKw kw =
          case Map.lookup (sp,kw) anns of
            Nothing -> ([],(anns,cs),kw)
            Just []     -> ([], (Map.delete (sp,kw)    anns,cs),kw)
            Just (s:ss) -> ([s],(Map.insert (sp,kw) ss anns,cs),kw)

    let (r,ga',kw) =
          case getKw an of
            ([],_,_) -> getKw (GHC.unicodeAnn an)
            v        -> v
#endif
    modify (\s -> s { apAnns = ga' })
    return (r,kw)

-- ---------------------------------------------------------------------

-- |Add some annotation to the currently active SrcSpan
addAnnotationsDelta :: Annotation -> Delta ()
addAnnotationsDelta ann = do
    l <- ask
    tellFinalAnn (getAnnKey l,ann)

getAnnKey :: DeltaOptions -> AnnKey
getAnnKey DeltaOptions {curSrcSpan, annConName}
  = AnnKey curSrcSpan annConName

-- -------------------------------------

addAnnDeltaPos :: KeywordId -> DeltaPos -> Delta ()
addAnnDeltaPos kw dp = tellKd (kw, dp)

-- -------------------------------------

-- | Enter a new AST element. Maintain SrcSpan stack
withAST :: Data a
        => GHC.Located a
        -> Delta b -> Delta b
withAST lss@(GHC.L ss _) action = do
  -- Calculate offset required to get to the start of the SrcSPan
  off <- gets apLayoutStart
  (resetAnns .  withSrcSpanDelta lss) (do

    let maskWriter s = s { annKds = []
                         , sortKeys = Nothing
                         , dwCapturedSpan = mempty }

    -- make sure all kds are relative to the start of the SrcSpan
    let spanStart = ss2pos ss

    cs <- do
      priorEndBeforeComments <- getPriorEnd
      if GHC.isGoodSrcSpan ss && priorEndBeforeComments < ss2pos ss
        then
          commentAllocation (priorComment spanStart) return
        else
          return []
    priorEndAfterComments <- getPriorEnd
    let edp = adjustDeltaForOffset
                -- Use the propagated offset if one is set
                -- Note that we need to use the new offset if it has
                -- changed.
                off (ss2delta priorEndAfterComments ss)
    -- Preparation complete, perform the action
    when (GHC.isGoodSrcSpan ss && priorEndAfterComments < ss2pos ss) (do
      modify (\s -> s { priorEndPosition    = (ss2pos ss) } ))
    (res, w) <- censor maskWriter (listen action)

    let kds = annKds w
        an = Ann
               { annEntryDelta = edp
               , annPriorComments = cs
               , annFollowingComments = [] -- only used in Transform and Print
               , annsDP     = kds
               , annSortKey = sortKeys w
               , annCapturedSpan = getFirst $ dwCapturedSpan w }

    addAnnotationsDelta an
     `debug` ("leaveAST:(annkey,an)=" ++ show (mkAnnKey lss,an))
    return res)

resetAnns :: Delta a -> Delta a
resetAnns action = do
  ans <- gets apAnns
  action <* modify (\s -> s { apAnns = ans })

-- ---------------------------------------------------------------------
-- |Split the ordered list of comments into ones that occur prior to
-- the give SrcSpan and the rest
priorComment :: Pos -> Comment -> Bool
priorComment start c = (ss2pos . commentIdentifier $ c) < start

-- TODO:AZ: We scan the entire comment list here. It may be better to impose an
-- invariant that the comments are sorted, and consume them as the pos
-- advances. It then becomes a process of using `takeWhile p` rather than a full
-- partition.
allocateComments :: (Comment -> Bool) -> [Comment] -> ([Comment], [Comment])
allocateComments = partition

-- ---------------------------------------------------------------------

addAnnotationWorker :: KeywordId -> GHC.SrcSpan -> Delta ()
addAnnotationWorker ann pa =
  -- Zero-width source spans are injected by the GHC Lexer when it puts virtual
  -- '{', ';' and '}' tokens in for layout
  unless (isPointSrcSpan pa) $
    do
      pe <- getPriorEnd
      ss <- getSrcSpan
      let p = ss2delta pe pa
      case (ann,isGoodDelta p) of
        (G GHC.AnnComma,False) -> return ()
        (G GHC.AnnSemi, False) -> return ()
        (G GHC.AnnOpen, False) -> return ()
        (G GHC.AnnClose,False) -> return ()
        _ -> do
          p' <- adjustDeltaForOffsetM p
          commentAllocation (priorComment (ss2pos pa)) (mapM_ (uncurry addDeltaComment))
#if __GLASGOW_HASKELL__ <= 710
          addAnnDeltaPos (checkUnicode ann pa) p'
#else
          addAnnDeltaPos ann p'
#endif
          setPriorEndAST pa
              `debug` ("addAnnotationWorker:(ss,ss,pe,pa,p,p',ann)=" ++ show (showGhc ss,showGhc ss,pe,showGhc pa,p,p',ann))

#if __GLASGOW_HASKELL__ <= 710
checkUnicode :: KeywordId -> GHC.SrcSpan -> KeywordId
checkUnicode gkw@(G kw) ss =
  if kw `Set.member` unicodeSyntax
    then
      let s = keywordToString gkw in
      if (length s /= spanLength ss)
        then AnnUnicode kw
        else gkw
  else
    gkw
  where
    unicodeSyntax = Set.fromList
      [ GHC.AnnDcolon
      , GHC.AnnDarrow
      , GHC.AnnForall
      , GHC.AnnRarrow
      , GHC.AnnLarrow
      , GHC.Annlarrowtail
      , GHC.Annrarrowtail
      , GHC.AnnLarrowtail
      , GHC.AnnRarrowtail]
checkUnicode kwid _ = kwid
#else

unicodeEquivalent :: GHC.AnnKeywordId -> [GHC.AnnKeywordId]
unicodeEquivalent kw =
  case Map.lookup kw unicodeSyntax of
    Nothing -> []
    Just kwu -> [kwu]
  where
    unicodeSyntax = Map.fromList
      [ (GHC.AnnDcolon,     GHC.AnnDcolonU)
      , (GHC.AnnDarrow,     GHC.AnnDarrowU)
      , (GHC.AnnForall,     GHC.AnnForallU)
      , (GHC.AnnRarrow,     GHC.AnnRarrowU)
      , (GHC.AnnLarrow,     GHC.AnnLarrowU)
      , (GHC.Annlarrowtail, GHC.AnnlarrowtailU)
      , (GHC.Annrarrowtail, GHC.AnnrarrowtailU)
      , (GHC.AnnLarrowtail, GHC.AnnLarrowtailU)
      , (GHC.AnnRarrowtail, GHC.AnnRarrowtailU)]
#endif

-- ---------------------------------------------------------------------

commentAllocation :: (Comment -> Bool)
                  -> ([(Comment, DeltaPos)] -> Delta a)
                  -> Delta a
commentAllocation p k = do
  cs <- getUnallocatedComments
  let (allocated,cs') = allocateComments p cs
  putUnallocatedComments cs'
  k =<< mapM makeDeltaComment (sortBy (comparing commentIdentifier) allocated)

makeDeltaComment :: Comment -> Delta (Comment, DeltaPos)
makeDeltaComment c = do
  let pa = commentIdentifier c
  pe <- getPriorEnd
  let p = ss2delta pe pa
  p' <- adjustDeltaForOffsetM p
  setPriorEnd (ss2posEnd pa)
  return $ (c, p')

addDeltaComment :: Comment -> DeltaPos -> Delta ()
addDeltaComment d p = do
  addAnnDeltaPos (AnnComment d) p

-- ---------------------------------------------------------------------

-- | Look up and add a Delta annotation at the current position, and
-- advance the position to the end of the annotation
addDeltaAnnotation :: GHC.AnnKeywordId -> Delta ()
addDeltaAnnotation ann' = do
  ss <- getSrcSpan
  (ma,ann) <- getOneAnnotationDelta ann'
  case nub ma of -- ++AZ++ TODO: get rid of duplicates earlier
    []     -> return () `debug` ("addDeltaAnnotation empty ma for:" ++ show (ss,ann))
    [pa]   -> addAnnotationWorker (G ann) pa
    (pa:_) -> addAnnotationWorker (G ann) pa `warn` ("addDeltaAnnotation:(ss,ann,ma)=" ++ showGhc (ss,ann,ma))

-- | Look up and add a Delta annotation at the current position, and
-- advance the position to the end of the annotation
addDeltaAnnotationLs :: GHC.AnnKeywordId -> Int -> Delta ()
addDeltaAnnotationLs ann off = do
  ss <- getSrcSpan
  ma <- peekAnnotationDelta ann
  let ma' = filter (\s -> (GHC.isSubspanOf s ss)) ma
  case drop off ma' of
    [] -> return ()
        `debug` ("addDeltaAnnotationLs:missed:(off,ann,ma)=" ++ showGhc (off,ss,ann))
    (pa:_) -> addAnnotationWorker (G ann) pa

-- | Look up and add possibly multiple Delta annotation at the current
-- position, and advance the position to the end of the annotations
addDeltaAnnotations :: GHC.AnnKeywordId -> Delta ()
addDeltaAnnotations ann = do
  (ma,kw) <- getAnnotationDelta ann
  let do_one ap' = addAnnotationWorker (G kw) ap'
                    `debug` ("addDeltaAnnotations:do_one:(ap',ann)=" ++ showGhc (ap',ann))
  mapM_ do_one (sort ma)

-- | Look up and add possibly multiple Delta annotations enclosed by
-- the current SrcSpan at the current position, and advance the
-- position to the end of the annotations
addDeltaAnnotationsInside :: GHC.AnnKeywordId -> Delta ()
addDeltaAnnotationsInside ann = do
  ss <- getSrcSpan
  ma <- peekAnnotationDelta ann
  let do_one ap' = addAnnotationWorker (G ann) ap'
                    -- `debug` ("addDeltaAnnotations:do_one:(ap',ann)=" ++ showGhc (ap',ann))
  let filtered = sort $ filter (\s -> GHC.isSubspanOf s ss) ma
  mapM_ do_one filtered

-- | Look up and add possibly multiple Delta annotations not enclosed by
-- the current SrcSpan at the current position, and advance the
-- position to the end of the annotations
-- The first argument (gann) is the one to look up in the GHC annotations, the
-- second is the one to apply in the ghc-exactprint ones. These are different
-- for GHC.AnnSemi mapping to AnnSemiSep, to ensure that it reflects the ';'
-- outside the current span.
addDeltaAnnotationsOutside :: GHC.AnnKeywordId -> KeywordId -> Delta ()
addDeltaAnnotationsOutside gann ann = do
  ss <- getSrcSpan
  (ma,kw) <- getAndRemoveAnnotationDelta ss gann
  let do_one ap' = if ann == AnnSemiSep
                     then addAnnotationWorker ann    ap'
                     else addAnnotationWorker (G kw) ap'
  mapM_ do_one (sort $ filter (\s -> not (GHC.isSubspanOf s ss)) ma)

-- | Add a Delta annotation at the current position, and advance the
-- position to the end of the annotation
addDeltaAnnotationExt :: GHC.SrcSpan -> GHC.AnnKeywordId -> Delta ()
addDeltaAnnotationExt s ann = addAnnotationWorker (G ann) s

addEofAnnotation :: Delta ()
addEofAnnotation = do
  pe <- getPriorEnd
  (ma,_kw) <- withSrcSpanDelta (GHC.noLoc ()) (getAnnotationDelta GHC.AnnEofPos)
  case ma of
    [] -> return ()
    (pa:pss) -> do
      commentAllocation (const True) (mapM_ (uncurry addDeltaComment))
      let DP (r,c) = ss2delta pe pa
      addAnnDeltaPos (G GHC.AnnEofPos) (DP (r, c - 1))
      setPriorEndAST pa `warn` ("Trailing annotations after Eof: " ++ showGhc pss)

countAnnsDelta :: GHC.AnnKeywordId -> Delta Int
countAnnsDelta ann = do
  ma <- peekAnnotationDelta ann
  return (length ma)


text:
package com.luolei.template;

/**
 * @author luolei
 * @email askluolei@gmail.com
 * @date 2017/10/12 22:51
 */
public class TemplateApplicationTest {

}


text:
import { Routes, RouterModule } from '@angular/router';

import { WeatherComponent } from './weather.component';

const routes: Routes = [
    { path: '', component: WeatherComponent }
];

export const routing = RouterModule.forChild(routes);


text:
name             'roundcube_test'
maintainer       'Xabier de Zuazo'
maintainer_email 'xabier@zuazo.org'
license          'Apache 2.0'
description      'This cookbook is used with test-kitchen to test the parent, '\
                 'roundcube cookbook'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.1.0'

depends 'roundcube'
depends 'nokogiri', '~> 0.1.4'


text:
import React, { Component } from 'react';
import ImageUpload from './ImageUpload';
import _ from 'lodash';

const REG_VALID_URL = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
const REG_VALID_TWITTER_USERNAME = /^@?([a-zA-Z0-9_]{1,15})$/;
const PRESET_AVATARS = [
  '/static/images/users/icon-avatar-placeholder.svg',
  '/static/images/users/avatar-02.svg',
  '/static/images/users/avatar-03.svg',
  '/static/images/users/avatar-04.svg',
];
const UPLOAD_AVATAR = '/static/images/users/upload-default.svg';
const UPLOAD_AVATAR_HOVER = '/static/images/users/upload-hover.svg';
const UPLOAD_AVATAR_ACTIVE = '/static/images/users/upload-pressed.svg';
const KNOWN_SOURCES = {
  'facebook': '/static/images/users/facebook-badge.svg',
  'twitter': '/static/images/users/twitter-badge.svg',
  'google': '/static/images/users/google-badge.svg',
  'github': '/static/images/users/github-badge.svg',
  'gravatar': '/static/images/users/gravatar-badge.svg',
  'angelist': '/static/images/users/angelist-badge.svg',
  'aboutme': '/static/images/users/aboutme-badge.svg',
}

export default class ImagePicker extends Component {

  constructor(props) {
    super(props);
    this.blacklist = [];
    this.options = PRESET_AVATARS.map(src => {return {source: 'preset', src: src}});

    if (props.src)
    {
      this.options[0].src = props.src;
      this.options[0].source = 'default';
    }

    this.options.push({
      source: 'upload',
      src: UPLOAD_AVATAR
    });

    this.state = {
      isLoading: false,
      currentIndex: 0,
      twitter: '',
      website: ''
    };

    this.lazyLookupSocialMediaAvatars = _.debounce(this.lookupSocialMediaAvatars.bind(this), 600);
  }

  render() {
    const {className='avatar'} = this.props;
    const {isLoading, currentIndex, hover, pressed} = this.state;
    const options = this.options;
    const currentOption = options[currentIndex];
    let currentSrc =  currentOption.src;

    // Update Hover/Press images for upload option
    if (hover && currentOption.source === 'upload' && currentOption.src.indexOf('/static') === 0)
    {
      currentSrc = (pressed) ? UPLOAD_AVATAR_ACTIVE : UPLOAD_AVATAR_HOVER;
    }

    return (
      <div className={`ImagePicker-container ${className}`}>

Choose a Profile Image

 this.avatarClick.call(this, currentOption)} onMouseOver={() => this.setState({'hover': true})} onMouseOut={() => this.setState({'hover': false, pressed: false})} onMouseDown={() => this.setState({'pressed': true})} onMouseUp={() => this.setState({'pressed': false})}>

          {options.map(
            option => {
              return
 this.select.call(this, option)} className={option === options[currentIndex] ? 'selected' : ''}>
;
            }
          )}

          <ImageUpload ref="ImageUpload" isUploading={false} onFinished={this.onUploadFinished.bind(this)} {...this.props} />

    );
  }

  componentWillReceiveProps(nextProps) {
    const {website, twitter} = nextProps;

    if (website !== this.state.website || twitter !== this.state.twitter)
    {
      const nextStateWebsite = REG_VALID_URL.test(website) ? website : '';
      const nextStateTwitter = REG_VALID_TWITTER_USERNAME.test(twitter) ? REG_VALID_TWITTER_USERNAME.exec(twitter)[1] : '';

      if (nextStateWebsite !== this.state.website || nextStateTwitter !== this.state.twitter)
      {
        this.state.twitter = nextStateTwitter;
        this.state.website = nextStateWebsite;

        if (this.state.twitter || this.state.website)
        {
          this.lazyLookupSocialMediaAvatars(this.state.website, this.state.twitter);
        }
      }
    }
  }

  onImageError()
  {
    const currentOption = this.options[this.state.currentIndex];
    if (this.blacklist.indexOf(currentOption.src) === -1)
    {
      this.blacklist.push(currentOption.src);
    }

    this.options.splice(this.state.currentIndex, 1);

    if (!this.options[this.state.currentIndex])
    {
      this.setState({currentIndex: 0}, this.thereWasAChange);
    }
    else
    {
      this.forceUpdate(this.thereWasAChange);
    }
  }

  thereWasAChange()
  {
    const currentOption = this.options[this.state.currentIndex];
    this.props.handleChange(currentOption.src !== UPLOAD_AVATAR ? currentOption.src : PRESET_AVATARS[0]);
  }

  nextIsPossible()
  {
    return this.state.currentIndex < this.options.length - 1;
  }

  prevIsPossible()
  {
    return this.state.currentIndex > 0;
  }

  select(option)
  {
    if (this.state.isLoading) return;
    this.setState({currentIndex: this.options.indexOf(option)}, this.thereWasAChange);
  }

  next()
  {
    if (this.state.isLoading) return;
    if (this.nextIsPossible())
    {
      this.setState({currentIndex: this.state.currentIndex + 1}, this.thereWasAChange);
    }
  }

  prev()
  {
    if (this.state.isLoading) return;
    if (this.prevIsPossible())
    {
      this.setState({currentIndex: this.state.currentIndex - 1}, this.thereWasAChange);
    }
  }

  avatarClick(option)
  {
    if (option.source === 'preset' || option.source === 'upload')
    {
      this.refs.ImageUpload.clickInput();
    }
  }

  onUploadFinished(result)
  {
    if (result)
    {
      const uploadOption = this.options.reduce((prev, curr) => prev.source === 'upload' ? prev : curr);
      uploadOption.src = result.url;
      this.setState({currentIndex: this.options.indexOf(uploadOption)});
      this.thereWasAChange();
    }
  }

  lookupSocialMediaAvatars(website, twitter)
  {
    const { profileForm, newUser, getSocialMediaAvatars } = this.props;

    if (!this.state.isLoading)
    {
      this.setState({isLoading: true});
    }

    getSocialMediaAvatars(newUser.id, {website: website, twitterHandle: twitter, name: profileForm.name})
    .then((response) => {
      const currentOption = this.options[this.state.currentIndex];
      const results = response.json.filter((option) => this.blacklist.indexOf(option.src) === -1 );
      let isFirstTime = false;

      results.forEach(result => {
        const existingOption = this.options.filter((option) => {return option.source === result.source})[0];
        if (existingOption)
        {
          existingOption.src = result.src;
        }
        else
        {
          if (this.options[0].source === 'preset')
          {
            this.options[0].source = result.source;
            this.options[0].src = result.src;
            isFirstTime = true;
          }
          else
          {
            this.options.splice(0, 0, result);
          }
        }
      });

      this.setState({currentIndex: isFirstTime ? 0 : this.options.indexOf(currentOption), isLoading: false}, this.thereWasAChange);
    })
    .catch((error) => {
      console.error(error);
      this.setState({isLoading: false});
    })
  }
}


text:
module.exports = function (chai, utils) {

	var Assertion = chai.Assertion;
	var flag = utils.flag;
	var assert = chai.assert;

	var fs = require('fs');

	//-------------------------------------------------------------------------------------------------------------

	Assertion.addMethod('file', function (msg) {
		var preMsg = '';
		if (msg) {
			flag(this, 'message', msg);
			preMsg = msg + ': ';
		}

		var obj = this._obj;

		new chai.Assertion(obj, preMsg + 'value').is.a('string');
		new chai.Assertion(obj, preMsg + 'value').to.be.a.path();

		var pass = fs.statSync(obj).isFile();

		flag(this, 'fs.isFile', pass);

		this.assert(
			pass
			, "expected #{this} to be a file"
			, "expected #{this} not to be a file"
		);
	});
	assert.isFile = function (val, msg) {
		new chai.Assertion(val).to.be.a.file(msg);
	};
	assert.notIsFile = function (val, msg) {
		new chai.Assertion(val).to.not.be.a.file(msg);
	};

	//-------------------------------------------------------------------------------------------------------------

	Assertion.addOverwritePropertyFlag('empty', 'fs.isFile', function (obj) {

		var pass = fs.statSync(obj).size === 0;
		var test = new Assertion(obj, flag(this, 'message'));

		//TODO verify this if/else makes sense
		if (flag(this, 'negate')) {
			test.assert(
				!pass
				, "expected #{this} not to be an empty file"
				, "expected #{this} to be an empty file"
			);
		}
		else {
			test.assert(
				pass
				, "expected #{this} to be an empty file"
				, "expected #{this} not to be an empty file"
			);
		}
	});

	assert.isEmptyFile = function (val, msg) {
		/* jshint -W030 */
		new chai.Assertion(val).to.be.a.file(msg).and.empty;
	};
	assert.notIsEmptyFile = function (val, msg) {
		/* jshint -W030 */
		new chai.Assertion(val).to.be.a.file(msg).and.not.empty;
	};

	//-------------------------------------------------------------------------------------------------------------

	Assertion.addProperty('json', function () {
		var obj = this._obj;

		if (!flag(this, 'fs.isFile')) {
			this.assert(
				false
				, "expected #{this} to be chained after file()"
			);
		}

		var pass = true;
		var json = false;
		var content = flag(this, 'utf8Content');
		if (!content) {
			content = fs.readFileSync(obj, 'utf8');
			flag(this, 'utf8Content', content);
		}

		try {
			json = JSON.parse(content);
			flag(this, 'isJson', true);
			flag(this, 'jsonContent', json);
		}
		catch (e) {
			pass = false;
		}

		flag(this, 'fs.isJsonFile', pass);

		this.assert(
			pass
			, "expected #{this} to be an json file"
			, "expected #{this} not to be an json file"
		);
	});
	/*Assertion.addOverwritePropertyFlag('json', 'fs.isFile', function (obj) {
		console.log('json fs.isFile');
		console.log(obj);

		if (!flag(this, 'fs.isFile')) {
			this.assert(
				false
				, "expected #{this} to be chained after file()"
			);
		}

		var pass = true;
		var json = false;
		var content = flag(this, 'utf8Content');
		try {
			if (!content) {
				content = fs.readFileSync(obj, 'utf8');
				flag(this, 'utf8Content', content);
			}
			json = JSON.parse(content);
			flag(this, 'isJson', true);
			flag(this, 'jsonContent', json);
		}
		catch (e) {
			pass = false;
		}
		flag(this, 'fs.isJsonFile', pass);

		this.assert(
			pass
			, "expected #{this} to be an json file"
			, "expected #{this} not to be an json file"
		);
	});*/

	assert.jsonFile = function (val, msg) {
		/* jshint -W030 */
		new chai.Assertion(val).to.be.a.file(msg).with.json;
	};
	assert.notJsonFile = function (val, msg) {
		/* jshint -W030 */
		new chai.Assertion(val).to.be.a.file(msg).not.with.json;
	};

	//-------------------------------------------------------------------------------------------------------------

	Assertion.addMethod('schema', function (schema) {
		//var obj = this._obj;

		assert.isFunction(assert.jsonSchema, 'expected chai-json-schema dependency (assert.jsonSchema)');
		assert.isFunction(assert.notJsonSchema, 'expected chai-json-schema dependency (assert.notJsonSchema)');

		if (!flag(this, 'isJson')) {
			this.assert(
				false
				, "expected #{this} to be chained after a isJson"
			);
		}
		if (!flag(this, 'jsonContent')) {
			this.assert(
				false
				, "expected #{this} to be chained after a jsonContent"
			);
		}

		var json = flag(this, 'jsonContent');

		if (flag(this, 'negate')) {
			assert.notJsonSchema(json, schema, flag(this, 'message'));
		}
		else {
			assert.jsonSchema(json, schema, flag(this, 'message'));
		}
	});

	assert.jsonSchemaFile = function (val, schema, msg) {
		new chai.Assertion(val).to.be.a.file(msg).with.json.schema(schema);
	};
	assert.notJsonSchemaFile = function (val, schema, msg) {
		new chai.Assertion(val).to.be.a.file(msg).with.json.not.schema(schema);
	};

};


text:
from unittest import TestCase
from unittest.mock import patch

from src import calling_cost_for_countries

class ModuleTest(TestCase):
    @patch("src.module.repository")
    def test_calling_cost_for_countries(self, repository_mock):
        repository_costs_result = {
            "country A": "2 pounds",
            "country B": "3 pounds"
        }
        repository_mock.cost_for_countries.return_value = repository_costs_result

        costs = calling_cost_for_countries(
            countries=["country A", "country B"]
        )
        self.assertEqual(repository_costs_result, costs)


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2015 Hippo Seven
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_save"
        android:title="@string/save"
        android:icon="@drawable/v_content_save_dark_x24"
        app:showAsAction="always"/>

    <item
        android:id="@+id/action_share"
        android:title="@string/save"
        android:icon="@drawable/v_share_dark_x24"
        app:showAsAction="ifRoom"/>

    <item
        android:id="@+id/action_refresh"
        android:title="@string/refresh"
        android:icon="@drawable/v_refresh_dark_x24"
        app:showAsAction="ifRoom"/>

</menu>


text:
package org.apache.beehive.netui.compiler.grammar;

import org.apache.beehive.netui.compiler.Diagnostics;
import org.apache.beehive.netui.compiler.FlowControllerInfo;
import org.apache.beehive.netui.compiler.RuntimeVersionChecker;
import org.apache.beehive.netui.compiler.typesystem.declaration.ClassDeclaration;
import org.apache.beehive.netui.compiler.typesystem.env.CoreAnnotationProcessorEnv;

public class CommandHandlerGrammar
        extends BaseFlowControllerGrammar
{
    public CommandHandlerGrammar( CoreAnnotationProcessorEnv env, Diagnostics diags, RuntimeVersionChecker rvc,
                                  ClassDeclaration jpfClass, FlowControllerInfo fcInfo )
    {
        super( env, diags, null, rvc, fcInfo );
        addMemberArrayGrammar( RAISE_ACTIONS_ATTR, new RaiseActionGrammar( env, diags, null, rvc, jpfClass, fcInfo ) );
    }
}


text:
/*
Language: Twig
Requires: xml.js
Author: Luke Holder <lukemh@gmail.com>
Description: Twig is a templating language for PHP
Website: https://twig.symfony.com
Category: template
*/

function(hljs) {
  var PARAMS = {
    className: 'params',
    begin: '\\(', end: '\\)'
  };

  var FUNCTION_NAMES = 'attribute block constant cycle date dump include ' +
                  'max min parent random range source template_from_string';

  var FUNCTIONS = {
    beginKeywords: FUNCTION_NAMES,
    keywords: {name: FUNCTION_NAMES},
    relevance: 0,
    contains: [
      PARAMS
    ]
  };

  var FILTER = {
    begin: /\|[A-Za-z_]+:?/,
    keywords:
      'abs batch capitalize column convert_encoding date date_modify default ' +
      'escape filter first format inky_to_html inline_css join json_encode keys last ' +
      'length lower map markdown merge nl2br number_format raw reduce replace ' +
      'reverse round slice sort spaceless split striptags title trim upper url_encode',
    contains: [
      FUNCTIONS
    ]
  };

  var TAGS = 'apply autoescape block deprecated do embed extends filter flush for from ' +
    'if import include macro sandbox set use verbatim with';

  TAGS = TAGS + ' ' + TAGS.split(' ').map(function(t){return 'end' + t}).join(' ');

  return {
    aliases: ['craftcms'],
    case_insensitive: true,
    subLanguage: 'xml',
    contains: [
      hljs.COMMENT(/\{#/, /#}/),
      {
        className: 'template-tag',
        begin: /\{%/, end: /%}/,
        contains: [
          {
            className: 'name',
            begin: /\w+/,
            keywords: TAGS,
            starts: {
              endsWithParent: true,
              contains: [FILTER, FUNCTIONS],
              relevance: 0
            }
          }
        ]
      },
      {
        className: 'template-variable',
        begin: /\{\{/, end: /}}/,
        contains: ['self', FILTER, FUNCTIONS]
      }
    ]
  };
}


text:
package info.hupel.isabelle.setup

import java.nio.charset.Charset
import java.nio.file._

import scala.collection.JavaConverters._
import scala.io.Source

import cats.instances.either._
import cats.instances.list._
import cats.syntax.traverse._

import org.log4s._

import info.hupel.isabelle.api.Configuration

/** Utilities to extract [[Resources resources]] from the classpath. */
object Resources {

  sealed abstract class Error(val explain: String)
  case object Absent extends Error("No resources found in classpath")
  case class DuplicatedFiles(files: List[String]) extends Error(s"Duplicated resources in classpath: ${files.mkString(", ")}")
  case class MissingFiles(files: List[String]) extends Error(s"Missing files in classpath: ${files.mkString(", ")}")

  private val logger = getLogger

  /**
   * Shorthand for `[[dumpIsabelleResources(path* dumpIsabelleResources]]
   * using a temporary path and the current class loader.
   */
  def dumpIsabelleResources(): Either[Error, Resources] =
    dumpIsabelleResources(Files.createTempDirectory("libisabelle_resources"), getClass.getClassLoader)

  /**
   * Searches the specified class loader for Isabelle source files.
   *
   * Isabelle sources files can be automatically managed by `libisabelle`. When
   * using an SBT-based build, the
   * `[[https://github.com/larsrh/sbt-libisabelle sbt-libisabelle]]` plugin
   * automatically configures the build to copy the Isabelle sources stored in
   * `src/main/isabelle` into an appropriate location such that they become
   * part of the runtime classpath.
   *
   * This function expects any number of index files in the location
   * `.libisabelle/.files`, containing a list of relative path names where
   * Isabelle source files may be found. For example, an entry `A/tactic.ML`
   * will lead to a lookup for a resource at `.libisabelle/A/tactic.ML`. All
   * index files will be processed. The referenced files will be copied to
   * the specified location. Path names are expected to be encoded in UTF-8,
   * which is the standard encoding Isabelle uses.
   *
   * The specified path will then be turned into an Isabelle "component" (refer
   * to the Isabelle system manual for information about components) by
   * creating an `etc/settings` file, which we will call ''resources
   * component''. The root directory of the resources component is available
   * in the environment variable `LIBISABELLE_RESOURCES_HOME`.
   *
   * Resources are checked for contained components and session root
   * directories. This is done by looking for `ROOT`, `ROOTS`, and
   * `etc/settings` in direct subdirectories that have been created below the
   * specified path. Components are added as subcomponents to the resources
   * component (`\$LIBISABELLE_RESOURCES_HOME/etc/components`) and session root
   * directories to `\$LIBISABELLE_RESOURCES_HOME/ROOTS`. Session roots that are
   * also components are only added as components, because components are
   * automatically discovered as session roots.
   *
   * Note that this will only work correctly if the specified path ultimately
   * gets registered as an Isabelle component. Otherwise, subcomponents that
   * are also session roots do not get discovered properly.
   */
  def dumpIsabelleResources(path: Path, classLoader: ClassLoader): Either[Error, Resources] = {
    val files = classLoader.getResources(".libisabelle/.files").asScala.toList.flatMap { url =>
      logger.debug(s"Found Isabelle resource set at $url")
      Source.fromURL(url, "UTF-8").getLines.toList
    }.filterNot(_.isEmpty)

    def filterFor(markers: String*) =
      (for {
        file <- files
        subdir = Paths.get(file).subpath(0, 1)
        if markers.exists(m => files.contains(s"$subdir/$m"))
      } yield subdir).distinct

    def writeList(target: Path, list: List[Path]) = {
      val out = Files.newBufferedWriter(target, Charset.forName("UTF-8"), StandardOpenOption.CREATE_NEW)
      out.write(list.distinct.mkString("\n"))
      out.close()
    }

    if (files.nonEmpty) {
      logger.debug(s"Dumping Isabelle resources to $path ...")

      if (files.distinct != files) {
        val fileSet = files.toSet
        val duplicates = files diff fileSet.toList
        Left(DuplicatedFiles(duplicates))
      }
      else {
        val result = files.traverse { file =>
          val target = path resolve file
          Files.createDirectories(target.getParent)
          val in = classLoader.getResourceAsStream(s".libisabelle/$file")
          if (in == null) {
            Left(List(file))
          }
          else {
            Files.copy(in, target)
            in.close()
            Right(())
          }
        }

        result match {
          case Left(files) =>
            Left(MissingFiles(files))
          case Right(_) =>
            val components = filterFor("etc/settings")
            components.foreach(subdir => logger.debug(s"Found component at $path/$subdir"))
            val target = path resolve "etc"
            Files.createDirectories(target)
            writeList(target resolve "components", components)

            val roots = filterFor("ROOT", "ROOTS")
            roots.foreach(subdir => logger.debug(s"Found session root at $path/$subdir"))
            writeList(path resolve "ROOTS", roots diff components)

            val out = Files.newBufferedWriter(target resolve "settings", Charset.forName("UTF-8"), StandardOpenOption.CREATE_NEW)
            out.write("""LIBISABELLE_RESOURCES_HOME="$COMPONENT"""")
            out.close()

            Right(Resources(path, roots.map(path.resolve)))
        }
      }
    }
    else {
      Left(Absent)
    }
  }

}

/**
 * A file system location containing Isabelle sources.
 *
 * In almost all cases, instances of this object should be produced using
 * `[[Resources.dumpIsabelleResources(path* Resources.dumpIsabelleResources]]`
 * (see its documentation for details).
 */
final case class Resources private(component: Path, roots: List[Path]) {

  /**
   * Produces a [[info.hupel.isabelle.api.Configuration configuration]] with
   * the specified paths, preceded by the location from this object.
   */
  def asSessionsConfiguration(auxPaths: List[Path], name: String): Configuration =
    Configuration(roots ::: auxPaths, name)

  /**
   * Checks presence of a theory file in this location. The input path should
   * be a relative file name (e.g. `src/HOL/ex/Seq.thy`). If present, the
   * output is an Isabelle-conforming theory import path
   * (e.g. `src/HOL/ex/Seq`).
   */
  def findTheory(theory: Path): Option[String] = {
    val fullPath = component.resolve(theory)
    if (Files.exists(fullPath))
      Some(fullPath.toRealPath().toString.stripSuffix(".thy"))
    else
      None
  }

}


text:
/**
 * @fileoverview Externs for prefixed EME v20140218 as supported by IE11/Edge
 * (http://www.w3.org/TR/2014/WD-encrypted-media-20140218).
 * @externs
 */

/**
 * @constructor
 * @param {string} keySystem
 */
function WebKitMediaKeys(keySystem) {}

/**
 * @param {string} keySystem
 * @param {string} contentType
 * @return {boolean}
 */
WebKitMediaKeys.isTypeSupported = function(keySystem, contentType) {};

/**
 * @param {string} contentType
 * @param {Uint8Array} initData
 * @return {!WebKitMediaKeySession}
 */
WebKitMediaKeys.prototype.createSession = function(contentType, initData) {};

/**
 * @interface
 * @extends {EventTarget}
 */
function WebKitMediaKeySession() {}

/**
 * @param {Uint8Array} message
 */
WebKitMediaKeySession.prototype.update = function(message) {};

WebKitMediaKeySession.prototype.close = function() {};

/** @type {string} */
WebKitMediaKeySession.prototype.sessionId;

/** @type {WebKitMediaKeyError} */
WebKitMediaKeySession.prototype.error;

/** @override */
WebKitMediaKeySession.prototype.addEventListener =
    function(type, listener, useCapture) {};

/** @override */
WebKitMediaKeySession.prototype.removeEventListener =
    function(type, listener, useCapture) {};

/** @override */
WebKitMediaKeySession.prototype.dispatchEvent = function(evt) {};

/**
 * @param {WebKitMediaKeys} mediaKeys
 */
HTMLMediaElement.prototype.webkitSetMediaKeys = function(mediaKeys) {};

/** @type {WebKitMediaKeys} */
HTMLMediaElement.prototype.webkitKeys;

/** @constructor */
function WebKitMediaKeyError() {}

/** @type {number} */
WebKitMediaKeyError.prototype.code;

/** @type {number} */
WebKitMediaKeyError.prototype.systemCode;

/** @type {number} */
WebKitMediaKeyError.MEDIA_KEYERR_UNKNOWN;

/** @type {number} */
WebKitMediaKeyError.MEDIA_KEYERR_CLIENT;

/** @type {number} */
WebKitMediaKeyError.MEDIA_KEYERR_SERVICE;

/** @type {number} */
WebKitMediaKeyError.MEDIA_KEYERR_OUTPUT;

/** @type {number} */
WebKitMediaKeyError.MEDIA_KEYERR_HARDWARECHANGE;

/** @type {number} */
WebKitMediaKeyError.MEDIA_KEYERR_DOMAIN;


text:
SPK_NAME = nzbconfig
SPK_VERS = 0.7
SPK_REV = 3
SPK_ICON = src/nzbconfig.png
DSM_UI_DIR = app
DSM_APP_NAME = SYNOCOMMUNITY.NZBConfig.AppInstance

SPK_DEPENDS = "python>2.7.3-3"

MAINTAINER = SynoCommunity
DESCRIPTION = Configuration interface for your packages SABnzbd, NZBGet, SickBeard, SickBeard Custom, CouchPotato and Headphones
DESCRIPTION_FRE = Interface de configuration pour vos paquets SABnzbd, NZBGet, SickBeard, SickBeard Custom, CouchPotato et Headphones
DESCRIPTION_SPN = Interfaz de configuración para los paquetes SABnzbd, NZBGet, SickBeard, SickBeard Custom, CouchPotato y Headphones
RELOAD_UI = yes
DISPLAY_NAME = NZB Config
CHANGELOG = "1. Add support for SickBeard Custom"

INSTALLER_SCRIPT = src/installer.sh
SSS_SCRIPT       = src/dsm-control.sh

INSTALL_PREFIX = /usr/local/$(SPK_NAME)

COPY_TARGET = nop
POST_STRIP_TARGET = nzbconfig_extra_install

override ARCH=

include ../../mk/spksrc.spk.mk

.PHONY: nzbconfig_extra_install
nzbconfig_extra_install: $(STAGING_DIR)/share/requirements.pybundle
	install -m 755 -d $(STAGING_DIR)/var
	install -m 755 -d $(STAGING_DIR)/app
	install -m 644 src/app/config $(STAGING_DIR)/app/config
	install -m 644 src/app/nzbconfig.js $(STAGING_DIR)/app/nzbconfig.js
	install -m 644 src/app/style.css $(STAGING_DIR)/app/style.css
	install -m 755 src/app/nzbconfig.cgi.py $(STAGING_DIR)/app/nzbconfig.cgi
	install -m 755 -d $(STAGING_DIR)/app/application
	install -m 644 src/app/application/* $(STAGING_DIR)/app/application/
	install -m 755 -d $(STAGING_DIR)/app/texts
	for language in enu fre; do \
		install -m 755 -d $(STAGING_DIR)/app/texts/$${language}; \
		install -m 644 src/app/texts/$${language}/strings $(STAGING_DIR)/app/texts/$${language}/strings; \
	done
	install -m 755 -d $(STAGING_DIR)/app/images
	for size in 16 24 32 48; do \
		convert $(SPK_ICON) -thumbnail $${size}x$${size} \
		        $(STAGING_DIR)/app/images/$(SPK_NAME)-$${size}.png ; \
	done
	install -m 644 src/app/images/* $(STAGING_DIR)/app/images/

$(STAGING_DIR)/share/requirements.pybundle:
	@$(MSG) "Bundling requirements"
	install -m 755 -d $(STAGING_DIR)/share
	@cd $(WORK_DIR) && $(PIP) bundle $@ pyextdirect==0.3.1 configobj flask


text:
import '../../scss/common/main.scss'
import '../Tab/Tab'
import '../Shift/Shift'

import baseMixin from '../../mixin/base'

import template from './TabPanel.tpl'
import './TabPanel.scss'

const tabPanelComp = {
  name: 'TabPanel',

  mixins: [baseMixin],

  template,

  props: {
    theme: {
      type: String,
      default: 'primary'
    },

    tabItems: {
      type: Array,
      required: true
    }
  },

  data: function () {
    return {
      themeClass: this.theme ? `theme-${this.theme}` : '',
      panelItems: {},
      currentIndex: 0,
      currentItem: '',
      compileVm: this.$parent,
      switchingIndex: 0
    }
  },

  methods: {
    _initPanel() {
      var optionContent = this.$options._content
      var switchinghtml = ''

      for (let i = 0; i < this.tabItems.length; i++) {
        var slotEle = optionContent['children'][i].innerHTML

        switchinghtml += `

${slotEle}

        `
      }
      this.$tpl = $(this.$options.template)
      this.$tpl.find('.panel-wrap').html(switchinghtml)
    },

    /**
     * @param { String } - tab 的 name 值
     */
    _findIndex(name) {
      var currentIndex = 0

      this.tabItems.every((item, index) => {
        if (item.name === name) {
          currentIndex = index

          return false
        }
        return true
      })

      return currentIndex
    },

    /**
     * @param { Number }
     */
    switchPanel(index) {
      this.switchingIndex = index

      return this
    }
  },

  mounted() {
    var dom = this.$tpl[0]
    this.$compile(dom)
    this.$el = dom

    // 自动根据网址的 query 的 tab 值来转换 tab 状态
    this.switchPanel(this._findIndex(this.$route.query.tab))
  },

  created() {
    this._initPanel()
  }
}

export default tabPanelComp


text:
<!doctype html>

  <meta charset="utf-8">
  <title i18n-content="devicesTitle"></title>
  <link rel="stylesheet" href="chrome://resources/css/chrome_shared.css">
  <link rel="stylesheet" href="chrome://resources/css/overlay.css">
  <link rel="stylesheet" href="chrome://resources/css/spinner.css">
  <link rel="stylesheet" href="local_discovery.css">

              <button class="register-cancel" i18n-content="cancel"></button>
              <button id="register-continue-button"
                      i18n-content="serviceRegister">
              </button>

              <button class="register-cancel" i18n-content="cancel"></button>

              <button class="register-cancel" i18n-content="cancel"></button>

              <button class="register-cancel" i18n-content="cancel"></button>

              <button class="register-cancel" i18n-content="cancel"></button>
              <button class="confirm-code" i18n-content="confirmCode"></button>

              <button id="register-error-exit" i18n-content="ok"></button>

      <if expr="not chromeos">

            <button id="cloudPrintConnectorSetupButton"></button>

      </if>


text:
package com.opengamma.strata.measure.capfloor;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.index.Index;
import com.opengamma.strata.calc.Measure;
import com.opengamma.strata.calc.runner.CalculationFunction;
import com.opengamma.strata.calc.runner.CalculationParameters;
import com.opengamma.strata.calc.runner.FunctionRequirements;
import com.opengamma.strata.collect.result.FailureReason;
import com.opengamma.strata.collect.result.Result;
import com.opengamma.strata.data.scenario.ScenarioMarketData;
import com.opengamma.strata.measure.Measures;
import com.opengamma.strata.measure.rate.RatesMarketDataLookup;
import com.opengamma.strata.measure.rate.RatesScenarioMarketData;
import com.opengamma.strata.product.capfloor.IborCapFloor;
import com.opengamma.strata.product.capfloor.IborCapFloorTrade;
import com.opengamma.strata.product.capfloor.ResolvedIborCapFloorTrade;

/**
 * Perform calculations on a single {@code IborCapFloorTrade} for each of a set of scenarios.
 *

 * This uses Black, Normal or SABR cap/floor volatilities,
 * which must be specified using {@link IborCapFloorMarketDataLookup}.
 * An instance of {@link RatesMarketDataLookup} must also be specified.
 *

 * The supported built-in measures are:
 *

 *
{@linkplain Measures#PRESENT_VALUE Present value}
 *
{@linkplain Measures#PV01_CALIBRATED_SUM PV01 calibrated sum on rate curves}
 *
{@linkplain Measures#PV01_CALIBRATED_BUCKETED PV01 calibrated bucketed on rate curves}
 *
{@linkplain Measures#PV01_MARKET_QUOTE_SUM PV01 market quote sum on rate curves}
 *
{@linkplain Measures#PV01_MARKET_QUOTE_BUCKETED PV01 market quote bucketed on rate curves}
 *
{@linkplain Measures#CURRENCY_EXPOSURE Currency exposure}
 *
{@linkplain Measures#CURRENT_CASH Current cash}
 *
{@linkplain Measures#CURRENT_CASH Current cash}
 *
{@linkplain Measures#RESOLVED_TARGET Resolved trade}
 *

 *

 * The "natural" currency is determined from the cap/floor leg.
 */
public class IborCapFloorTradeCalculationFunction
    implements CalculationFunction<IborCapFloorTrade> {

  /**
   * The calculations by measure.
   */
  private static final ImmutableMap<Measure, SingleMeasureCalculation> CALCULATORS =
      ImmutableMap.<Measure, SingleMeasureCalculation>builder()
          .put(Measures.PRESENT_VALUE, IborCapFloorMeasureCalculations.DEFAULT::presentValue)
          .put(Measures.PV01_CALIBRATED_SUM, IborCapFloorMeasureCalculations.DEFAULT::pv01RatesCalibratedSum)
          .put(Measures.PV01_CALIBRATED_BUCKETED, IborCapFloorMeasureCalculations.DEFAULT::pv01RatesCalibratedBucketed)
          .put(Measures.PV01_MARKET_QUOTE_SUM, IborCapFloorMeasureCalculations.DEFAULT::pv01RatesMarketQuoteSum)
          .put(Measures.PV01_MARKET_QUOTE_BUCKETED, IborCapFloorMeasureCalculations.DEFAULT::pv01RatesMarketQuoteBucketed)
          .put(Measures.CURRENCY_EXPOSURE, IborCapFloorMeasureCalculations.DEFAULT::currencyExposure)
          .put(Measures.CURRENT_CASH, IborCapFloorMeasureCalculations.DEFAULT::currentCash)
          .put(Measures.RESOLVED_TARGET, (rt, smd, m) -> rt)
          .build();

  private static final ImmutableSet<Measure> MEASURES = CALCULATORS.keySet();

  /**
   * Creates an instance.
   */
  public IborCapFloorTradeCalculationFunction() {
  }

  //-------------------------------------------------------------------------
  @Override
  public Class<IborCapFloorTrade> targetType() {
    return IborCapFloorTrade.class;
  }

  @Override
  public Set<Measure> supportedMeasures() {
    return MEASURES;
  }

  @Override
  public Optional<String> identifier(IborCapFloorTrade target) {
    return target.getInfo().getId().map(id -> id.toString());
  }

  @Override
  public Currency naturalCurrency(IborCapFloorTrade trade, ReferenceData refData) {
    return trade.getProduct().getCapFloorLeg().getCurrency();
  }

  //-------------------------------------------------------------------------
  @Override
  public FunctionRequirements requirements(
      IborCapFloorTrade trade,
      Set<Measure> measures,
      CalculationParameters parameters,
      ReferenceData refData) {

    // extract data from product
    IborCapFloor product = trade.getProduct();
    Set<Currency> currencies = product.allPaymentCurrencies();
    Set<Index> indices = product.allIndices();

    // use lookup to build requirements
    RatesMarketDataLookup ratesLookup = parameters.getParameter(RatesMarketDataLookup.class);
    FunctionRequirements ratesReqs = ratesLookup.requirements(currencies, indices);
    IborCapFloorMarketDataLookup capFloorLookup = parameters.getParameter(IborCapFloorMarketDataLookup.class);
    FunctionRequirements capFloorReqs = capFloorLookup.requirements(product.getCapFloorLeg().getIndex());
    return ratesReqs.combinedWith(capFloorReqs);
  }

  //-------------------------------------------------------------------------
  @Override
  public Map<Measure, Result<?>> calculate(
      IborCapFloorTrade trade,
      Set<Measure> measures,
      CalculationParameters parameters,
      ScenarioMarketData scenarioMarketData,
      ReferenceData refData) {

    // expand the trade once for all measures and all scenarios
    ResolvedIborCapFloorTrade resolved = trade.resolve(refData);
    RatesMarketDataLookup ratesLookup = parameters.getParameter(RatesMarketDataLookup.class);
    RatesScenarioMarketData ratesMarketData = ratesLookup.marketDataView(scenarioMarketData);
    IborCapFloorMarketDataLookup capFloorLookup = parameters.getParameter(IborCapFloorMarketDataLookup.class);
    IborCapFloorScenarioMarketData capFloorMarketData = capFloorLookup.marketDataView(scenarioMarketData);

    // loop around measures, calculating all scenarios for one measure
    Map<Measure, Result<?>> results = new HashMap<>();
    for (Measure measure : measures) {
      results.put(measure, calculate(measure, resolved, ratesMarketData, capFloorMarketData));
    }
    return results;
  }

  // calculate one measure
  private Result<?> calculate(
      Measure measure,
      ResolvedIborCapFloorTrade trade,
      RatesScenarioMarketData ratesMarketData,
      IborCapFloorScenarioMarketData capFloorMarketData) {

    SingleMeasureCalculation calculator = CALCULATORS.get(measure);
    if (calculator == null) {
      return Result.failure(FailureReason.UNSUPPORTED, "Unsupported measure for IborCapFloorTrade: {}", measure);
    }
    return Result.of(() -> calculator.calculate(trade, ratesMarketData, capFloorMarketData));
  }

  //-------------------------------------------------------------------------
  @FunctionalInterface
  interface SingleMeasureCalculation {
    public abstract Object calculate(
        ResolvedIborCapFloorTrade trade,
        RatesScenarioMarketData ratesMarketData,
        IborCapFloorScenarioMarketData capFloorMarketData);
  }

}


text:
Spree::OrderMailer.class_eval do
  helper Spree::BaseHelper
end