text:
(async function() {
  TestRunner.addResult(`Tests that pseudo elements and their styles are handled properly.\n`);
  await TestRunner.loadLegacyModule('elements'); await TestRunner.loadTestModule('elements_test_runner');
  await TestRunner.showPanel('elements');
  await TestRunner.loadHTML(`

Text

    `);
  await TestRunner.evaluateInPagePromise(`
      function removeLastRule()
      {
          document.styleSheets[0].deleteRule(document.styleSheets[0].cssRules.length - 1);
      }

      function addAfterRule()
      {
          document.styleSheets[0].addRule("#inspected:after", "content: \\"AFTER\\"");
      }

      function addBeforeRule()
      {
          document.styleSheets[0].addRule("#inspected:before", "content: \\"BEFORE\\"");
      }

      function addMarkerRule()
      {
          document.styleSheets[0].addRule("#inspected", "display: list-item");
          document.styleSheets[0].addRule("#inspected::marker", "content: \\"MARKER\\"");
      }

      function modifyTextContent()
      {
          document.getElementById("inspected").textContent = "bar";
      }

      function clearTextContent()
      {
          document.getElementById("inspected").textContent = "";
      }

      function removeNode()
      {
          document.getElementById("inspected").remove();
      }
  `);

  var containerNode;
  var inspectedNode;

  TestRunner.runTestSuite([
    function dumpOriginalTree(next) {
      ElementsTestRunner.expandElementsTree(callback);
      function callback() {
        containerNode = ElementsTestRunner.expandedNodeWithId('container');
        inspectedNode = ElementsTestRunner.expandedNodeWithId('inspected');
        TestRunner.addResult('Original elements tree:');
        ElementsTestRunner.dumpElementsTree(containerNode);
        next();
      }
    },

    function dumpNormalNodeStyles(next) {
      selectNodeAndDumpStyles('inspected', '', next);
    },

    function dumpBeforeStyles(next) {
      selectNodeAndDumpStyles('inspected', 'before', next);
    },

    function dumpAfterStyles(next) {
      selectNodeAndDumpStyles('inspected', 'after', next);
    },

    function dumpMarkerStyles(next) {
      selectNodeAndDumpStyles('inspected', 'marker', next);
    },

    function removeAfter(next) {
      executeAndDumpTree('removeLastRule()', SDK.DOMModel.Events.NodeRemoved, next);
    },

    function removeBefore(next) {
      executeAndDumpTree('removeLastRule()', SDK.DOMModel.Events.NodeRemoved, next);
    },

    function removeMarker(next) {
      executeAndDumpTree('removeLastRule(); removeLastRule()', SDK.DOMModel.Events.NodeRemoved, next);
    },

    function addAfter(next) {
      executeAndDumpTree('addAfterRule()', SDK.DOMModel.Events.NodeInserted, expandAndDumpTree.bind(this, next));
    },

    function addBefore(next) {
      executeAndDumpTree('addBeforeRule()', SDK.DOMModel.Events.NodeInserted, next);
    },

    function addMarker(next) {
      executeAndDumpTree('addMarkerRule()', SDK.DOMModel.Events.NodeInserted, next);
    },

    function modifyTextContent(next) {
      executeAndDumpTree('modifyTextContent()', SDK.DOMModel.Events.NodeInserted, next);
    },

    function clearTextContent(next) {
      executeAndDumpTree('clearTextContent()', SDK.DOMModel.Events.NodeRemoved, next);
    },

    function removeNodeAndCheckPseudoElementsUnbound(next) {
      var inspectedBefore = inspectedNode.beforePseudoElement();
      var inspectedAfter = inspectedNode.afterPseudoElement();
      var inspectedMarker = inspectedNode.markerPseudoElement();

      executeAndDumpTree('removeNode()', SDK.DOMModel.Events.NodeRemoved, callback);
      function callback() {
        TestRunner.addResult(
            'inspected:before DOMNode in DOMAgent: ' + !!(TestRunner.domModel.nodeForId(inspectedBefore.id)));
        TestRunner.addResult(
            'inspected:after DOMNode in DOMAgent: ' + !!(TestRunner.domModel.nodeForId(inspectedAfter.id)));
        TestRunner.addResult(
            'inspected::marker DOMNode in DOMAgent: ' + !!(TestRunner.domModel.nodeForId(inspectedMarker.id)));
        next();
      }
    }
  ]);

  function executeAndDumpTree(pageFunction, eventName, next) {
    TestRunner.domModel.addEventListener(eventName, domCallback, this);
    TestRunner.evaluateInPage(pageFunction);

    function domCallback() {
      TestRunner.domModel.removeEventListener(eventName, domCallback, this);
      ElementsTestRunner.firstElementsTreeOutline().addEventListener(
          Elements.ElementsTreeOutline.Events.ElementsTreeUpdated, treeCallback, this);
    }

    function treeCallback() {
      ElementsTestRunner.firstElementsTreeOutline().removeEventListener(
          Elements.ElementsTreeOutline.Events.ElementsTreeUpdated, treeCallback, this);
      ElementsTestRunner.dumpElementsTree(containerNode);
      next();
    }
  }

  function expandAndDumpTree(next) {
    TestRunner.addResult('== Expanding: ==');
    ElementsTestRunner.expandElementsTree(callback);
    function callback() {
      ElementsTestRunner.dumpElementsTree(containerNode);
      next();
    }
  }

  function selectNodeAndDumpStyles(id, pseudoTypeName, callback) {
    if (pseudoTypeName)
      ElementsTestRunner.selectPseudoElementAndWaitForStyles('inspected', pseudoTypeName, stylesCallback);
    else
      ElementsTestRunner.selectNodeAndWaitForStyles('inspected', stylesCallback);

    async function stylesCallback() {
      await ElementsTestRunner.dumpSelectedElementStyles(true, false, false, true);
      callback();
    }
  }
})();


text:
<?php

namespace SensioLabs\Insight\Sdk\Model;

use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\Exclude;
use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\XmlList;

class Project
{
    /**
     * @see https://github.com/sensiolabs/connect/blob/master/src/SensioLabs/Connect/Api/Entity/Project.php
     */
    const TYPE_PHP_WEBSITE = 0;
    const TYPE_PHP_LIBRARY = 1;
    const TYPE_SYMFONY2_BUNDLE = 2;
    const TYPE_SYMFONY1_PLUGIN = 4;
    const TYPE_OTHER = 6;
    const TYPE_DRUPAL_MODULE = 7;
    const TYPE_LARAVAL_WEB_PROJECT = 8;
    const TYPE_SILEX_WEB_PROJECT = 9;
    const TYPE_SYMFONY2_WEB_PROJECT = 10;
    const TYPE_SYMFONY1_WEB_PROJECT = 11;

    /**
     * @Exclude()
     */
    public static $types = array(
        self::TYPE_SYMFONY2_WEB_PROJECT => 'Symfony2 Web Project',
        self::TYPE_SYMFONY1_WEB_PROJECT => 'symfony1 Web Project',
        self::TYPE_SILEX_WEB_PROJECT => 'Silex Web Project',
        self::TYPE_LARAVAL_WEB_PROJECT => 'Laravel Web Project',
        self::TYPE_SYMFONY2_BUNDLE => 'Symfony2 Bundle',
        self::TYPE_SYMFONY1_PLUGIN => 'symfony1 Plugin',
        self::TYPE_DRUPAL_MODULE => 'Drupal Module',
        self::TYPE_PHP_WEBSITE => 'PHP Web Project',
        self::TYPE_PHP_LIBRARY => 'PHP Library',
        self::TYPE_OTHER => 'Other',
    );

    /**
     * @Type("array<SensioLabs\Insight\Sdk\Model\Link>")
     * @XmlList(inline = true, entry = "link")
     */
    private $links = array();

    /**
     * @Type("string")
     * @SerializedName("id")
     */
    private $uuid;

    /** @Type("string") */
    private $name;

    /** @Type("string") */
    private $configuration;

    /** @Type("string") */
    private $description;

    /** @Type("integer") */
    private $type;

    /**
     * @Type("string")
     * @SerializedName("repository-url")
     */
    private $repositoryUrl;

    /** @Type("boolean") */
    private $private;

    /**
     * @Type("boolean")
     * @SerializedName("report-available")
     */
    private $reportAvailable;

    /**
     * @Type("SensioLabs\Insight\Sdk\Model\Analysis")
     * @SerializedName("last-analysis")
     */
    private $lastAnalysis;

    public function toArray()
    {
        return array(
            'name'          => $this->name,
            'public'        => !$this->private,
            'description'   => $this->description,
            'repositoryUrl' => $this->repositoryUrl,
            'type'          => $this->type,
            'configuration' => $this->configuration,
        );
    }

    /**
     * @return Link[]
     */
    public function getLinks()
    {
        return $this->links;
    }

    /**
     * @return string
     */
    public function getUuid()
    {
        return $this->uuid;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return string
     */
    public function getConfiguration()
    {
        return $this->configuration;
    }

    public function setConfiguration($configuration)
    {
        $this->configuration = $configuration;

        return $this;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * @return int
     */
    public function getType()
    {
        return $this->type;
    }

    public function setType($type)
    {
        if (!array_key_exists($type, static::$types)) {
            throw new \InvalidArgumentException(sprintf('"%s" is not a valid type. You must pick one among "%"', $type, implode('", "', array_keys(static::$types))));
        }

        $this->type = $type;

        return $this;
    }

    /**
     * @return string
     */
    public function getRepositoryUrl()
    {
        return $this->repositoryUrl;
    }

    public function setRepositoryUrl($repositoryUrl)
    {
        $this->repositoryUrl = $repositoryUrl;

        return $this;
    }

    /**
     * @return bool
     */
    public function isPublic()
    {
        return !$this->private;
    }

    public function setPublic($isPublic = false)
    {
        $this->private = !$isPublic;

        return $this;
    }

    /**
     * @return bool
     */
    public function isPrivate()
    {
        return $this->private;
    }

    public function setPrivate($isPrivate = true)
    {
        $this->private = $isPrivate;

        return $this;
    }

    /**
     * @return bool
     */
    public function isReportAvailable()
    {
        return $this->reportAvailable;
    }

    /**
     * @return Analysis|null
     */
    public function getLastAnalysis()
    {
        return $this->lastAnalysis;
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict'

const querystring = require('querystring')
const async = require('async')

const utils = require('./lib/utils')
const Cookie = require('./lib/cookie')

// errors
const BadRequest = require('./errors/bad-request')
const Unauthorized = require('./errors/unauthorized')

function Server(dhke, opts) {
  if (!(this instanceof Server)) {
    return new Server(dhke, opts)
  }

  this.dhke = dhke
  this.cookie = Cookie(this.dhke.crypter, opts.domain, opts.cookie)

  this.strategies = {}
  this.apps = {}

  this.serializer = () => {
    throw new Error('serializeUser not defined')
  }
  this.deserializer = () => {
    throw new Error('deserializeUser not defined')
  }
  this.authorizator = (user, app, done) => {
    done(null, user)
  }
}

Server.prototype.authenticate = function() {
  return (req, res, next) => {
    this.cookie.initializeRequest(req, res)

    const query = req.query || {}
    let app_name = null

    if (!query.app) {
      return next(new BadRequest('Missing app param'))
    }

    if (!(app_name = this.decodeApp(query.app))) {
      return next(new BadRequest('Missing app param'))
    }

    this
    .getLoggedUser()
    .then((user) => {
      return utils.promisify((resolve, reject) => {
        this.authorizator.call(this, user, app_name, (err, user) => {
          if (err) {
            return reject(err)
          }

          if (!user) {
            return reject(new Unauthorized())
          }

          resolve(user)
        })
      })
    })
    .then((user) => {
      this.send(res, {
        app: app_name,
        user: user,
        params: query
      })
    })
    .catch((err) => {
      next(err)
    })
  }
}

Server.prototype.logIn = function(strategy, opts) {
  opts = opts || {}

  if (!(strategy = this.strategies[strategy])) {
    throw new Error('Strategy ' + strategy + ' does not exist')
  }

  return (req, res, next) => {
    this.cookie.initializeRequest(req, res)

    const body = req.body || {}
    let app_name = null

    if (!(app_name = this.decodeApp(body.app))) {
      return next(new BadRequest('Missing app param'))
    }

    utils.promisify((resolve, reject) => {
      strategy.call(this, body[opts.usernameField || 'username'], body[opts.passwordField || 'password'], (err, user) => {
        if (err) {
          return reject(err)
        }

        if (!user) {
          return reject(new Unauthorized())
        }

        resolve(user)
      })
    })
    .then((user) => {
      return utils.promisify((resolve, reject) => {
        this.serializer.call(this, user, (err, serialized) => {
          if (err) {
            return reject(err)
          }

          if (!serialized) {
            return reject(new Unauthorized())
          }

          resolve([user, serialized])
        })
      })
    })
    .then(([user, serialized]) => {
      return utils.promisify((resolve, reject) => {
        this.authorizator.call(this, user, app_name, (err, user) => {
          if (err) {
            return reject(err)
          }

          if (!user) {
            return reject(new Unauthorized())
          }

          this.cookie.set(serialized)

          resolve(user)
        })
      })
    })
    .then((user) => {
      this.send(res, {
        app: app_name,
        user: user,
        params: body
      })
    })
    .catch((err) => {
      next(err)
    })
  }
}

Server.prototype.logOut = function(redirect) {
  return (req, res, next) => {
    this.cookie.initializeRequest(req, res)

    this.cookie.delete()

    if (redirect) {
      return res.redirect(redirect)
    }

    next()
  }
}

Server.prototype.addApp = function(app, info) {
  if (typeof app != 'object') {
    let tmp = {}
    tmp[app] = info
    app = tmp
  }

  for (var app_name in app) {
    let info = app[app_name]

    if (typeof info != 'object' || !info.redirect) {
      throw new Error('Configuration missing for app: ' + app_name)
    }

    this.apps[app_name] = info
  }

  return this
}

Server.prototype.strategy = function(strategy, cb) {
  this.strategies[strategy] = cb

  return this
}

Server.prototype.authorizeUser = function(cb) {
  this.authorizator = cb

  return this
}

Server.prototype.serializeUser = function(cb) {
  this.serializer = cb

  return this
}

Server.prototype.deserializeUser = function(cb) {
  this.deserializer = cb

  return this
}

Server.prototype.getLoggedUser = function() {
  return new Promise(
    (resolve, reject) => {
      const cookie_value = this.cookie.get()

      if (!cookie_value) {
        return reject(null)
      }

      this.deserializer.call(this, cookie_value, (err, user) => {
        if (err) {
          return reject(err)
        }

        if (!user) {
          return reject(null)
        }

        resolve(user)
      })
    }
  )
}

Server.prototype.send = function(res, opts) {
  const info = this.apps[opts.app]

  if (!info) {
    return res.status(500).end()
  }

  const query = {
    verify: opts.params.verify || '',
    user: this.dhke.encrypt(opts.app, JSON.stringify(opts.user))
  }

  res.redirect(info.redirect + '?' + querystring.stringify(query))
}

Server.prototype.decodeApp = function(coded_app) {
  const app = utils.decryptApp(coded_app)

  return this.apps.hasOwnProperty(app) ? app : null
}

module.exports = Server


text:
// Underscore.js
// (c) 2009 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the terms of the MIT license.
// Portions of Underscore are inspired by or borrowed from Prototype.js,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore/

(function() {

  /*------------------------- Baseline setup ---------------------------------*/

  // Establish the root object, "window" in the browser, or "global" on the server.
  var root = this;

  // Save the previous value of the "U" variable.
  var previousU = root.U;

  // Create a safe reference to the Underscore object for the functions below.
  var U = root.U = {};

  // Export the Underscore object for CommonJS.
  if (typeof exports !== 'undefined') U = exports;

  // Current version.
  U.VERSION = '0.3';

  /*------------------------ Collection Functions: ---------------------------*/

  // The cornerstone, an each implementation.
  // Handles objects implementing forEach, each, arrays, and raw objects.
  U.each = function(obj, iterator, context) {
    var index = 0;
    try {
      if (obj.forEach) {
        obj.forEach(iterator, context);
      } else if (obj.length) {
        for (var i=0, l = obj.length; i<l; i++) iterator.call(context, obj[i], i, obj);
      } else if (obj.each) {
        obj.each(function(value) { iterator.call(context, value, index++, obj); });
      } else {
        for (var key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) {
          iterator.call(context, obj[key], key, obj);
        }
      }
    } catch(e) {
      if (e != 'UUbreakUU') throw e;
    }
    return obj;
  };

  // Return the results of applying the iterator to each element. Use JavaScript
  // 1.6's version of map, if possible.
  U.map = function(obj, iterator, context) {
    if (obj && obj.map) return obj.map(iterator, context);
    var results = [];
    U.each(obj, function(value, index, list) {
      results.push(iterator.call(context, value, index, list));
    });
    return results;
  };

  // Reduce builds up a single result from a list of values. Also known as
  // inject, or foldl. Uses JavaScript 1.8's version of reduce, if possible.
  U.reduce = function(obj, memo, iterator, context) {
    if (obj && obj.reduce) return obj.reduce(U.bind(iterator, context), memo);
    U.each(obj, function(value, index, list) {
      memo = iterator.call(context, memo, value, index, list);
    });
    return memo;
  };

  // The right-associative version of reduce, also known as foldr. Uses
  // JavaScript 1.8's version of reduceRight, if available.
  U.reduceRight = function(obj, memo, iterator, context) {
    if (obj && obj.reduceRight) return obj.reduceRight(U.bind(iterator, context), memo);
    var reversed = U.clone(U.toArray(obj)).reverse();
    U.each(reversed, function(value, index) {
      memo = iterator.call(context, memo, value, index, obj);
    });
    return memo;
  };

  // Return the first value which passes a truth test.
  U.detect = function(obj, iterator, context) {
    var result;
    U.each(obj, function(value, index, list) {
      if (iterator.call(context, value, index, list)) {
        result = value;
        throw 'UUbreakUU';
      }
    });
    return result;
  };

  // Return all the elements that pass a truth test. Use JavaScript 1.6's
  // filter(), if it exists.
  U.select = function(obj, iterator, context) {
    if (obj.filter) return obj.filter(iterator, context);
    var results = [];
    U.each(obj, function(value, index, list) {
      iterator.call(context, value, index, list) && results.push(value);
    });
    return results;
  };

  // Return all the elements for which a truth test fails.
  U.reject = function(obj, iterator, context) {
    var results = [];
    U.each(obj, function(value, index, list) {
      !iterator.call(context, value, index, list) && results.push(value);
    });
    return results;
  };

  // Determine whether all of the elements match a truth test. Delegate to
  // JavaScript 1.6's every(), if it is present.
  U.all = function(obj, iterator, context) {
    iterator = iterator || U.identity;
    if (obj.every) return obj.every(iterator, context);
    var result = true;
    U.each(obj, function(value, index, list) {
      if (!(result = result && iterator.call(context, value, index, list))) throw 'UUbreakUU';
    });
    return result;
  };

  // Determine if at least one element in the object matches a truth test. Use
  // JavaScript 1.6's some(), if it exists.
  U.any = function(obj, iterator, context) {
    iterator = iterator || U.identity;
    if (obj.some) return obj.some(iterator, context);
    var result = false;
    U.each(obj, function(value, index, list) {
      if (result = iterator.call(context, value, index, list)) throw 'UUbreakUU';
    });
    return result;
  };

  // Determine if a given value is included in the array or object,
  // based on '==='.
  U.include = function(obj, target) {
    if (U.isArray(obj)) return U.indexOf(obj, target) != -1;
    var found = false;
    U.each(obj, function(value) {
      if (found = value === target) {
        throw 'UUbreakUU';
      }
    });
    return found;
  };

  // Invoke a method with arguments on every item in a collection.
  U.invoke = function(obj, method) {
    var args = U.toArray(arguments).slice(2);
    return U.map(obj, function(value) {
      return (method ? value[method] : value).apply(value, args);
    });
  };

  // Convenience version of a common use case of map: fetching a property.
  U.pluck = function(obj, key) {
    return U.map(obj, function(value){ return value[key]; });
  };

  // Return the maximum item or (item-based computation).
  U.max = function(obj, iterator, context) {
    if (!iterator && U.isArray(obj)) return Math.max.apply(Math, obj);
    var result = {computed : -Infinity};
    U.each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed >= result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Return the minimum element (or element-based computation).
  U.min = function(obj, iterator, context) {
    if (!iterator && U.isArray(obj)) return Math.min.apply(Math, obj);
    var result = {computed : Infinity};
    U.each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed < result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Sort the object's values by a criteria produced by an iterator.
  U.sortBy = function(obj, iterator, context) {
    return U.pluck(U.map(obj, function(value, index, list) {
      return {
        value : value,
        criteria : iterator.call(context, value, index, list)
      };
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a  b ? 1 : 0;
    }), 'value');
  };

  // Use a comparator function to figure out at what index an object should
  // be inserted so as to maintain order. Uses binary search.
  U.sortedIndex = function(array, obj, iterator) {
    iterator = iterator || U.identity;
    var low = 0, high = array.length;
    while (low < high) {
      var mid = (low + high) >> 1;
      iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
    }
    return low;
  };

  // Convert anything iterable into a real, live array.
  U.toArray = function(iterable) {
    if (!iterable) return [];
    if (U.isArray(iterable)) return iterable;
    return U.map(iterable, function(val){ return val; });
  };

  // Return the number of elements in an object.
  U.size = function(obj) {
    return U.toArray(obj).length;
  };

  /*-------------------------- Array Functions: ------------------------------*/

  // Get the first element of an array.
  U.first = function(array) {
    return array[0];
  };

  // Get the last element of an array.
  U.last = function(array) {
    return array[array.length - 1];
  };

  // Trim out all falsy values from an array.
  U.compact = function(array) {
    return U.select(array, function(value){ return !!value; });
  };

  // Return a completely flattened version of an array.
  U.flatten = function(array) {
    return U.reduce(array, [], function(memo, value) {
      if (U.isArray(value)) return memo.concat(U.flatten(value));
      memo.push(value);
      return memo;
    });
  };

  // Return a version of the array that does not contain the specified value(s).
  U.without = function(array) {
    var values = array.slice.call(arguments, 0);
    return U.select(array, function(value){ return !U.include(values, value); });
  };

  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  U.uniq = function(array, isSorted) {
    return U.reduce(array, [], function(memo, el, i) {
      if (0 == i || (isSorted ? U.last(memo) != el : !U.include(memo, el))) memo.push(el);
      return memo;
    });
  };

  // Produce an array that contains every item shared between all the
  // passed-in arrays.
  U.intersect = function(array) {
    var rest = U.toArray(arguments).slice(1);
    return U.select(U.uniq(array), function(item) {
      return U.all(rest, function(other) {
        return U.indexOf(other, item) >= 0;
      });
    });
  };

  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  U.zip = function() {
    var args = U.toArray(arguments);
    var length = U.max(U.pluck(args, 'length'));
    var results = new Array(length);
    for (var i=0; i<length; i++) results[i] = U.pluck(args, String(i));
    return results;
  };

  // If the browser doesn't supply us with indexOf (I'm looking at you, MSIE),
  // we need this function. Return the position of the first occurence of an
  // item in an array, or -1 if the item is not included in the array.
  U.indexOf = function(array, item) {
    if (array.indexOf) return array.indexOf(item);
    for (i=0, l=array.length; i<l; i++) if (array[i] === item) return i;
    return -1;
  };

  // Provide JavaScript 1.6's lastIndexOf, delegating to the native function,
  // if possible.
  U.lastIndexOf = function(array, item) {
    if (array.lastIndexOf) return array.lastIndexOf(item);
    var i = array.length;
    while (i--) if (array[i] === item) return i;
    return -1;
  };

  /* ----------------------- Function Functions: -----------------------------*/

  // Create a function bound to a given object (assigning 'this', and arguments,
  // optionally). Binding with arguments is also known as 'curry'.
  U.bind = function(func, context) {
    if (!context) return func;
    var args = U.toArray(arguments).slice(2);
    return function() {
      var a = args.concat(U.toArray(arguments));
      return func.apply(context, a);
    };
  };

  // Bind all of an object's methods to that object. Useful for ensuring that
  // all callbacks defined on an object belong to it.
  U.bindAll = function() {
    var args = U.toArray(arguments);
    var context = args.pop();
    U.each(args, function(methodName) {
      context[methodName] = U.bind(context[methodName], context);
    });
  };

  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  U.delay = function(func, wait) {
    var args = U.toArray(arguments).slice(2);
    return setTimeout(function(){ return func.apply(func, args); }, wait);
  };

  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  U.defer = function(func) {
    return U.delay.apply(U, [func, 1].concat(U.toArray(arguments).slice(1)));
  };

  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  U.wrap = function(func, wrapper) {
    return function() {
      var args = [func].concat(U.toArray(arguments));
      return wrapper.apply(wrapper, args);
    };
  };

  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  U.compose = function() {
    var funcs = U.toArray(arguments);
    return function() {
      for (var i=funcs.length-1; i >= 0; i--) {
        arguments = [funcs[i].apply(this, arguments)];
      }
      return arguments[0];
    };
  };

  /* ------------------------- Object Functions: ---------------------------- */

  // Retrieve the names of an object's properties.
  U.keys = function(obj) {
    return U.map(obj, function(value, key){ return key; });
  };

  // Retrieve the values of an object's properties.
  U.values = function(obj) {
    return U.map(obj, U.identity);
  };

  // Extend a given object with all of the properties in a source object.
  U.extend = function(destination, source) {
    for (var property in source) destination[property] = source[property];
    return destination;
  };

  // Create a (shallow-cloned) duplicate of an object.
  U.clone = function(obj) {
    if (U.isArray(obj)) return obj.slice(0);
    return U.extend({}, obj);
  };

  // Perform a deep comparison to check if two objects are equal.
  U.isEqual = function(a, b) {
    // Check object identity.
    if (a === b) return true;
    // Different types?
    var atype = typeof(a), btype = typeof(b);
    if (atype != btype) return false;
    // Basic equality test (watch out for coercions).
    if (a == b) return true;
    // One of them implements an isEqual()?
    if (a.isEqual) return a.isEqual(b);
    // If a is not an object by this point, we can't handle it.
    if (atype !== 'object') return false;
    // Nothing else worked, deep compare the contents.
    var aKeys = U.keys(a), bKeys = U.keys(b);
    // Different object sizes?
    if (aKeys.length != bKeys.length) return false;
    // Recursive comparison of contents.
    for (var key in a) if (!U.isEqual(a[key], b[key])) return false;
    return true;
  };

  // Is a given value a DOM element?
  U.isElement = function(obj) {
    return !!(obj && obj.nodeType == 1);
  };

  // Is a given value a real Array?
  U.isArray = function(obj) {
    return Object.prototype.toString.call(obj) == '[object Array]';
  };

  // Is a given value a Function?
  U.isFunction = function(obj) {
    return Object.prototype.toString.call(obj) == '[object Function]';
  };

  // Is a given variable undefined?
  U.isUndefined = function(obj) {
    return typeof obj == 'undefined';
  };

  /* -------------------------- Utility Functions: -------------------------- */

  // Run Underscore.js in noConflict mode, returning the 'U' variable to its
  // previous owner. Returns a reference to the Underscore object.
  U.noConflict = function() {
    root.U = previousUnderscore;
    return this;
  };

  // Keep the identity function around for default iterators.
  U.identity = function(value) {
    return value;
  };

  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  U.uniqueId = function(prefix) {
    var id = this.UidCounter = (this.UidCounter || 0) + 1;
    return prefix ? prefix + id : id;
  };

  // JavaScript templating a-la ERB, pilfered from John Resig's
  // "Secrets of the JavaScript Ninja", page 83.
  U.template = function(str, data) {
    var fn = new Function('obj',
      'var p=[],print=function(){p.push.apply(p,arguments);};' +
      'with(obj){p.push(\'' +
      str
        .replace(/[\r\t\n]/g, " ")
        .split("<%").join("\t")
        .replace(/((^|%>)[^\t]*)'/g, "$1\r")
        .replace(/\t=(.*?)%>/g, "',$1,'")
        .split("\t").join("');")
        .split("%>").join("p.push('")
        .split("\r").join("\\'")
    + "');}return p.join('');");
    return data ? fn(data) : fn;
  };
  //Yiannis Additions
  U.boxString=function (str) {
  var a = [];
  var i = 0;
  var s = '';
  var n = str.length;
  function wrap() {
    var div = '<' + 'div' + ' class="cell" >';
    var span = '<' + 'span' + '>';
    var divend = '<' + '/div' + '>';
    var spanend = '<' + '/span' + '>';
    var z = div + span + str[i] + spanend + divend;
    return z;
  }

  while (i < n) {
    a[i] = wrap(i);
    s += wrap(i);
    i++;
  }
  s = s + '

';
  return s;
}
// pad a string left or right
// to do options object
U.padString =function (pos, str, orientation) {
  var t1 = '';
  var z = '';
  for (var i = 0; i < pos; i++) {
    t1 = t1 + ' '; // empty string
  }
  z = t1 + str;
  return z;
}

U.showSymbol= function (symbol, position, length) {
  var t = function () {
    var t1 = '';
    for (var i = 0; i < length; i++) {
      t1 = t1 + ' '; // empty string
    }
    return t1;
  }

  var t3 = symbolAtPosition(symbol, position, t());
  var t4 = U.boxString(t3);

  $that.siblings('.msg').append(t4).show('slow');
}

// Character Routines
// insert string at position
// todo checks
U.insertChar= function (sub, position, str) {
  var s = str.slice(0, position);
  var s1 = str.slice(position, str.length);
  return (s + sub + s1);
}

// delete string at position
// using slice we cut string in half
// todo checks
U.deleteChar=function(position, str) {
  //if (position == str.length + 1) return -1;
  var s = str.slice(0, position);
  var s1 = str.slice(position + 1, str.length);
  return (s + s1);
}

U.replaceChar=function(chr,position, str){
  var s=U.deleteChar(position,str);
  return s=U.insertChar(chr,position, s);

}
// delete string at position
// using slice we cut string in half
// TODO checks
U.swapChar=function(position, str) {
  var c0=str.charAt(position);
  var c1=str.charAt(position+1);
      var c2 = U.deleteChar(position,str);
      str = U.deleteChar(position,c2);
      str = U.insertChar(c1,position,str);
      str = U.insertChar(c0,position+1,str);

  return str;
}

/*
 *   Tic-tac-toe game related
 */

// utility to draw a table using
// divs
U.divTable = function (rows, columns) {
  var s = '';
  var id=0;
  // draw one div
  function wrap(n, n1, counter) {
    var div = '<' + 'div' + ' class="cell" rel="'+counter+'" id="cell-'+counter+'" >';
    var divend = '<' + '/div' + '>';
    var span = '<' + 'span' + '>';
    var spanend = '<' + '/span' + '>';
    var z = div +  divend;
    return z;
  }

  // loop through rows and columns
  for (var i = 0; i < rows; i++) {
    for (var j = 0; j < columns; j++) {

      s = s + wrap(i, j, id);
       id++;
    }
    s = s + '<' + 'div style="clear:both"' + '> ';
  }
  return s;
}

$.fn.showProperties=function(obj){
  var s='
';
  for (var prop in obj){
      if (obj.hasOwnProperty(prop)){
     s+= ''+prop+ ' : ' + obj[prop]+'\n';
     }
  }
  s=s+'
';
  $(this).html(s);
  return s;
}

U.properties = function (obj){
  var s ='';
  for (var prop in obj){
      if (obj.hasOwnProperty(prop)){
     s+= ''+prop+ ' : ' + obj[prop]+'\n';
     }
  }
  logPRE(s);
}

U.scriptsLoaded=function () {
        var scripts = document.getElementsByTagName('script');
        var count = 0;
        for (var i = 0, n = scripts.length; i < n; i++) {
            if (scripts[i].src) {
                count++;
            }
        }
        log('number of scripts loaded', count);
    };

U.string={};

//alias

$.fn.properties=$.fn.showProperties;
  /*------------------------------- Aliases ----------------------------------*/

  U.forEach  = U.each;
  U.foldl    = U.inject       = U.reduce;
  U.foldr    = U.reduceRight;
  U.filter   = U.select;
  U.every    = U.all;
  U.some     = U.any;
  U.unique   = U.uniq;
  U.get      = U.pluck;
  U.properties = U.properties;

})();

var $D = function circle(radius, steps, centerX, centerY, options) {

  var defaults = {
    fillStyle: '#dd0000',
                steps:40,
                radius:10,
                X0:30,
                Y0:30};

  var settings =$.extend(options,defaults);
  settings.fillStyle = '#dd0000 ';
  log(settings.fillStyle);
  var xValues = [centerX];
  var yValues = [centerY];

  var ctx = $("#canvas")[0].getContext("2d");

  ctx.fillStyle = settings.fillStyle;

  ctx.beginPath();
  for (var i = 0; i <= steps; i++) {
    var radian = (2 * Math.PI) * (i / steps);
    xValues[i + 1] = centerX + radius * Math.cos(radian);
    yValues[i + 1] = centerY + radius * Math.sin(radian);
    if (0 == i) {
      ctx.moveTo(xValues[i + 1], yValues[i + 1]);
    } else {
      ctx.lineTo(xValues[i + 1], yValues[i + 1]);
    }
    log(i, xValues[i + 1].toFixed(2), yValues[i + 1].toFixed(2));
  }
  ctx.fill();
}


text:
<?php

namespace Siesta\NamingStrategy;

class ToClassCamelCaseStrategy implements NamingStrategy
{
    /**
     * @param string $value
     *
     * @return string
     */
    public function transform(string $value): string
    {
        $camelCase = preg_replace_callback('/_([a-z])/', function ($c) {
            return strtoupper($c[1]);
        }, $value);
        return ucfirst($camelCase);
    }

}


text:
  Contamine-Sarzin est
       un village
       géographiquement positionné dans le département de Haute-Savoie en Rhône-Alpes. Elle comptait 512 habitants en 2008.

Le parc d'habitations, à Contamine-Sarzin, était réparti en 2011 en 26 appartements et 216 maisons soit
 un marché relativement équilibré.

À proximité de Contamine-Sarzin sont localisées les villes de
Mésigny localisée à 4 km, 692 habitants,
Chilly localisée à 4 km, 1 082 habitants,
Frangy localisée à 4 km, 1 934 habitants,
Sallenôves à 2 km, 559 habitants,
Musièges à 2 km, 303 habitants,
Chavannaz à 3 km, 173 habitants,
 entre autres. De plus, Contamine-Sarzin est située à seulement 18 km de Annecy.

La commune propose quelques  équipements, elle propose entre autres une boucle de randonnée.

Si vous pensez emmenager à Contamine-Sarzin, vous pourrez aisément trouver une maison à acheter.

À Contamine-Sarzin, la valeur moyenne à la vente d'un appartement s'évalue à 2 749 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 2 393 € du m². À la location la valeur moyenne se situe à 13,89 € du m² mensuel.


text:
package org.ovirt.engine.core.common.job;

import java.util.HashMap;
import java.util.Map;

import org.ovirt.engine.core.common.asynctasks.AsyncTaskType;

/**
 * The {@code StepEnum} stores the name of steps which should be resolved as a descriptive message.
 */
public enum StepEnum {
    VALIDATING,
    EXECUTING,
    FINALIZING,
    INSTALLING_HOST,
    TEST_POWER_MANAGEMENT,
    ADD_VM_TO_POOL,
    MIGRATE_VM,
    CREATING_SNAPSHOTS,
    RUN_STATELESS_VM,
    TAKING_VM_FROM_POOL,

    // Gluster
    SETTING_GLUSTER_OPTION,
    REBALANCING_VOLUME,
    REMOVING_BRICKS,

    /**
     * Maps VDSM tasks type to {@code StepEnum} so it can be resolvable as readable description
     */
    COPY_IMAGE(AsyncTaskType.copyImage),
    MOVE_IMAGE(AsyncTaskType.moveImage),
    CREATE_VOLUME(AsyncTaskType.createVolume),
    DELETE_VOLUME(AsyncTaskType.deleteVolume),
    DELETE_IMAGE(AsyncTaskType.deleteImage),
    MERGE_SNAPSHOTS(AsyncTaskType.mergeSnapshots),
    CLONE_IMAGE_STRUCTURE(AsyncTaskType.cloneImageStructure),
    SYNC_IMAGE_DATA(AsyncTaskType.syncImageData),
    DOWNLOAD_IMAGE(AsyncTaskType.downloadImage),
    UNKNOWN(AsyncTaskType.unknown);

    /**
     * Holds the map between the VDSM task to the Step name which represents it.
     */
    private static final Map<AsyncTaskType, StepEnum> asyncTaskToStepEnumMap = new HashMap<AsyncTaskType, StepEnum>();

    /**
     * Store the correlated VDSM task type with the step name or {@code null} if none.
     */
    private AsyncTaskType asyncTaskType;

    static {
        for (StepEnum s : values()) {
            if (s.asyncTaskType != null) {
                asyncTaskToStepEnumMap.put(s.asyncTaskType, s);
            }
        }
    }

    private StepEnum() {
    }

    private StepEnum(AsyncTaskType asyncTaskType) {
        this.asyncTaskType = asyncTaskType;
    }

    public static StepEnum getStepNameByTaskType(AsyncTaskType asyncTaskType) {
        return asyncTaskToStepEnumMap.get(asyncTaskType);
    }

}


text:
<?xml version="1.0"?>
<material>
	<technique name="Techniques/DiffNormalSpec.xml" />
	<texture unit="diffuse" name="Textures/woman1_Shoes_diffuse.png" />
	<texture unit="normal" name="Textures/woman1_Shoes_normal.png" />
	<texture unit="specular" name="Textures/woman1_Shoes_specular.png" />
	<parameter name="MatDiffColor" value="1 1 1 1" />
	<parameter name="MatSpecColor" value="1 1 1 20" />
	<parameter name="MatEmissiveColor" value="0 0 0 1" />
</material>


text:
package tasty.mushrooms.commons.util;

import tasty.mushrooms.commons.exception.TeemoInstantiationException;

/**
 * 实例化工具类
 *
 * @since 1.0.0
 */
public abstract class InstantiateUtil {

	/**
	 * 根据类型实例化对象
	 *
	 * @param clazz 要实例化的类型
	 * @return 对象实例
	 * @throws TeemoInstantiationException 实例化失败(如无默认构造方法,实例化类型为抽象类或接口等)时抛出此异常
	 */
	public static <T> T instantiate(Class<T> clazz) throws TeemoInstantiationException {
		Assert.notNull(clazz, "Class must not be null");
		if (clazz.isInterface()) {
			throw new TeemoInstantiationException("Specified class is an interface");
		}
		try {
			return clazz.newInstance();
		} catch (InstantiationException ex) {
			throw new TeemoInstantiationException("Is it an abstract class?", ex);
		} catch (IllegalAccessException ex) {
			throw new TeemoInstantiationException("Is the constructor accessible?", ex);
		}
	}

	/**
	 * 根据类型实例化对象
	 *
	 * @param clazz 要实例化的类型
	 * @param assignableTo 检查类型,用来检查要实例化的类型是否与从此类型相同或为此类型的子类, 检查失败抛出
	 *            IllegalArgumentException 异常
	 * @return 对象实例
	 * @throws TeemoInstantiationException 实例化失败(如无默认构造方法,实例化类型为抽象类或接口等)时抛出此异常
	 */
	@SuppressWarnings("unchecked")
	public static <T> T instantiate(Class<?> clazz, Class<T> assignableTo) throws TeemoInstantiationException {
		Assert.isAssignable(assignableTo, clazz, null);
		return (T) instantiate(clazz);
	}
}


text:
class TestViewModel extends Fayde.MVVM.ViewModelBase {
    private _Now: DateTime = DateTime.Now;

    get Now(): DateTime {
        return this._Now;
    }
    set Now(value: DateTime) {
        this._Now = value;
        this.OnPropertyChanged("Now");
    }
}
export = TestViewModel;


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<APIProxy revision="1" name="OBBR-ConsentManagementWithKVM">
    <Basepaths>/consent</Basepaths>
    <ConfigurationVersion majorVersion="4" minorVersion="0"/>
    <CreatedAt>1647835276335</CreatedAt>
    <CreatedBy>deboraelkin@google.com</CreatedBy>
    <Description>Provides basic consent management functionality (Get, Create, Update, Revoke) using KVMs. The key to a consent is always a consent_id (So no functionality to retrieve all consents associated with a given end user or client). Displays consent screen to end user and manages response</Description>
    <DisplayName>OBBR-ConsentMgmtWithKVM</DisplayName>
    <LastModifiedAt>1647836611098</LastModifiedAt>
    <LastModifiedBy>deboraelkin@google.com</LastModifiedBy>
    <ManifestVersion>SHA-512:7d62e60a648450150db00aa5992f66bda22a651ef497293363092b7fa8b5a7b977d52aa372ea4d91fc30ce5a639615a41651b3e5c60acf5456796e086ba614d9:ap-southeast-2</ManifestVersion>
    <Policies>
        <Policy>AM-AssignConsentId</Policy>
        <Policy>AM-InsertQueryParamsForRedirect</Policy>
        <Policy>AM-RedirectToOIDCConsentCallback</Policy>
        <Policy>AM-SetConsentCacheKeyAndValue</Policy>
        <Policy>AM-SetConsentStatus</Policy>
        <Policy>AM-SetConsentStatusToInactive</Policy>
        <Policy>AM-SetConsentStatusToInvalid</Policy>
        <Policy>AM-SetConsentStatusToNotFound</Policy>
        <Policy>AM-SetCreateResponseBody</Policy>
        <Policy>AM-SetGetConsentResponse</Policy>
        <Policy>AM-SetMockListOfAccounts</Policy>
        <Policy>AM-SetNewConsentInfo</Policy>
        <Policy>AM-SetResponse204NoContent</Policy>
        <Policy>AM-SetStatusUpdateTime</Policy>
        <Policy>AM-SetUpdateResponseBody</Policy>
        <Policy>AM-SetUpdatedConsentInfo</Policy>
        <Policy>EV-ExtractConsentCacheKeyFromURIParam</Policy>
        <Policy>EV-ExtractConsentIdFromURIParam</Policy>
        <Policy>EV-ParseCachedConsentState</Policy>
        <Policy>EV-ParseExistingConsentInfo</Policy>
        <Policy>EV-ParseRequestedConsentInfo</Policy>
        <Policy>IC-RemoveFromCacheToPreventReplays</Policy>
        <Policy>JS-CheckIfConsentExpired</Policy>
        <Policy>JS-CheckPermissionIsAllowed</Policy>
        <Policy>JS-ConvertPermissionsArrayToFlatString</Policy>
        <Policy>JS-SetResourcesFromFormValues</Policy>
        <Policy>KVM-GetExistingConsent</Policy>
        <Policy>KVM-PutNewOrUpdatedConsent</Policy>
        <Policy>LC-RetrieveCachedConsentState</Policy>
        <Policy>PC-CacheConsentState</Policy>
        <Policy>RF-BadRequest</Policy>
        <Policy>RF-InvalidCachedConsent</Policy>
        <Policy>RF-InvalidConsent</Policy>
        <Policy>RF-OperationNotAllowed</Policy>
        <Policy>RF-RedirectToOIDCConsentCallback-ConsentNotFoundOrInvalid</Policy>
        <Policy>XSLT-RenderConsentScreen</Policy>
    </Policies>
    <ProxyEndpoints>
        <ProxyEndpoint>default</ProxyEndpoint>
    </ProxyEndpoints>
    <Resources>
        <Resource>xsl://renderConsentScreen.xsl</Resource>
        <Resource>jsc://checkIfConsentExpired.js</Resource>
        <Resource>jsc://checkPermissionIsAllowed.js</Resource>
        <Resource>jsc://convertArrayToFlatString.js</Resource>
        <Resource>jsc://setResourcesFromFormValues.js</Resource>
    </Resources>
    <Spec></Spec>
    <TargetServers/>
    <TargetEndpoints/>
</APIProxy>


text:
@interface PZTextField ()
@property (assign) UILabel* clLabel;
@end

@implementation PZTextField

@synthesize clLabel=_clLabel;

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    self.userInteractionEnabled = FALSE;
    return self;
}

-(void) pulseUp
{
    [UIView
     animateWithDuration:0.4
     delay:0.
     options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut
     animations:^{self.clLabel.alpha = 1.;}
     completion:^(BOOL finished){}];
}

-(void) pulse
{
    if(self.alpha!=1.)
        return; //animating

    [UIView
    animateWithDuration:0.4
     delay:0.
     options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut
     animations:^{self.clLabel.alpha = 0.7f;}
     completion:^(BOOL finished){[self pulseUp];}];

    [UIView commitAnimations];
}

-(void) setCurrentLocation
{
    [self pulse];
    if(self.clLabel)
        return;

    CGSize size = [@"Current Location" sizeWithFont:[UIFont systemFontOfSize:self.font.pointSize]];
    CGFloat x = self.frame.size.width/2 - (size.width+5)/2;
    CGFloat y = self.frame.size.height/2 - size.height/2;
    self.clLabel = [[UILabel alloc] initWithFrame:CGRectIntegral(CGRectMake(x, y, size.width+10, size.height+2))];
    self.clLabel.text = @"Current Location";
    self.clLabel.font = [UIFont systemFontOfSize:self.font.pointSize];
    self.clLabel.textAlignment = UITextAlignmentCenter;
    self.clLabel.backgroundColor = [UIColor colorWithRed:80./255. green:128./255. blue:228./255. alpha:1.];
    self.clLabel.textColor = [UIColor whiteColor];
    self.clLabel.layer.cornerRadius = 10;
    [self addSubview:self.clLabel];
    [self.clLabel release];

    self.text = @" ";
    self.textColor = [UIColor clearColor];
}

-(void) clearCurrentLocation
{
    [self.clLabel removeFromSuperview];
    self.clLabel = nil;
}

@end


text:
module ToSource
  class Emitter
    # Emitter for match operator
    class Match3 < self

      handle(Rubinius::AST::Match3)

    private

      # Perform dispatch
      #
      # @return [undefined]
      #
      # @api private
      #
      def dispatch
        util = node
        visit(util.value)
        emit(' =~ ')
        visit(util.pattern)
      end

    end
  end
end


text:
cask "jetbrains-toolbox" do
  arch = Hardware::CPU.intel? ? "" : "-arm64"

  version "1.22,1.22.10774"

  if Hardware::CPU.intel?
    sha256 "7ce32584ecc7012930d72f9871e5fba57d205a56726d1cb786bc0177ee3756eb"
  else
    sha256 "c3502cb63298876233e8ed66a1db8b9b90ab43501fe4ea8c9666970fdd2d95ff"
  end

  url "https://download.jetbrains.com/toolbox/jetbrains-toolbox-#{version.after_comma}#{arch}.dmg"
  name "JetBrains Toolbox"
  desc "JetBrains tools manager"
  homepage "https://www.jetbrains.com/toolbox-app/"

  livecheck do
    url "https://data.services.jetbrains.com/products/releases?code=TBA&latest=true&type=release"
    strategy :page_match do |page|
      JSON.parse(page)["TBA"].map do |release|
        "#{release["version"]},#{release["build"]}"
      end
    end
  end

  auto_updates true
  depends_on macos: ">= :high_sierra"

  app "JetBrains Toolbox.app"

  zap trash: [
    "~/Library/Application Support/JetBrains/Toolbox",
    "~/Library/Logs/JetBrains/Toolbox",
    "~/Library/Preferences/com.jetbrains.toolbox.renderer.plist",
    "~/Library/Saved Application State/com.jetbrains.toolbox.savedState",
  ]
end


text:
<!doctype html>
<meta charset="utf-8">
<title>Checkerboard using conic gradients</title>
<link rel="help" href="https://drafts.csswg.org/css-backgrounds-3/#propdef-background-size">
<meta name="assert" content="Gradients are correctly repeated.">
<link rel="match" href="tiled-conic-gradients-ref.html">


text:
<?php
/**
 * @author @jenschude <jens.schulze@commercetools.de>
 */

namespace Commercetools\Core\Request\Reviews;

use Commercetools\Core\Model\Common\Context;
use Commercetools\Core\Request\AbstractDeleteByKeyRequest;
use Commercetools\Core\Model\Type\Type;
use Commercetools\Core\Request\DataErasureTrait;
use Commercetools\Core\Response\ApiResponseInterface;
use Commercetools\Core\Model\Review\Review;
use Commercetools\Core\Model\MapperInterface;

/**
 * @package Commercetools\Core\Request\Reviews
 * @link https://docs.commercetools.com/http-api-projects-reviews.html#delete-review-by-key
 * @method Review mapResponse(ApiResponseInterface $response)
 * @method Review mapFromResponse(ApiResponseInterface $response, MapperInterface $mapper = null)
 */
class ReviewDeleteByKeyRequest extends AbstractDeleteByKeyRequest
{
    use DataErasureTrait;

    protected $resultClass = Review::class;

    /**
     * @param string $id
     * @param int $version
     * @param Context $context
     */
    public function __construct($id, $version, Context $context = null)
    {
        parent::__construct(ReviewsEndpoint::endpoint(), $id, $version, $context);
    }

    /**
     * @param string $key
     * @param int $version
     * @param Context $context
     * @return static
     */
    public static function ofKeyAndVersion($key, $version, Context $context = null)
    {
        return new static($key, $version, $context);
    }
}


text:
package hudson;

import hudson.model.TaskListener;
import jenkins.model.Jenkins;
import static hudson.util.jna.GNUCLibrary.LIBC;

import hudson.util.IOException2;
import hudson.util.QuotedStringTokenizer;
import hudson.util.VariableResolver;
import hudson.Proc.LocalProc;
import hudson.os.PosixAPI;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.taskdefs.Chmod;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.commons.io.IOUtils;
import org.jruby.ext.posix.FileStat;
import org.jruby.ext.posix.POSIX;
import org.kohsuke.stapler.Stapler;
import org.jvnet.animal_sniffer.IgnoreJRERequirement;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.io.PrintStream;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.SimpleTimeZone;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.nio.charset.Charset;

import com.sun.jna.Native;
import com.sun.jna.Memory;
import com.sun.jna.NativeLong;

/**
 * Various utility methods that don't have more proper home.
 *
 * @author Kohsuke Kawaguchi
 */
public class Util {

    // Constant number of milliseconds in various time units.
    private static final long ONE_SECOND_MS = 1000;
    private static final long ONE_MINUTE_MS = 60 * ONE_SECOND_MS;
    private static final long ONE_HOUR_MS = 60 * ONE_MINUTE_MS;
    private static final long ONE_DAY_MS = 24 * ONE_HOUR_MS;
    private static final long ONE_MONTH_MS = 30 * ONE_DAY_MS;
    private static final long ONE_YEAR_MS = 365 * ONE_DAY_MS;

    /**
     * Creates a filtered sublist.
     * @since 1.176
     */
    public static <T> List<T> filter( Iterable<?> base, Class<T> type ) {
        List<T> r = new ArrayList<T>();
        for (Object i : base) {
            if(type.isInstance(i))
                r.add(type.cast(i));
        }
        return r;
    }

    /**
     * Creates a filtered sublist.
     */
    public static <T> List<T> filter( List<?> base, Class<T> type ) {
        return filter((Iterable)base,type);
    }

    /**
     * Pattern for capturing variables. Either $xyz or ${xyz}, while ignoring "$$"
      */
    private static final Pattern VARIABLE = Pattern.compile("\\$([A-Za-z0-9_]+|\\{[A-Za-z0-9_]+\\}|\\$)");

    /**
     * Replaces the occurrence of '$key' by <tt>properties.get('key')</tt>.
     *
     *

     * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
     *
     */
    public static String replaceMacro(String s, Map<String,String> properties) {
        return replaceMacro(s,new VariableResolver.ByMap<String>(properties));
    }

    /**
     * Replaces the occurrence of '$key' by <tt>resolver.get('key')</tt>.
     *
     *

     * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
     */
    public static String replaceMacro(String s, VariableResolver<String> resolver) {
    	if (s == null) {
    		return null;
    	}

        int idx=0;
        while(true) {
            Matcher m = VARIABLE.matcher(s);
            if(!m.find(idx))   return s;

            String key = m.group().substring(1);

            // escape the dollar sign or get the key to resolve
            String value;
            if(key.charAt(0)=='$') {
               value = "$";
            } else {
               if(key.charAt(0)=='{')  key = key.substring(1,key.length()-1);
               value = resolver.resolve(key);
            }

            if(value==null)
                idx = m.end(); // skip this
            else {
                s = s.substring(0,m.start())+value+s.substring(m.end());
                idx = m.start() + value.length();
            }
        }
    }

    /**
     * Loads the contents of a file into a string.
     */
    public static String loadFile(File logfile) throws IOException {
        return loadFile(logfile, Charset.defaultCharset());
    }

    public static String loadFile(File logfile,Charset charset) throws IOException {
        if(!logfile.exists())
            return "";

        StringBuilder str = new StringBuilder((int)logfile.length());

        BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(logfile),charset));
        try {
            char[] buf = new char[1024];
            int len;
            while((len=r.read(buf,0,buf.length))>0)
               str.append(buf,0,len);
        } finally {
            r.close();
        }

        return str.toString();
    }

    /**
     * Deletes the contents of the given directory (but not the directory itself)
     * recursively.
     *
     * @throws IOException
     *      if the operation fails.
     */
    public static void deleteContentsRecursive(File file) throws IOException {
        File[] files = file.listFiles();
        if(files==null)
            return;     // the directory didn't exist in the first place
        for (File child : files)
            deleteRecursive(child);
    }

    /**
     * Deletes this file (and does not take no for an answer).
     * @param f a file to delete
     * @throws IOException if it exists but could not be successfully deleted
     */
    public static void deleteFile(File f) throws IOException {
        if (!f.delete()) {
            if(!f.exists())
                // we are trying to delete a file that no longer exists, so this is not an error
                return;

            // perhaps this file is read-only?
            makeWritable(f);
            /*
             on Unix both the file and the directory that contains it has to be writable
             for a file deletion to be successful. (Confirmed on Solaris 9)

             $ ls -la
             total 6
             dr-xr-sr-x   2 hudson   hudson       512 Apr 18 14:41 .
             dr-xr-sr-x   3 hudson   hudson       512 Apr 17 19:36 ..
             -r--r--r--   1 hudson   hudson       469 Apr 17 19:36 manager.xml
             -rw-r--r--   1 hudson   hudson         0 Apr 18 14:41 x
             $ rm x
             rm: x not removed: Permission denied
             */

            makeWritable(f.getParentFile());

            if(!f.delete() && f.exists()) {
                // trouble-shooting.
                // see http://www.nabble.com/Sometimes-can%27t-delete-files-from-hudson.scm.SubversionSCM%24CheckOutTask.invoke%28%29-tt17333292.html
                // I suspect other processes putting files in this directory
                File[] files = f.listFiles();
                if(files!=null && files.length>0)
                    throw new IOException("Unable to delete " + f.getPath()+" - files in dir: "+Arrays.asList(files));
                throw new IOException("Unable to delete " + f.getPath());
            }
        }
    }

    /**
     * Makes the given file writable by any means possible.
     */
    @IgnoreJRERequirement
    private static void makeWritable(File f) {
        // try chmod. this becomes no-op if this is not Unix.
        try {
            Chmod chmod = new Chmod();
            chmod.setProject(new Project());
            chmod.setFile(f);
            chmod.setPerm("u+w");
            chmod.execute();
        } catch (BuildException e) {
            LOGGER.log(Level.INFO,"Failed to chmod "+f,e);
        }

        // also try JDK6-way of doing it.
        try {
            f.setWritable(true);
        } catch (NoSuchMethodError e) {
            // not JDK6
        }

        try {// try libc chmod
            POSIX posix = PosixAPI.get();
            String path = f.getAbsolutePath();
            FileStat stat = posix.stat(path);
            posix.chmod(path, stat.mode()|0200); // u+w
        } catch (Throwable t) {
            LOGGER.log(Level.FINE,"Failed to chmod(2) "+f,t);
        }

    }

    public static void deleteRecursive(File dir) throws IOException {
        if(!isSymlink(dir))
            deleteContentsRecursive(dir);
        try {
            deleteFile(dir);
        } catch (IOException e) {
            // if some of the child directories are big, it might take long enough to delete that
            // it allows others to create new files, causing problemsl ike JENKINS-10113
            // so give it one more attempt before we give up.
            if(!isSymlink(dir))
                deleteContentsRecursive(dir);
            deleteFile(dir);
        }
    }

    /*
     * Copyright 2001-2004 The Apache Software Foundation.
     *
     * 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.
     */
    /**
     * Checks if the given file represents a symlink.
     */
    //Taken from http://svn.apache.org/viewvc/maven/shared/trunk/file-management/src/main/java/org/apache/maven/shared/model/fileset/util/FileSetManager.java?view=markup
    public static boolean isSymlink(File file) throws IOException {
        String name = file.getName();
        if (name.equals(".") || name.equals(".."))
            return false;

        File fileInCanonicalParent;
        File parentDir = file.getParentFile();
        if ( parentDir == null ) {
            fileInCanonicalParent = file;
        } else {
            fileInCanonicalParent = new File( parentDir.getCanonicalPath(), name );
        }
        return !fileInCanonicalParent.getCanonicalFile().equals( fileInCanonicalParent.getAbsoluteFile() );
    }

    /**
     * Creates a new temporary directory.
     */
    public static File createTempDir() throws IOException {
        File tmp = File.createTempFile("hudson", "tmp");
        if(!tmp.delete())
            throw new IOException("Failed to delete "+tmp);
        if(!tmp.mkdirs())
            throw new IOException("Failed to create a new directory "+tmp);
        return tmp;
    }

    private static final Pattern errorCodeParser = Pattern.compile(".*CreateProcess.*error=([0-9]+).*");

    /**
     * On Windows, error messages for IOException aren't very helpful.
     * This method generates additional user-friendly error message to the listener
     */
    public static void displayIOException( IOException e, TaskListener listener ) {
        String msg = getWin32ErrorMessage(e);
        if(msg!=null)
            listener.getLogger().println(msg);
    }

    public static String getWin32ErrorMessage(IOException e) {
        return getWin32ErrorMessage((Throwable)e);
    }

    /**
     * Extracts the Win32 error message from {@link Throwable} if possible.
     *
     * @return
     *      null if there seems to be no error code or if the platform is not Win32.
     */
    public static String getWin32ErrorMessage(Throwable e) {
        String msg = e.getMessage();
        if(msg!=null) {
            Matcher m = errorCodeParser.matcher(msg);
            if(m.matches()) {
                try {
                    ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
                    return rb.getString("error"+m.group(1));
                } catch (Exception _) {
                    // silently recover from resource related failures
                }
            }
        }

        if(e.getCause()!=null)
            return getWin32ErrorMessage(e.getCause());
        return null; // no message
    }

    /**
     * Gets a human readable message for the given Win32 error code.
     *
     * @return
     *      null if no such message is available.
     */
    public static String getWin32ErrorMessage(int n) {
        try {
            ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
            return rb.getString("error"+n);
        } catch (MissingResourceException e) {
            LOGGER.log(Level.WARNING,"Failed to find resource bundle",e);
            return null;
        }
    }

    /**
     * Guesses the current host name.
     */
    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "localhost";
        }
    }

    public static void copyStream(InputStream in,OutputStream out) throws IOException {
        byte[] buf = new byte[8192];
        int len;
        while((len=in.read(buf))>0)
            out.write(buf,0,len);
    }

    public static void copyStream(Reader in, Writer out) throws IOException {
        char[] buf = new char[8192];
        int len;
        while((len=in.read(buf))>0)
            out.write(buf,0,len);
    }

    public static void copyStreamAndClose(InputStream in,OutputStream out) throws IOException {
        try {
            copyStream(in,out);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }

    public static void copyStreamAndClose(Reader in,Writer out) throws IOException {
        try {
            copyStream(in,out);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * Tokenizes the text separated by delimiters.
     *
     *

     * In 1.210, this method was changed to handle quotes like Unix shell does.
     * Before that, this method just used {@link StringTokenizer}.
     *
     * @since 1.145
     * @see QuotedStringTokenizer
     */
    public static String[] tokenize(String s,String delimiter) {
        return QuotedStringTokenizer.tokenize(s,delimiter);
    }

    public static String[] tokenize(String s) {
        return tokenize(s," \t\n\r\f");
    }

    /**
     * Converts the map format of the environment variables to the K=V format in the array.
     */
    public static String[] mapToEnv(Map<String,String> m) {
        String[] r = new String[m.size()];
        int idx=0;

        for (final Map.Entry<String,String> e : m.entrySet()) {
            r[idx++] = e.getKey() + '=' + e.getValue();
        }
        return r;
    }

    public static int min(int x, int... values) {
        for (int i : values) {
            if(i<x)
                x=i;
        }
        return x;
    }

    public static String nullify(String v) {
        if(v!=null && v.length()==0)    v=null;
        return v;
    }

    public static String removeTrailingSlash(String s) {
        if(s.endsWith("/")) return s.substring(0,s.length()-1);
        else                return s;
    }

    /**
     * Computes MD5 digest of the given input stream.
     *
     * @param source
     *      The stream will be closed by this method at the end of this method.
     * @return
     *      32-char wide string
     */
    public static String getDigestOf(InputStream source) throws IOException {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");

            byte[] buffer = new byte[1024];
            DigestInputStream in =new DigestInputStream(source,md5);
            try {
                while(in.read(buffer)>0)
                    ; // simply discard the input
            } finally {
                in.close();
            }
            return toHexString(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new IOException2("MD5 not installed",e);    // impossible
        }
    }

    public static String getDigestOf(String text) {
        try {
            return getDigestOf(new ByteArrayInputStream(text.getBytes("UTF-8")));
        } catch (IOException e) {
            throw new Error(e);
        }
    }

    /**
     * Converts a string into 128-bit AES key.
     * @since 1.308
     */
    public static SecretKey toAes128Key(String s) {
        try {
            // turn secretKey into 256 bit hash
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.reset();
            digest.update(s.getBytes("UTF-8"));

            // Due to the stupid US export restriction JDK only ships 128bit version.
            return new SecretKeySpec(digest.digest(),0,128/8, "AES");
        } catch (NoSuchAlgorithmException e) {
            throw new Error(e);
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
    }

    public static String toHexString(byte[] data, int start, int len) {
        StringBuilder buf = new StringBuilder();
        for( int i=0; i<len; i++ ) {
            int b = data[start+i]&0xFF;
            if(b<16)    buf.append('0');
            buf.append(Integer.toHexString(b));
        }
        return buf.toString();
    }

    public static String toHexString(byte[] bytes) {
        return toHexString(bytes,0,bytes.length);
    }

    public static byte[] fromHexString(String data) {
        byte[] r = new byte[data.length() / 2];
        for (int i = 0; i < data.length(); i += 2)
            r[i / 2] = (byte) Integer.parseInt(data.substring(i, i + 2), 16);
        return r;
    }

    /**
     * Returns a human readable text of the time duration, for example "3 minutes 40 seconds".
     * This version should be used for representing a duration of some activity (like build)
     *
     * @param duration
     *      number of milliseconds.
     */
    public static String getTimeSpanString(long duration) {
        // Break the duration up in to units.
        long years = duration / ONE_YEAR_MS;
        duration %= ONE_YEAR_MS;
        long months = duration / ONE_MONTH_MS;
        duration %= ONE_MONTH_MS;
        long days = duration / ONE_DAY_MS;
        duration %= ONE_DAY_MS;
        long hours = duration / ONE_HOUR_MS;
        duration %= ONE_HOUR_MS;
        long minutes = duration / ONE_MINUTE_MS;
        duration %= ONE_MINUTE_MS;
        long seconds = duration / ONE_SECOND_MS;
        duration %= ONE_SECOND_MS;
        long millisecs = duration;

        if (years > 0)
            return makeTimeSpanString(years, Messages.Util_year(years), months, Messages.Util_month(months));
        else if (months > 0)
            return makeTimeSpanString(months, Messages.Util_month(months), days, Messages.Util_day(days));
        else if (days > 0)
            return makeTimeSpanString(days, Messages.Util_day(days), hours, Messages.Util_hour(hours));
        else if (hours > 0)
            return makeTimeSpanString(hours, Messages.Util_hour(hours), minutes, Messages.Util_minute(minutes));
        else if (minutes > 0)
            return makeTimeSpanString(minutes, Messages.Util_minute(minutes), seconds, Messages.Util_second(seconds));
        else if (seconds >= 10)
            return Messages.Util_second(seconds);
        else if (seconds >= 1)
            return Messages.Util_second(seconds+(float)(millisecs/100)/10); // render "1.2 sec"
        else if(millisecs>=100)
            return Messages.Util_second((float)(millisecs/10)/100); // render "0.12 sec".
        else
            return Messages.Util_millisecond(millisecs);
    }

    /**
     * Create a string representation of a time duration.  If the quantity of
     * the most significant unit is big (>=10), then we use only that most
     * significant unit in the string representation. If the quantity of the
     * most significant unit is small (a single-digit value), then we also
     * use a secondary, smaller unit for increased precision.
     * So 13 minutes and 43 seconds returns just "13 minutes", but 3 minutes
     * and 43 seconds is "3 minutes 43 seconds".
     */
    private static String makeTimeSpanString(long bigUnit,
                                             String bigLabel,
                                             long smallUnit,
                                             String smallLabel) {
        String text = bigLabel;
        if (bigUnit < 10)
            text += ' ' + smallLabel;
        return text;
    }

    /**
     * Get a human readable string representing strings like "xxx days ago",
     * which should be used to point to the occurrence of an event in the past.
     */
    public static String getPastTimeString(long duration) {
        return Messages.Util_pastTime(getTimeSpanString(duration));
    }

    /**
     * Combines number and unit, with a plural suffix if needed.
     *
     * @deprecated
     *   Use individual localization methods instead.
     *   See {@link Messages#Util_year(Object)} for an example.
     *   Deprecated since 2009-06-24, remove method after 2009-12-24.
     */
    public static String combine(long n, String suffix) {
        String s = Long.toString(n)+' '+suffix;
        if(n!=1)
        	// Just adding an 's' won't work in most natural languages, even English has exception to the rule (e.g. copy/copies).
            s += "s";
        return s;
    }

    /**
     * Create a sub-list by only picking up instances of the specified type.
     */
    public static <T> List<T> createSubList( Collection<?> source, Class<T> type ) {
        List<T> r = new ArrayList<T>();
        for (Object item : source) {
            if(type.isInstance(item))
                r.add(type.cast(item));
        }
        return r;
    }

    /**
     * Escapes non-ASCII characters in URL.
     *
     *

     * Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters,
     * such as '#'.
     * {@link #rawEncode(String)} should generally be used instead, though be careful to pass only
     * a single path component to that method (it will encode /, but this method does not).
     */
    public static String encode(String s) {
        try {
            boolean escaped = false;

            StringBuilder out = new StringBuilder(s.length());

            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            OutputStreamWriter w = new OutputStreamWriter(buf,"UTF-8");

            for (int i = 0; i < s.length(); i++) {
                int c = s.charAt(i);
                if (c<128 && c!=' ') {
                    out.append((char) c);
                } else {
                    // 1 char -> UTF8
                    w.write(c);
                    w.flush();
                    for (byte b : buf.toByteArray()) {
                        out.append('%');
                        out.append(toDigit((b >> 4) & 0xF));
                        out.append(toDigit(b & 0xF));
                    }
                    buf.reset();
                    escaped = true;
                }
            }

            return escaped ? out.toString() : s;
        } catch (IOException e) {
            throw new Error(e); // impossible
        }
    }

    private static final boolean[] uriMap = new boolean[123];
    static {
        String raw =
    "!  $ &'()*+,-. 0123456789   =  @ABCDEFGHIJKLMNOPQRSTUVWXYZ    _ abcdefghijklmnopqrstuvwxyz";
  //  "# %         /          :;< >?                           [\]^ `                          {|}~
  //  ^--so these are encoded
        int i;
        // Encode control chars and space
        for (i = 0; i < 33; i++) uriMap[i] = true;
        for (int j = 0; j < raw.length(); i++, j++)
            uriMap[i] = (raw.charAt(j) == ' ');
        // If we add encodeQuery() just add a 2nd map to encode &+=
        // queryMap[38] = queryMap[43] = queryMap[61] = true;
    }

    /**
     * Encode a single path component for use in an HTTP URL.
     * Escapes all non-ASCII, general unsafe (space and "#%<>[\]^`{|}~)
     * and HTTP special characters (/;:?) as specified in RFC1738.
     * (so alphanumeric and !@$&*()-_=+',. are not encoded)
     * Note that slash(/) is encoded, so the given string should be a
     * single path component used in constructing a URL.
     * Method name inspired by PHP's rawurlencode.
     */
    public static String rawEncode(String s) {
        boolean escaped = false;
        StringBuilder out = null;
        CharsetEncoder enc = null;
        CharBuffer buf = null;
        char c;
        for (int i = 0, m = s.length(); i < m; i++) {
            c = s.charAt(i);
            if (c > 122 || uriMap[c]) {
                if (!escaped) {
                    out = new StringBuilder(i + (m - i) * 3);
                    out.append(s.substring(0, i));
                    enc = Charset.forName("UTF-8").newEncoder();
                    buf = CharBuffer.allocate(1);
                    escaped = true;
                }
                // 1 char -> UTF8
                buf.put(0,c);
                buf.rewind();
                try {
                    ByteBuffer bytes = enc.encode(buf);
                    while (bytes.hasRemaining()) {
                        byte b = bytes.get();
                        out.append('%');
                        out.append(toDigit((b >> 4) & 0xF));
                        out.append(toDigit(b & 0xF));
                    }
                } catch (CharacterCodingException ex) { }
            } else if (escaped) {
                out.append(c);
            }
        }
        return escaped ? out.toString() : s;
    }

    private static char toDigit(int n) {
        return (char)(n < 10 ? '0' + n : 'A' + n - 10);
    }

    /**
     * Surrounds by a single-quote.
     */
    public static String singleQuote(String s) {
        return '\''+s+'\'';
    }

    /**
     * Escapes HTML unsafe characters like <, & to the respective character entities.
     */
    public static String escape(String text) {
        if (text==null)     return null;
        StringBuilder buf = new StringBuilder(text.length()+64);
        for( int i=0; i<text.length(); i++ ) {
            char ch = text.charAt(i);
            if(ch=='\n')
                buf.append("
");
            else
            if(ch=='<')
                buf.append("<");
            else
            if(ch=='&')
                buf.append("&");
            else
            if(ch=='"')
                buf.append(""");
            else
            if(ch=='\'')
                buf.append("'");
            else
            if(ch==' ') {
                // All spaces in a block of consecutive spaces are converted to
                // non-breaking space ( ) except for the last one.  This allows
                // significant whitespace to be retained without prohibiting wrapping.
                char nextCh = i+1 < text.length() ? text.charAt(i+1) : 0;
                buf.append(nextCh==' ' ? " " : " ");
            }
            else
                buf.append(ch);
        }
        return buf.toString();
    }

    public static String xmlEscape(String text) {
        StringBuilder buf = new StringBuilder(text.length()+64);
        for( int i=0; i<text.length(); i++ ) {
            char ch = text.charAt(i);
            if(ch=='<')
                buf.append("<");
            else
            if(ch=='&')
                buf.append("&");
            else
                buf.append(ch);
        }
        return buf.toString();
    }

    /**
     * Creates an empty file.
     */
    public static void touch(File file) throws IOException {
        new FileOutputStream(file).close();
    }

    /**
     * Copies a single file by using Ant.
     */
    public static void copyFile(File src, File dst) throws BuildException {
        Copy cp = new Copy();
        cp.setProject(new org.apache.tools.ant.Project());
        cp.setTofile(dst);
        cp.setFile(src);
        cp.setOverwrite(true);
        cp.execute();
    }

    /**
     * Convert null to "".
     */
    public static String fixNull(String s) {
        if(s==null)     return "";
        else            return s;
    }

    /**
     * Convert empty string to null.
     */
    public static String fixEmpty(String s) {
        if(s==null || s.length()==0)    return null;
        return s;
    }

    /**
     * Convert empty string to null, and trim whitespace.
     *
     * @since 1.154
     */
    public static String fixEmptyAndTrim(String s) {
        if(s==null)    return null;
        return fixEmpty(s.trim());
    }

    public static <T> List<T> fixNull(List<T> l) {
        return l!=null ? l : Collections.<T>emptyList();
    }

    public static <T> Set<T> fixNull(Set<T> l) {
        return l!=null ? l : Collections.<T>emptySet();
    }

    public static <T> Collection<T> fixNull(Collection<T> l) {
        return l!=null ? l : Collections.<T>emptySet();
    }

    public static <T> Iterable<T> fixNull(Iterable<T> l) {
        return l!=null ? l : Collections.<T>emptySet();
    }

    /**
     * Cuts all the leading path portion and get just the file name.
     */
    public static String getFileName(String filePath) {
        int idx = filePath.lastIndexOf('\\');
        if(idx>=0)
            return getFileName(filePath.substring(idx+1));
        idx = filePath.lastIndexOf('/');
        if(idx>=0)
            return getFileName(filePath.substring(idx+1));
        return filePath;
    }

    /**
     * Concatenate multiple strings by inserting a separator.
     */
    public static String join(Collection<?> strings, String separator) {
        StringBuilder buf = new StringBuilder();
        boolean first=true;
        for (Object s : strings) {
            if(first)   first=false;
            else        buf.append(separator);
            buf.append(s);
        }
        return buf.toString();
    }

    /**
     * Combines all the given collections into a single list.
     */
    public static <T> List<T> join(Collection<? extends T>... items) {
        int size = 0;
        for (Collection<? extends T> item : items)
            size += item.size();
        List<T> r = new ArrayList<T>(size);
        for (Collection<? extends T> item : items)
            r.addAll(item);
        return r;
    }

    /**
     * Creates Ant {@link FileSet} with the base dir and include pattern.
     *
     *

     * The difference with this and using {@link FileSet#setIncludes(String)}
     * is that this method doesn't treat whitespace as a pattern separator,
     * which makes it impossible to use space in the file path.
     *
     * @param includes
     *      String like "foo/bar/*.xml" Multiple patterns can be separated
     *      by ',', and whitespace can surround ',' (so that you can write
     *      "abc, def" and "abc,def" to mean the same thing.
     * @param excludes
     *      Exclusion pattern. Follows the same format as the 'includes' parameter.
     *      Can be null.
     * @since 1.172
     */
    public static FileSet createFileSet(File baseDir, String includes, String excludes) {
        FileSet fs = new FileSet();
        fs.setDir(baseDir);
        fs.setProject(new Project());

        StringTokenizer tokens;

        tokens = new StringTokenizer(includes,",");
        while(tokens.hasMoreTokens()) {
            String token = tokens.nextToken().trim();
            fs.createInclude().setName(token);
        }
        if(excludes!=null) {
            tokens = new StringTokenizer(excludes,",");
            while(tokens.hasMoreTokens()) {
                String token = tokens.nextToken().trim();
                fs.createExclude().setName(token);
            }
        }
        return fs;
    }

    public static FileSet createFileSet(File baseDir, String includes) {
        return createFileSet(baseDir,includes,null);
    }

    /**
     * Creates a symlink to baseDir+targetPath at baseDir+symlinkPath.
     *

     * If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
     *
     * @param baseDir
     *      Base directory to resolve the 'symlinkPath' parameter.
     * @param targetPath
     *      The file that the symlink should point to.
     * @param symlinkPath
     *      Where to create a symlink in.
     */
    public static void createSymlink(File baseDir, String targetPath, String symlinkPath, TaskListener listener) throws InterruptedException {
        if(Functions.isWindows() || NO_SYMLINK)   return;

        try {
            String errmsg = "";
            // if a file or a directory exists here, delete it first.
            // try simple delete first (whether exists() or not, as it may be symlink pointing
            // to non-existent target), but fallback to "rm -rf" to delete non-empty dir.
            File symlinkFile = new File(baseDir, symlinkPath);
            if (!symlinkFile.delete() && symlinkFile.exists())
                // ignore a failure.
                new LocalProc(new String[]{"rm","-rf", symlinkPath},new String[0],listener.getLogger(), baseDir).join();

            int r;
            if (!SYMLINK_ESCAPEHATCH) {
                try {
                    r = LIBC.symlink(targetPath,symlinkFile.getAbsolutePath());
                    if (r!=0) {
                        r = Native.getLastError();
                        errmsg = LIBC.strerror(r);
                    }
                } catch (LinkageError e) {
                    // if JNA is unavailable, fall back.
                    // we still prefer to try JNA first as PosixAPI supports even smaller platforms.
                    r = PosixAPI.get().symlink(targetPath,symlinkFile.getAbsolutePath());
                }
            } else // escape hatch, until we know that the above works well.
                r = new LocalProc(new String[]{
                    "ln","-s", targetPath, symlinkPath},
                    new String[0],listener.getLogger(), baseDir).join();
            if(r!=0)
                listener.getLogger().println(String.format("ln -s %s %s failed: %d %s",targetPath, symlinkFile, r, errmsg));
        } catch (IOException e) {
            PrintStream log = listener.getLogger();
            log.printf("ln %s %s failed%n",targetPath, new File(baseDir, symlinkPath));
            Util.displayIOException(e,listener);
            e.printStackTrace( log );
        }
    }

    /**
     * Resolves symlink, if the given file is a symlink. Otherwise return null.
     *

     * If the resolution fails, report an error.
     *
     * @param listener
     *      If we rely on an external command to resolve symlink, this is it.
     *      (TODO: try readlink(1) available on some platforms)
     */
    public static String resolveSymlink(File link, TaskListener listener) throws InterruptedException, IOException {
        if(Functions.isWindows())     return null;

        String filename = link.getAbsolutePath();
        try {
            for (int sz=512; sz < 65536; sz*=2) {
                Memory m = new Memory(sz);
                int r = LIBC.readlink(filename,m,new NativeLong(sz));
                if (r<0) {
                    int err = Native.getLastError();
                    if (err==22/*EINVAL --- but is this really portable?*/)
                        return null; // this means it's not a symlink
                    throw new IOException("Failed to readlink "+link+" error="+ err+" "+ LIBC.strerror(err));
                }
                if (r==sz)
                    continue;   // buffer too small

                byte[] buf = new byte[r];
                m.read(0,buf,0,r);
                return new String(buf);
            }
            // something is wrong. It can't be this long!
            throw new IOException("Symlink too long: "+link);
        } catch (LinkageError e) {
            // if JNA is unavailable, fall back.
            // we still prefer to try JNA first as PosixAPI supports even smaller platforms.
            return PosixAPI.get().readlink(filename);
        }
    }

    /**
     * Encodes the URL by RFC 2396.
     *
     * I thought there's another spec that refers to UTF-8 as the encoding,
     * but don't remember it right now.
     *
     * @since 1.204
     * @deprecated since 2008-05-13. This method is broken (see ISSUE#1666). It should probably
     * be removed but I'm not sure if it is considered part of the public API
     * that needs to be maintained for backwards compatibility.
     * Use {@link #encode(String)} instead.
     */
    @Deprecated
    public static String encodeRFC2396(String url) {
        try {
            return new URI(null,url,null).toASCIIString();
        } catch (URISyntaxException e) {
            LOGGER.warning("Failed to encode "+url);    // could this ever happen?
            return url;
        }
    }

    /**
     * Wraps with the error icon and the CSS class to render error message.
     * @since 1.173
     */
    public static String wrapToErrorSpan(String s) {
        s = ""+s+"";
        return s;
    }

    /**
     * Returns the parsed string if parsed successful; otherwise returns the default number.
     * If the string is null, empty or a ParseException is thrown then the defaultNumber
     * is returned.
     * @param numberStr string to parse
     * @param defaultNumber number to return if the string can not be parsed
     * @return returns the parsed string; otherwise the default number
     */
    public static Number tryParseNumber(String numberStr, Number defaultNumber) {
        if ((numberStr == null) || (numberStr.length() == 0)) {
            return defaultNumber;
        }
        try {
            return NumberFormat.getNumberInstance().parse(numberStr);
        } catch (ParseException e) {
            return defaultNumber;
        }
    }

    /**
     * Checks if the public method defined on the base type with the given arguments
     * are overridden in the given derived type.
     */
    public static boolean isOverridden(Class base, Class derived, String methodName, Class... types) {
        // the rewriteHudsonWar method isn't overridden.
        try {
            return !base.getMethod(methodName, types).equals(
                    derived.getMethod(methodName,types));
        } catch (NoSuchMethodException e) {
            throw new AssertionError(e);
        }
    }

    /**
     * Returns a file name by changing its extension.
     *
     * @param ext
     *      For example, ".zip"
     */
    public static File changeExtension(File dst, String ext) {
        String p = dst.getPath();
        int pos = p.lastIndexOf('.');
        if (pos<0)  return new File(p+ext);
        else        return new File(p.substring(0,pos)+ext);
    }

    /**
     * Null-safe String intern method.
     */
    public static String intern(String s) {
        return s==null ? s : s.intern();
    }

    /**
     * Loads a key/value pair string as {@link Properties}
     * @since 1.392
     */
    @IgnoreJRERequirement
    public static Properties loadProperties(String properties) throws IOException {
        Properties p = new Properties();
        try {
            p.load(new StringReader(properties));
        } catch (NoSuchMethodError e) {
            // load(Reader) method is only available on JDK6.
            // this fall back version doesn't work correctly with non-ASCII characters,
            // but there's no other easy ways out it seems.
            p.load(new ByteArrayInputStream(properties.getBytes()));
        }
        return p;
    }

    public static final FastDateFormat XS_DATETIME_FORMATTER = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss'Z'",new SimpleTimeZone(0,"GMT"));

    // Note: RFC822 dates must not be localized!
    public static final FastDateFormat RFC822_DATETIME_FORMATTER
            = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);

    private static final Logger LOGGER = Logger.getLogger(Util.class.getName());

    /**
     * On Unix environment that cannot run "ln", set this to true.
     */
    public static boolean NO_SYMLINK = Boolean.getBoolean(Util.class.getName()+".noSymLink");

    public static boolean SYMLINK_ESCAPEHATCH = Boolean.getBoolean(Util.class.getName()+".symlinkEscapeHatch");
}


text:
from mailhandler.adapters import BaseAdapter

class TrackingAdapter(BaseAdapter):
    """
    Tracking features adapter.
    """
    name = 'tracking'

    def email_events(self, unique_id):
        url = self.get_url('/message/events/%s/' % unique_id)
        response = self._get(url)
        return response.json()


text:
//
//  JSNewsImgsTableViewCell.h
//  SYJNeteaseNews
//
//  Created by ShenYj on 2017/1/5.
//  Copyright © 2017年 ShenYj. All rights reserved.
//

#import <UIKit/UIKit.h>

@class JSNewsModel;

@interface JSNewsImgsTableViewCell : UITableViewCell

/** 新闻模型数据 */
@property (nonatomic) JSNewsModel *newsModel;

@end


text:
package com.bond.spider.cnjy.service;

import com.bond.spider.cnjy.dao.ChidDao;
import com.bond.spider.cnjy.model.ChidModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;

@Service
public class ChidService  extends ChidServiceGen{

    @Autowired
    private ChidDao chidDao;

}


text:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Apppp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="assets/font-awesome.min.css" rel="stylesheet">

  <link href="https://fonts.googleapis.com/css?family=Bungee+Inline|Love+Ya+Like+A+Sister|Wendy+One" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Gloria+Hallelujah|Indie+Flower|Ravi+Prakash" rel="stylesheet">
</head>
<body>
  <my-app>Loading...</my-app>

  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script src="assets/bootstrap-v3.3.7/js/bootstrap.min.js"></script>
</body>
</html>


text:
'use strict'

const Wmata = require('./captran-wmata')

// shortcut query params for dev

const pentagon = {
  busesNearby: {
    api: 'busPositions',
    Lat: 38.8690011,
    Lon: -77.0544217,
    Radius: 500
  },
  stopsNearby: {
    api: 'stops',
    Lat: 38.8690011,
    Lon: -77.0544217,
    Radius: 500
  }
}
const lafeyette = {
  busPredictions: {
    api: 'stopPredictions',
    StopID: '1001141'
  }
}
const farragutMurrow = {
  busPredictions: {
    api: 'stopPredictions',
    StopID: '1001133'
  }
}

class WmataDev extends Wmata {

  // returns a string
  static get DEV () { return 'apple' }

  // functions for testing and dev
  queryBusesNearPentagon (callback) {
    return this.query(pentagon.busesNearby, callback)
  }
  queryStopsNearPentagon (callback) {
    return this.query(pentagon.stopsNearby, callback)
  }
  queryBusPredictionsNearWH (callback) {
    return this.query(lafeyette.busPredictions, callback)
  }
  queryBusPredicctionsNearFarragut (callback) {
    return this.query(farragutMurrow.busPredictions, callback)
  }
  consoleCall (params) {
    this.callWmata(params).then(console.log)
  } // or just throw in console.log as this.query's callback

}

module.exports = WmataDev


text:
FROM ruby:2.1.5

ENV MAILCATCHER_ENV production

RUN git clone --depth 1 -b with_assets \
    https://github.com/Paxa/mailcatcher.git /mailcatcher

WORKDIR /mailcatcher

RUN bundle install --deployment && \
    gem build ./mailcatcher.gemspec && \
    gem install ./mailcatcher-0.6.0.gem

WORKDIR /

RUN rm -rf /mailcatcher

EXPOSE 1025 1080

CMD ["mailcatcher", "--smtp-ip=0.0.0.0", "--http-ip=0.0.0.0", "--foreground"]


text:
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import ExecutionPlanService
from dbaas_services.analyzing.forms import ExecutionPlanForm

class ExecutionPlanAdmin(admin.DjangoServicesAdmin):
    form = ExecutionPlanForm
    service_class = ExecutionPlanService
    list_display = ("plan_name", "metrics", "threshold",
                    "proccess_function", "adapter", "alarm_repository_attr",)


text:
<?xml version="1.0" encoding="utf-8" ?>
<Moc-Config>
	<MOC MOC_NAME="MRSRecRangeList" MOC_NAME_C="录音录像号段" Module="MRS" ACCESS_CONTROL="add,delete,modify,read" DEST_SVC="custom:ubp_mrs_moc:CreateModule:before" Group="MRSSipGrp" Relation="">
		<Parameter name="ID" desc="区间ID" type="int" range="[1,2147483647]" constrain="PRI" mode="display" />
		<Parameter name="Name" desc="区间描述" type="string" range="[0,512]" mode="update" />
		<Parameter name="BeginISDN" desc="起始ISDN" type="string" range="[1,8]" constrain="NOT NULL" not_begin_with="0" all_num="" mode="update" />
		<Parameter name="EndISDN" desc="终止ISDN" type="string" range="[1,8]" constrain="NOT NULL" not_begin_with="0" all_num="" mode="update" />
	</MOC>
</Moc-Config>