text:
"use strict";

exports.__esModule = true;

var _keys = require("babel-runtime/core-js/object/keys");

var _keys2 = _interopRequireDefault(_keys);

var _create = require("babel-runtime/core-js/object/create");

var _create2 = _interopRequireDefault(_create);

var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _getIterator2 = require("babel-runtime/core-js/get-iterator");

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _includes = require("lodash/includes");

var _includes2 = _interopRequireDefault(_includes);

var _repeat = require("lodash/repeat");

var _repeat2 = _interopRequireDefault(_repeat);

var _renamer = require("./lib/renamer");

var _renamer2 = _interopRequireDefault(_renamer);

var _index = require("../index");

var _index2 = _interopRequireDefault(_index);

var _defaults = require("lodash/defaults");

var _defaults2 = _interopRequireDefault(_defaults);

var _babelMessages = require("babel-messages");

var messages = _interopRequireWildcard(_babelMessages);

var _binding2 = require("./binding");

var _binding3 = _interopRequireDefault(_binding2);

var _globals = require("globals");

var _globals2 = _interopRequireDefault(_globals);

var _babelTypes = require("babel-types");

var t = _interopRequireWildcard(_babelTypes);

var _cache = require("../cache");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _crawlCallsCount = 0;

function getCache(path, parentScope, self) {
  var scopes = _cache.scope.get(path.node) || [];

  for (var _iterator = scopes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
    var _ref;

    if (_isArray) {
      if (_i >= _iterator.length) break;
      _ref = _iterator[_i++];
    } else {
      _i = _iterator.next();
      if (_i.done) break;
      _ref = _i.value;
    }

    var scope = _ref;

    if (scope.parent === parentScope && scope.path === path) return scope;
  }

  scopes.push(self);

  if (!_cache.scope.has(path.node)) {
    _cache.scope.set(path.node, scopes);
  }
}

var collectorVisitor = {
  For: function For(path) {
    for (var _iterator2 = t.FOR_INIT_KEYS, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
      var _ref2;

      if (_isArray2) {
        if (_i2 >= _iterator2.length) break;
        _ref2 = _iterator2[_i2++];
      } else {
        _i2 = _iterator2.next();
        if (_i2.done) break;
        _ref2 = _i2.value;
      }

      var key = _ref2;

      var declar = path.get(key);
      if (declar.isVar()) path.scope.getFunctionParent().registerBinding("var", declar);
    }
  },
  Declaration: function Declaration(path) {
    if (path.isBlockScoped()) return;

    if (path.isExportDeclaration() && path.get("declaration").isDeclaration()) return;

    path.scope.getFunctionParent().registerDeclaration(path);
  },
  ReferencedIdentifier: function ReferencedIdentifier(path, state) {
    state.references.push(path);
  },
  ForXStatement: function ForXStatement(path, state) {
    var left = path.get("left");
    if (left.isPattern() || left.isIdentifier()) {
      state.constantViolations.push(left);
    }
  },

  ExportDeclaration: {
    exit: function exit(_ref3) {
      var node = _ref3.node;
      var scope = _ref3.scope;

      var declar = node.declaration;
      if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar)) {
        var _id = declar.id;
        if (!_id) return;

        var binding = scope.getBinding(_id.name);
        if (binding) binding.reference();
      } else if (t.isVariableDeclaration(declar)) {
        for (var _iterator3 = declar.declarations, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) {
          var _ref4;

          if (_isArray3) {
            if (_i3 >= _iterator3.length) break;
            _ref4 = _iterator3[_i3++];
          } else {
            _i3 = _iterator3.next();
            if (_i3.done) break;
            _ref4 = _i3.value;
          }

          var decl = _ref4;

          var ids = t.getBindingIdentifiers(decl);
          for (var name in ids) {
            var _binding = scope.getBinding(name);
            if (_binding) _binding.reference();
          }
        }
      }
    }
  },

  LabeledStatement: function LabeledStatement(path) {
    path.scope.getProgramParent().addGlobal(path.node);
    path.scope.getBlockParent().registerDeclaration(path);
  },
  AssignmentExpression: function AssignmentExpression(path, state) {
    state.assignments.push(path);
  },
  UpdateExpression: function UpdateExpression(path, state) {
    state.constantViolations.push(path.get("argument"));
  },
  UnaryExpression: function UnaryExpression(path, state) {
    if (path.node.operator === "delete") {
      state.constantViolations.push(path.get("argument"));
    }
  },
  BlockScoped: function BlockScoped(path) {
    var scope = path.scope;
    if (scope.path === path) scope = scope.parent;
    scope.getBlockParent().registerDeclaration(path);
  },
  ClassDeclaration: function ClassDeclaration(path) {
    var id = path.node.id;
    if (!id) return;

    var name = id.name;
    path.scope.bindings[name] = path.scope.getBinding(name);
  },
  Block: function Block(path) {
    var paths = path.get("body");
    for (var _iterator4 = paths, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) {
      var _ref5;

      if (_isArray4) {
        if (_i4 >= _iterator4.length) break;
        _ref5 = _iterator4[_i4++];
      } else {
        _i4 = _iterator4.next();
        if (_i4.done) break;
        _ref5 = _i4.value;
      }

      var bodyPath = _ref5;

      if (bodyPath.isFunctionDeclaration()) {
        path.scope.getBlockParent().registerDeclaration(bodyPath);
      }
    }
  }
};

var uid = 0;

var Scope = function () {
  function Scope(path, parentScope) {
    (0, _classCallCheck3.default)(this, Scope);

    if (parentScope && parentScope.block === path.node) {
      return parentScope;
    }

    var cached = getCache(path, parentScope, this);
    if (cached) return cached;

    this.uid = uid++;
    this.parent = parentScope;
    this.hub = path.hub;

    this.parentBlock = path.parent;
    this.block = path.node;
    this.path = path;
  }

  Scope.prototype.traverse = function traverse(node, opts, state) {
    (0, _index2.default)(node, opts, this, state, this.path);
  };

  Scope.prototype.generateDeclaredUidIdentifier = function generateDeclaredUidIdentifier() {
    var name = arguments.length <= 0 || arguments[0] === undefined ? "temp" : arguments[0];

    var id = this.generateUidIdentifier(name);
    this.push({ id: id });
    return id;
  };

  Scope.prototype.generateUidIdentifier = function generateUidIdentifier() {
    var name = arguments.length <= 0 || arguments[0] === undefined ? "temp" : arguments[0];

    return t.identifier(this.generateUid(name));
  };

  Scope.prototype.generateUid = function generateUid() {
    var name = arguments.length <= 0 || arguments[0] === undefined ? "temp" : arguments[0];

    name = t.toIdentifier(name).replace(/^_+/, "").replace(/[0-9]+$/g, "");

    var uid = void 0;
    var i = 0;
    do {
      uid = this._generateUid(name, i);
      i++;
    } while (this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid));

    var program = this.getProgramParent();
    program.references[uid] = true;
    program.uids[uid] = true;

    return uid;
  };

  Scope.prototype._generateUid = function _generateUid(name, i) {
    var id = name;
    if (i > 1) id += i;
    return "_" + id;
  };

  Scope.prototype.generateUidIdentifierBasedOnNode = function generateUidIdentifierBasedOnNode(parent, defaultName) {
    var node = parent;

    if (t.isAssignmentExpression(parent)) {
      node = parent.left;
    } else if (t.isVariableDeclarator(parent)) {
      node = parent.id;
    } else if (t.isObjectProperty(node) || t.isObjectMethod(node)) {
      node = node.key;
    }

    var parts = [];

    var add = function add(node) {
      if (t.isModuleDeclaration(node)) {
        if (node.source) {
          add(node.source);
        } else if (node.specifiers && node.specifiers.length) {
          for (var _iterator5 = node.specifiers, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) {
            var _ref6;

            if (_isArray5) {
              if (_i5 >= _iterator5.length) break;
              _ref6 = _iterator5[_i5++];
            } else {
              _i5 = _iterator5.next();
              if (_i5.done) break;
              _ref6 = _i5.value;
            }

            var specifier = _ref6;

            add(specifier);
          }
        } else if (node.declaration) {
          add(node.declaration);
        }
      } else if (t.isModuleSpecifier(node)) {
        add(node.local);
      } else if (t.isMemberExpression(node)) {
        add(node.object);
        add(node.property);
      } else if (t.isIdentifier(node)) {
        parts.push(node.name);
      } else if (t.isLiteral(node)) {
        parts.push(node.value);
      } else if (t.isCallExpression(node)) {
        add(node.callee);
      } else if (t.isObjectExpression(node) || t.isObjectPattern(node)) {
        for (var _iterator6 = node.properties, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) {
          var _ref7;

          if (_isArray6) {
            if (_i6 >= _iterator6.length) break;
            _ref7 = _iterator6[_i6++];
          } else {
            _i6 = _iterator6.next();
            if (_i6.done) break;
            _ref7 = _i6.value;
          }

          var prop = _ref7;

          add(prop.key || prop.argument);
        }
      }
    };

    add(node);

    var id = parts.join("$");
    id = id.replace(/^_/, "") || defaultName || "ref";

    return this.generateUidIdentifier(id.slice(0, 20));
  };

  Scope.prototype.isStatic = function isStatic(node) {
    if (t.isThisExpression(node) || t.isSuper(node)) {
      return true;
    }

    if (t.isIdentifier(node)) {
      var binding = this.getBinding(node.name);
      if (binding) {
        return binding.constant;
      } else {
        return this.hasBinding(node.name);
      }
    }

    return false;
  };

  Scope.prototype.maybeGenerateMemoised = function maybeGenerateMemoised(node, dontPush) {
    if (this.isStatic(node)) {
      return null;
    } else {
      var _id2 = this.generateUidIdentifierBasedOnNode(node);
      if (!dontPush) this.push({ id: _id2 });
      return _id2;
    }
  };

  Scope.prototype.checkBlockScopedCollisions = function checkBlockScopedCollisions(local, kind, name, id) {
    if (kind === "param") return;

    if (kind === "hoisted" && local.kind === "let") return;

    var duplicate = false;

    if (!duplicate) duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module";

    if (!duplicate) duplicate = local.kind === "param" && (kind === "let" || kind === "const");

    if (duplicate) {
      throw this.hub.file.buildCodeFrameError(id, messages.get("scopeDuplicateDeclaration", name), TypeError);
    }
  };

  Scope.prototype.rename = function rename(oldName, newName, block) {
    var binding = this.getBinding(oldName);
    if (binding) {
      newName = newName || this.generateUidIdentifier(oldName).name;
      return new _renamer2.default(binding, oldName, newName).rename(block);
    }
  };

  Scope.prototype._renameFromMap = function _renameFromMap(map, oldName, newName, value) {
    if (map[oldName]) {
      map[newName] = value;
      map[oldName] = null;
    }
  };

  Scope.prototype.dump = function dump() {
    var sep = (0, _repeat2.default)("-", 60);
    console.log(sep);
    var scope = this;
    do {
      console.log("#", scope.block.type);
      for (var name in scope.bindings) {
        var binding = scope.bindings[name];
        console.log(" -", name, {
          constant: binding.constant,
          references: binding.references,
          violations: binding.constantViolations.length,
          kind: binding.kind
        });
      }
    } while (scope = scope.parent);
    console.log(sep);
  };

  Scope.prototype.toArray = function toArray(node, i) {
    var file = this.hub.file;

    if (t.isIdentifier(node)) {
      var binding = this.getBinding(node.name);
      if (binding && binding.constant && binding.path.isGenericType("Array")) return node;
    }

    if (t.isArrayExpression(node)) {
      return node;
    }

    if (t.isIdentifier(node, { name: "arguments" })) {
      return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Array"), t.identifier("prototype")), t.identifier("slice")), t.identifier("call")), [node]);
    }

    var helperName = "toArray";
    var args = [node];
    if (i === true) {
      helperName = "toConsumableArray";
    } else if (i) {
      args.push(t.numericLiteral(i));
      helperName = "slicedToArray";
    }
    return t.callExpression(file.addHelper(helperName), args);
  };

  Scope.prototype.registerDeclaration = function registerDeclaration(path) {
    if (path.isLabeledStatement()) {
      this.registerBinding("label", path);
    } else if (path.isFunctionDeclaration()) {
      this.registerBinding("hoisted", path.get("id"), path);
    } else if (path.isVariableDeclaration()) {
      var declarations = path.get("declarations");
      for (var _iterator7 = declarations, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) {
        var _ref8;

        if (_isArray7) {
          if (_i7 >= _iterator7.length) break;
          _ref8 = _iterator7[_i7++];
        } else {
          _i7 = _iterator7.next();
          if (_i7.done) break;
          _ref8 = _i7.value;
        }

        var declar = _ref8;

        this.registerBinding(path.node.kind, declar);
      }
    } else if (path.isClassDeclaration()) {
      this.registerBinding("let", path);
    } else if (path.isImportDeclaration()) {
      var specifiers = path.get("specifiers");
      for (var _iterator8 = specifiers, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) {
        var _ref9;

        if (_isArray8) {
          if (_i8 >= _iterator8.length) break;
          _ref9 = _iterator8[_i8++];
        } else {
          _i8 = _iterator8.next();
          if (_i8.done) break;
          _ref9 = _i8.value;
        }

        var specifier = _ref9;

        this.registerBinding("module", specifier);
      }
    } else if (path.isExportDeclaration()) {
      var _declar = path.get("declaration");
      if (_declar.isClassDeclaration() || _declar.isFunctionDeclaration() || _declar.isVariableDeclaration()) {
        this.registerDeclaration(_declar);
      }
    } else {
      this.registerBinding("unknown", path);
    }
  };

  Scope.prototype.buildUndefinedNode = function buildUndefinedNode() {
    if (this.hasBinding("undefined")) {
      return t.unaryExpression("void", t.numericLiteral(0), true);
    } else {
      return t.identifier("undefined");
    }
  };

  Scope.prototype.registerConstantViolation = function registerConstantViolation(path) {
    var ids = path.getBindingIdentifiers();
    for (var name in ids) {
      var binding = this.getBinding(name);
      if (binding) binding.reassign(path);
    }
  };

  Scope.prototype.registerBinding = function registerBinding(kind, path) {
    var bindingPath = arguments.length <= 2 || arguments[2] === undefined ? path : arguments[2];

    if (!kind) throw new ReferenceError("no `kind`");

    if (path.isVariableDeclaration()) {
      var declarators = path.get("declarations");
      for (var _iterator9 = declarators, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) {
        var _ref10;

        if (_isArray9) {
          if (_i9 >= _iterator9.length) break;
          _ref10 = _iterator9[_i9++];
        } else {
          _i9 = _iterator9.next();
          if (_i9.done) break;
          _ref10 = _i9.value;
        }

        var declar = _ref10;

        this.registerBinding(kind, declar);
      }
      return;
    }

    var parent = this.getProgramParent();
    var ids = path.getBindingIdentifiers(true);

    for (var name in ids) {
      for (var _iterator10 = ids[name], _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) {
        var _ref11;

        if (_isArray10) {
          if (_i10 >= _iterator10.length) break;
          _ref11 = _iterator10[_i10++];
        } else {
          _i10 = _iterator10.next();
          if (_i10.done) break;
          _ref11 = _i10.value;
        }

        var _id3 = _ref11;

        var local = this.getOwnBinding(name);
        if (local) {
          if (local.identifier === _id3) continue;

          this.checkBlockScopedCollisions(local, kind, name, _id3);
        }

        if (local && local.path.isFlow()) local = null;

        parent.references[name] = true;

        this.bindings[name] = new _binding3.default({
          identifier: _id3,
          existing: local,
          scope: this,
          path: bindingPath,
          kind: kind
        });
      }
    }
  };

  Scope.prototype.addGlobal = function addGlobal(node) {
    this.globals[node.name] = node;
  };

  Scope.prototype.hasUid = function hasUid(name) {
    var scope = this;

    do {
      if (scope.uids[name]) return true;
    } while (scope = scope.parent);

    return false;
  };

  Scope.prototype.hasGlobal = function hasGlobal(name) {
    var scope = this;

    do {
      if (scope.globals[name]) return true;
    } while (scope = scope.parent);

    return false;
  };

  Scope.prototype.hasReference = function hasReference(name) {
    var scope = this;

    do {
      if (scope.references[name]) return true;
    } while (scope = scope.parent);

    return false;
  };

  Scope.prototype.isPure = function isPure(node, constantsOnly) {
    if (t.isIdentifier(node)) {
      var binding = this.getBinding(node.name);
      if (!binding) return false;
      if (constantsOnly) return binding.constant;
      return true;
    } else if (t.isClass(node)) {
      if (node.superClass && !this.isPure(node.superClass, constantsOnly)) return false;
      return this.isPure(node.body, constantsOnly);
    } else if (t.isClassBody(node)) {
      for (var _iterator11 = node.body, _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : (0, _getIterator3.default)(_iterator11);;) {
        var _ref12;

        if (_isArray11) {
          if (_i11 >= _iterator11.length) break;
          _ref12 = _iterator11[_i11++];
        } else {
          _i11 = _iterator11.next();
          if (_i11.done) break;
          _ref12 = _i11.value;
        }

        var method = _ref12;

        if (!this.isPure(method, constantsOnly)) return false;
      }
      return true;
    } else if (t.isBinary(node)) {
      return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly);
    } else if (t.isArrayExpression(node)) {
      for (var _iterator12 = node.elements, _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : (0, _getIterator3.default)(_iterator12);;) {
        var _ref13;

        if (_isArray12) {
          if (_i12 >= _iterator12.length) break;
          _ref13 = _iterator12[_i12++];
        } else {
          _i12 = _iterator12.next();
          if (_i12.done) break;
          _ref13 = _i12.value;
        }

        var elem = _ref13;

        if (!this.isPure(elem, constantsOnly)) return false;
      }
      return true;
    } else if (t.isObjectExpression(node)) {
      for (var _iterator13 = node.properties, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : (0, _getIterator3.default)(_iterator13);;) {
        var _ref14;

        if (_isArray13) {
          if (_i13 >= _iterator13.length) break;
          _ref14 = _iterator13[_i13++];
        } else {
          _i13 = _iterator13.next();
          if (_i13.done) break;
          _ref14 = _i13.value;
        }

        var prop = _ref14;

        if (!this.isPure(prop, constantsOnly)) return false;
      }
      return true;
    } else if (t.isClassMethod(node)) {
      if (node.computed && !this.isPure(node.key, constantsOnly)) return false;
      if (node.kind === "get" || node.kind === "set") return false;
      return true;
    } else if (t.isClassProperty(node) || t.isObjectProperty(node)) {
      if (node.computed && !this.isPure(node.key, constantsOnly)) return false;
      return this.isPure(node.value, constantsOnly);
    } else if (t.isUnaryExpression(node)) {
      return this.isPure(node.argument, constantsOnly);
    } else {
      return t.isPureish(node);
    }
  };

  Scope.prototype.setData = function setData(key, val) {
    return this.data[key] = val;
  };

  Scope.prototype.getData = function getData(key) {
    var scope = this;
    do {
      var data = scope.data[key];
      if (data != null) return data;
    } while (scope = scope.parent);
  };

  Scope.prototype.removeData = function removeData(key) {
    var scope = this;
    do {
      var data = scope.data[key];
      if (data != null) scope.data[key] = null;
    } while (scope = scope.parent);
  };

  Scope.prototype.init = function init() {
    if (!this.references) this.crawl();
  };

  Scope.prototype.crawl = function crawl() {
    _crawlCallsCount++;
    this._crawl();
    _crawlCallsCount--;
  };

  Scope.prototype._crawl = function _crawl() {
    var path = this.path;

    this.references = (0, _create2.default)(null);
    this.bindings = (0, _create2.default)(null);
    this.globals = (0, _create2.default)(null);
    this.uids = (0, _create2.default)(null);
    this.data = (0, _create2.default)(null);

    if (path.isLoop()) {
      for (var _iterator14 = t.FOR_INIT_KEYS, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : (0, _getIterator3.default)(_iterator14);;) {
        var _ref15;

        if (_isArray14) {
          if (_i14 >= _iterator14.length) break;
          _ref15 = _iterator14[_i14++];
        } else {
          _i14 = _iterator14.next();
          if (_i14.done) break;
          _ref15 = _i14.value;
        }

        var key = _ref15;

        var node = path.get(key);
        if (node.isBlockScoped()) this.registerBinding(node.node.kind, node);
      }
    }

    if (path.isFunctionExpression() && path.has("id")) {
      if (!path.get("id").node[t.NOT_LOCAL_BINDING]) {
        this.registerBinding("local", path.get("id"), path);
      }
    }

    if (path.isClassExpression() && path.has("id")) {
      if (!path.get("id").node[t.NOT_LOCAL_BINDING]) {
        this.registerBinding("local", path);
      }
    }

    if (path.isFunction()) {
      var params = path.get("params");
      for (var _iterator15 = params, _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : (0, _getIterator3.default)(_iterator15);;) {
        var _ref16;

        if (_isArray15) {
          if (_i15 >= _iterator15.length) break;
          _ref16 = _iterator15[_i15++];
        } else {
          _i15 = _iterator15.next();
          if (_i15.done) break;
          _ref16 = _i15.value;
        }

        var param = _ref16;

        this.registerBinding("param", param);
      }
    }

    if (path.isCatchClause()) {
      this.registerBinding("let", path);
    }

    var parent = this.getProgramParent();
    if (parent.crawling) return;

    var state = {
      references: [],
      constantViolations: [],
      assignments: []
    };

    this.crawling = true;
    path.traverse(collectorVisitor, state);
    this.crawling = false;

    for (var _iterator16 = state.assignments, _isArray16 = Array.isArray(_iterator16), _i16 = 0, _iterator16 = _isArray16 ? _iterator16 : (0, _getIterator3.default)(_iterator16);;) {
      var _ref17;

      if (_isArray16) {
        if (_i16 >= _iterator16.length) break;
        _ref17 = _iterator16[_i16++];
      } else {
        _i16 = _iterator16.next();
        if (_i16.done) break;
        _ref17 = _i16.value;
      }

      var _path = _ref17;

      var ids = _path.getBindingIdentifiers();
      var programParent = void 0;
      for (var name in ids) {
        if (_path.scope.getBinding(name)) continue;

        programParent = programParent || _path.scope.getProgramParent();
        programParent.addGlobal(ids[name]);
      }

      _path.scope.registerConstantViolation(_path);
    }

    for (var _iterator17 = state.references, _isArray17 = Array.isArray(_iterator17), _i17 = 0, _iterator17 = _isArray17 ? _iterator17 : (0, _getIterator3.default)(_iterator17);;) {
      var _ref18;

      if (_isArray17) {
        if (_i17 >= _iterator17.length) break;
        _ref18 = _iterator17[_i17++];
      } else {
        _i17 = _iterator17.next();
        if (_i17.done) break;
        _ref18 = _i17.value;
      }

      var ref = _ref18;

      var binding = ref.scope.getBinding(ref.node.name);
      if (binding) {
        binding.reference(ref);
      } else {
        ref.scope.getProgramParent().addGlobal(ref.node);
      }
    }

    for (var _iterator18 = state.constantViolations, _isArray18 = Array.isArray(_iterator18), _i18 = 0, _iterator18 = _isArray18 ? _iterator18 : (0, _getIterator3.default)(_iterator18);;) {
      var _ref19;

      if (_isArray18) {
        if (_i18 >= _iterator18.length) break;
        _ref19 = _iterator18[_i18++];
      } else {
        _i18 = _iterator18.next();
        if (_i18.done) break;
        _ref19 = _i18.value;
      }

      var _path2 = _ref19;

      _path2.scope.registerConstantViolation(_path2);
    }
  };

  Scope.prototype.push = function push(opts) {
    var path = this.path;

    if (!path.isBlockStatement() && !path.isProgram()) {
      path = this.getBlockParent().path;
    }

    if (path.isSwitchStatement()) {
      path = this.getFunctionParent().path;
    }

    if (path.isLoop() || path.isCatchClause() || path.isFunction()) {
      t.ensureBlock(path.node);
      path = path.get("body");
    }

    var unique = opts.unique;
    var kind = opts.kind || "var";
    var blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist;

    var dataKey = "declaration:" + kind + ":" + blockHoist;
    var declarPath = !unique && path.getData(dataKey);

    if (!declarPath) {
      var declar = t.variableDeclaration(kind, []);
      declar._generated = true;
      declar._blockHoist = blockHoist;

      var _path$unshiftContaine = path.unshiftContainer("body", [declar]);

      declarPath = _path$unshiftContaine[0];

      if (!unique) path.setData(dataKey, declarPath);
    }

    var declarator = t.variableDeclarator(opts.id, opts.init);
    declarPath.node.declarations.push(declarator);
    this.registerBinding(kind, declarPath.get("declarations").pop());
  };

  Scope.prototype.getProgramParent = function getProgramParent() {
    var scope = this;
    do {
      if (scope.path.isProgram()) {
        return scope;
      }
    } while (scope = scope.parent);
    throw new Error("We couldn't find a Function or Program...");
  };

  Scope.prototype.getFunctionParent = function getFunctionParent() {
    var scope = this;
    do {
      if (scope.path.isFunctionParent()) {
        return scope;
      }
    } while (scope = scope.parent);
    throw new Error("We couldn't find a Function or Program...");
  };

  Scope.prototype.getBlockParent = function getBlockParent() {
    var scope = this;
    do {
      if (scope.path.isBlockParent()) {
        return scope;
      }
    } while (scope = scope.parent);
    throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...");
  };

  Scope.prototype.getAllBindings = function getAllBindings() {
    var ids = (0, _create2.default)(null);

    var scope = this;
    do {
      (0, _defaults2.default)(ids, scope.bindings);
      scope = scope.parent;
    } while (scope);

    return ids;
  };

  Scope.prototype.getAllBindingsOfKind = function getAllBindingsOfKind() {
    var ids = (0, _create2.default)(null);

    for (var _iterator19 = arguments, _isArray19 = Array.isArray(_iterator19), _i19 = 0, _iterator19 = _isArray19 ? _iterator19 : (0, _getIterator3.default)(_iterator19);;) {
      var _ref20;

      if (_isArray19) {
        if (_i19 >= _iterator19.length) break;
        _ref20 = _iterator19[_i19++];
      } else {
        _i19 = _iterator19.next();
        if (_i19.done) break;
        _ref20 = _i19.value;
      }

      var kind = _ref20;

      var scope = this;
      do {
        for (var name in scope.bindings) {
          var binding = scope.bindings[name];
          if (binding.kind === kind) ids[name] = binding;
        }
        scope = scope.parent;
      } while (scope);
    }

    return ids;
  };

  Scope.prototype.bindingIdentifierEquals = function bindingIdentifierEquals(name, node) {
    return this.getBindingIdentifier(name) === node;
  };

  Scope.prototype.warnOnFlowBinding = function warnOnFlowBinding(binding) {
    if (_crawlCallsCount === 0 && binding && binding.path.isFlow()) {
      console.warn("\n        You or one of the Babel plugins you are using are using Flow declarations as bindings.\n        Support for this will be removed in version 6.8. To find out the caller, grep for this\n        message and change it to a `console.trace()`.\n      ");
    }
    return binding;
  };

  Scope.prototype.getBinding = function getBinding(name) {
    var scope = this;

    do {
      var binding = scope.getOwnBinding(name);
      if (binding) return this.warnOnFlowBinding(binding);
    } while (scope = scope.parent);
  };

  Scope.prototype.getOwnBinding = function getOwnBinding(name) {
    return this.warnOnFlowBinding(this.bindings[name]);
  };

  Scope.prototype.getBindingIdentifier = function getBindingIdentifier(name) {
    var info = this.getBinding(name);
    return info && info.identifier;
  };

  Scope.prototype.getOwnBindingIdentifier = function getOwnBindingIdentifier(name) {
    var binding = this.bindings[name];
    return binding && binding.identifier;
  };

  Scope.prototype.hasOwnBinding = function hasOwnBinding(name) {
    return !!this.getOwnBinding(name);
  };

  Scope.prototype.hasBinding = function hasBinding(name, noGlobals) {
    if (!name) return false;
    if (this.hasOwnBinding(name)) return true;
    if (this.parentHasBinding(name, noGlobals)) return true;
    if (this.hasUid(name)) return true;
    if (!noGlobals && (0, _includes2.default)(Scope.globals, name)) return true;
    if (!noGlobals && (0, _includes2.default)(Scope.contextVariables, name)) return true;
    return false;
  };

  Scope.prototype.parentHasBinding = function parentHasBinding(name, noGlobals) {
    return this.parent && this.parent.hasBinding(name, noGlobals);
  };

  Scope.prototype.moveBindingTo = function moveBindingTo(name, scope) {
    var info = this.getBinding(name);
    if (info) {
      info.scope.removeOwnBinding(name);
      info.scope = scope;
      scope.bindings[name] = info;
    }
  };

  Scope.prototype.removeOwnBinding = function removeOwnBinding(name) {
    delete this.bindings[name];
  };

  Scope.prototype.removeBinding = function removeBinding(name) {
    var info = this.getBinding(name);
    if (info) {
      info.scope.removeOwnBinding(name);
    }

    var scope = this;
    do {
      if (scope.uids[name]) {
        scope.uids[name] = false;
      }
    } while (scope = scope.parent);
  };

  return Scope;
}();

Scope.globals = (0, _keys2.default)(_globals2.default.builtin);
Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"];
exports.default = Scope;
module.exports = exports["default"];


text:
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++

/* global Clipboard, anchors */

(function ($) {
  'use strict'

  $(function () {

    // Tooltip and popover demos
    $('.tooltip-demo').tooltip({
      selector: '[data-toggle="tooltip"]',
      container: 'body'
    })

    $('[data-toggle="popover"]').popover()

    // Demos within modals
    $('.tooltip-test').tooltip()
    $('.popover-test').popover()

    // Indeterminate checkbox example
    $('.bd-example-indeterminate [type="checkbox"]').prop('indeterminate', true)

    // Disable empty links in docs examples
    $('.bd-content [href="#"]').click(function (e) {
      e.preventDefault()
    })

    // Modal relatedTarget demo
    $('#exampleModal').on('show.bs.modal', function (event) {
      var $button = $(event.relatedTarget)      // Button that triggered the modal
      var recipient = $button.data('whatever')  // Extract info from data-* attributes
      // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
      // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
      var $modal = $(this)
      $modal.find('.modal-title').text('New message to ' + recipient)
      $modal.find('.modal-body input').val(recipient)
    })

    // Activate animated progress bar
    $('.bd-toggle-animated-progress').on('click', function () {
      $(this).siblings('.progress').find('.progress-bar-striped').toggleClass('progress-bar-animated')
    })

    // Insert copy to clipboard button before .highlight
    $('.highlight').each(function () {
      var btnHtml = '
<button class="btn-clipboard" title="Copy to clipboard">Copy</button>
'
      $(this).before(btnHtml)
      $('.btn-clipboard')
        .tooltip()
        .on('mouseleave', function () {
          // explicitly hide tooltip, since after clicking it remains
          // focused (as it's a button), so tooltip would otherwise
          // remain visible until focus is moved away
          $(this).tooltip('hide')
        })
    })

    var clipboard = new Clipboard('.btn-clipboard', {
      target: function (trigger) {
        return trigger.parentNode.nextElementSibling
      }
    })

    clipboard.on('success', function (e) {
      $(e.trigger)
        .attr('title', 'Copied!')
        .tooltip('_fixTitle')
        .tooltip('show')
        .attr('title', 'Copy to clipboard')
        .tooltip('_fixTitle')

      e.clearSelection()
    })

    clipboard.on('error', function (e) {
      var modifierKey = /Mac/i.test(navigator.userAgent) ? '\u2318' : 'Ctrl-'
      var fallbackMsg = 'Press ' + modifierKey + 'C to copy'

      $(e.trigger)
        .attr('title', fallbackMsg)
        .tooltip('_fixTitle')
        .tooltip('show')
        .attr('title', 'Copy to clipboard')
        .tooltip('_fixTitle')
    })

  })

}(jQuery))

;(function () {
  'use strict'

  anchors.options = {
    icon: '#'
  }
  anchors.add('.bd-content > h2, .bd-content > h3, .bd-content > h4, .bd-content > h5')
}())

redpajama_set_name: RedPajamaGithub


text:
package org.apache.cassandra.db;

import java.nio.ByteBuffer;
import java.io.IOException;
import java.util.Collection;

public interface IMutation
{
    public String getTable();
    public Collection<Integer> getColumnFamilyIds();
    public ByteBuffer key();
    public void apply() throws IOException;
    public String toString(boolean shallow);
}


text:
require 'spec_helper'

module Challah
  describe "Routes" do
    describe "GET /sign-in" do
      it "routes properly" do
        expect(:get => "/sign-in").to route_to("sessions#new")
      end
    end

    describe "POST /sign-in" do
      it "routes properly" do
        expect(:post => "/sign-in").to route_to("sessions#create")
      end
    end

    describe "GET /sign-out" do
      it "routes properly" do
        expect(:get => "/sign-out").to route_to("sessions#destroy")
      end
    end
  end
end


text:
namespace engine {

ExplodeOnHitSystem::ExplodeOnHitSystem()
    : mScene( Scene::Get() )
{
}

void ExplodeOnHitSystem::Init()
{
    SystemSuppressor::Get().Add( SystemSuppressor::SceneLoad, GetType_static() );

    mScene.AddValidator( GetType_static(), []( Actor const& actor )->bool {
        return actor.Get<IExplodeOnHitComponent>().IsValid(); } );
}

void ExplodeOnHitSystem::Update( double DeltaTime )
{
    for( auto actor : mScene.GetActorsFromMap( GetType_static() ) )
    {
        Opt<IExplodeOnHitComponent> explodeOnHitC = actor->Get<IExplodeOnHitComponent>();
        if ( !explodeOnHitC.IsValid() || !explodeOnHitC->IsExploded() )
        {
            continue;
        }
        WeaponItemSubSystem::Projectiles_t projectiles;
        ExplodeOnDeathSystem::FillExplosionProjectiles( *explodeOnHitC.Get(), *actor, projectiles );
        Scatter scatter;
        WeaponItemSubSystem::Get()->AddProjectiles( *actor, projectiles, scatter );
        Opt<IHealthComponent> healthC = actor->Get<IHealthComponent>();
        if( healthC.IsValid() )
        {
            healthC->SetHP( 0 );
        }
    }
}

} // namespace engine


text:
ALPHA_VALUES=(0.1 0.5 1)
EPOCH_VALUES=(4)
NVERT_VALUES=(1000 5000 10000 20000 50000 100000 200000 500000 1000000)
CACHE_VALUES=(1000)

function run() {
# $1 is alpha, $2 is epoch, $3 is num_vertices, $4 is cache size
    echo "==========START EXPERIMENT==========" >> output.log
    # Output git commit number
    git rev-parse HEAD >> output.log

    # Replace parameters in h file
    cp -f benchmark/benchmarks/query_creator.h benchmark/benchmarks/query_creator_tmp.h
    for param in ALPHA NUM_VERTICES CACHE_SIZE
    do
        sed -i ".bak" "s/^#define $param .*$//g" benchmark/benchmarks/query_creator.h
    done

    cp -f benchmark/benchmarks/query_simulator.h benchmark/benchmarks/query_simulator_tmp.h
    for param in PARAM_ALPHA PARAM_EPOCH_THRESHOLD PARAM_NUM_VERTICES PARAM_CACHE_SIZE
    do
        sed -i ".bak" "s/^#define $param .*$//g" benchmark/benchmarks/query_simulator.h
    done

    sed -i ".bak" "s/ALPHA/$1/g" benchmark/benchmarks/query_creator.h
    sed -i ".bak" "s/NUM_VERTICES/$3/g" benchmark/benchmarks/query_creator.h
    sed -i ".bak" "s/CACHE_SIZE/$4/g" benchmark/benchmarks/query_creator.h

    sed -i ".bak" "s/PARAM_ALPHA/$1/g" benchmark/benchmarks/query_simulator.h
    sed -i ".bak" "s/PARAM_EPOCH_THRESHOLD/$2/g" benchmark/benchmarks/query_simulator.h
    sed -i ".bak" "s/PARAM_NUM_VERTICES/$3/g" benchmark/benchmarks/query_simulator.h
    sed -i ".bak" "s/PARAM_CACHE_SIZE/$4/g" benchmark/benchmarks/query_simulator.h

    make benchmark-persistent benchmark-persistent-madvise

    echo "PARAM_ALPHA=$1,PARAM_EPOCH_THRESHOLD=$2,PARAM_NUM_VERTICES=$3,PARAM_CACHE_SIZE=$4" >> output.log

    for m in {1..5}
    do
        ./bin/benchmark-persistent --run query_creator -d bin/db/

        echo "NO_MADVISE" >> output.log
            echo "TRIAL $m" >> output.log
            echo "==========BEFORE VM STAT==========" >> output.log
        sudo purge
            vm_stat >> output.log
            echo "==========LLAMA OUTPUT==========" >> output.log
            ./bin/benchmark-persistent --run query_simulator -d bin/db/ >> output.log
            echo "==========AFTER VM STAT==========" >> output.log
            vm_stat >> output.log
            echo "==========END LLAMA OUTPUT==========" >> output.log

        echo "WITH_MADVISE" >> output.log
            echo "TRIAL $m" >> output.log
            echo "==========BEFORE VM STAT==========" >> output.log
        sudo purge
            vm_stat >> output.log
            echo "==========LLAMA OUTPUT==========" >> output.log
            ./bin/benchmark-persistent-madvise --run query_simulator -d bin/db/ >> output.log
            echo "==========AFTER VM STAT==========" >> output.log
            vm_stat >> output.log
            echo "==========END LLAMA OUTPUT==========" >> output.log
    done

    cp -f benchmark/benchmarks/query_creator_tmp.h benchmark/benchmarks/query_creator.h
    rm -f benchmark/benchmarks/query_creator_tmp.h

    cp -f benchmark/benchmarks/query_simulator_tmp.h benchmark/benchmarks/query_simulator.h
    rm -f benchmark/benchmarks/query_simulator_tmp.h

    rm temp.txt
}

for i in ${ALPHA_VALUES[@]}
do
    for j in ${EPOCH_VALUES[@]}
    do
        for k in ${NVERT_VALUES[@]}
        do
            for l in ${CACHE_VALUES[@]}
            do
                run $i $j $k $l
            done
        done
    done
done


text:
package com.uncos.wechatboot.utils;

import java.util.Random;
import java.util.UUID;

/**
 * 随机字符串生成器
 */
public class RandomStringGenerator {

    private static final int defaultLength = 32;
    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789";

    /**
     * 获取一定长度的随机字符串
     *
     * @param length 指定字符串长度
     * @return 一定长度的字符串
     */
    public static String generate(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获取默认长度的随机字符串
     *
     * @return 默认长度的字符串
     */
    public static String generate() {
        return generate(defaultLength);
    }

    /**
     * 生成uuid
     *
     * @return 36位字符串
     */
    public static String uuid() {
        return UUID.randomUUID().toString();
    }

    /**
     * 生成uuid(去除连接线)
     *
     * @return 32位字符串
     */
    public static String uuidWithoutSymbol() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

}


text:
import abc

from os_win import utilsfactory

import nova.conf

CONF = nova.conf.CONF

class HyperVBaseVIFDriver(object):
    @abc.abstractmethod
    def plug(self, instance, vif):
        pass

    @abc.abstractmethod
    def unplug(self, instance, vif):
        pass

class HyperVNeutronVIFDriver(HyperVBaseVIFDriver):
    """Neutron VIF driver."""

    def plug(self, instance, vif):
        # Neutron takes care of plugging the port
        pass

    def unplug(self, instance, vif):
        # Neutron takes care of unplugging the port
        pass

class HyperVNovaNetworkVIFDriver(HyperVBaseVIFDriver):
    """Nova network VIF driver."""

    def __init__(self):
        self._netutils = utilsfactory.get_networkutils()

    def plug(self, instance, vif):
        self._netutils.connect_vnic_to_vswitch(CONF.hyperv.vswitch_name,
                                               vif['id'])

    def unplug(self, instance, vif):
        # TODO(alepilotti) Not implemented
        pass


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// 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.
package com.google.devtools.build.android;

import com.google.devtools.build.android.xml.Namespaces;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;

/**
 * An {@link XmlResourceValue} is extracted from xml files in the resource 'values' directory.
 */
public interface XmlResourceValue {
  /**
   * Each XmlValue is expected to write a valid representation in xml to the writer.
   *
   * @param key The FullyQualified name for the xml resource being written.
   * @param source The source of the value to allow for proper comment annotation.
   * @param mergedDataWriter The target writer.
   */
  void write(FullyQualifiedName key, Path source, AndroidDataWritingVisitor mergedDataWriter);

  /** Serializes the resource value to the OutputStream and returns the bytes written. */
  int serializeTo(Path source, Namespaces namespaces, OutputStream out) throws IOException;

  /**
   * Combines these xml values together and returns a single value.
   *
   * @param value Another resource to be combined with this one.
   * @return A union of the values of these two values.
   * @throws IllegalArgumentException if either value cannot combine with the other.
   */
  XmlResourceValue combineWith(XmlResourceValue value);
}


text:
#import "AddProgressionEventFunction.h"
#import <AIRExtHelpers/MPFREObjectUtils.h>
#import "GameAnalytics.h"

GAProgressionStatus ga_getProgressionStatus( int status ) {
    if( status == 2 ) {
        return GAProgressionStatusComplete;
    } else if( status == 1 ) {
        return GAProgressionStatusStart;
    }
    return GAProgressionStatusFail;
}

FREObject ga_addProgressionEvent( FREContext context, void* functionData, uint32_t argc, FREObject argv[] ) {
    GAProgressionStatus status = ga_getProgressionStatus( [MPFREObjectUtils getInt:argv[0]] );
    NSString* progression01 = [MPFREObjectUtils getNSString:argv[1]];
    NSString* progression02 = (argv[2] == nil) ? nil : [MPFREObjectUtils getNSString:argv[2]];
    NSString* progression03 = (argv[3] == nil) ? nil : [MPFREObjectUtils getNSString:argv[3]];
    int score = [MPFREObjectUtils getInt:argv[4]];

    /* Do not track score if the value is lte to zero */
    if( score <= 0 ) {
        [GameAnalytics addProgressionEventWithProgressionStatus:status progression01:progression01 progression02:progression02 progression03:progression03];
    } else {
        [GameAnalytics addProgressionEventWithProgressionStatus:status progression01:progression01 progression02:progression02 progression03:progression03 score:score];
    }

    return nil;
}


text:
from xml.etree import ElementTree as Etree
from xml.dom import minidom
from elavonvtpv.enum import RequestType
from elavonvtpv.Response import Response
import datetime
import hashlib
import requests

class Request:
    def __init__(self, secret, request_type, merchant_id, order_id, currency=None, amount=None, card=None,
                 tss_info=None, settle=True, account=None, channel=None, comment1=None, comment2=None,
                 past_reference=None, authorization_code=None, refund_hash=None, pares=None, mpi=None):
        """
        Defines a Request object
        :param secret: the shared secret between Elavon and your account
        :param request_type: RequestType enum object containing the type of the request to be sent to Elavon
        :param merchant_id: the credentials of the elavon merchant account
        :param order_id: number unique to the request for all accounts associated with the merchant
        :param currency: Currency enum object containing the code of the currency to be use in the transaction
        :param amount: amount of currency to be charged, in the smallest unit of currency possible
        :param card: CreditCard object containing the data pertaining to the customer's credit card
        :param tss_info: TssInfo object containing the data pertaining to the anti-fraud system
        :param settle: flag indicating if the transaction must be settled automatically by Elavon
        :param account: the sub-account to be used for the request
        :param channel: Channel enum object indicating the channel by which the transaction is made
        :param comment1: optional comment to include in the request
        :param comment2: optional comment to include in the request
        :param past_reference: reference of the transaction to which this one refers
        :param authorization_code: authorization code given with the transaction to which this one refers
        :param refund_hash: hash provided by Elavon, needed to make refunds
        :param pares: authorization code given with the transaction to which this one refers
        :param mpi: hash provided by Elavon, needed to make refunds
        """
        self.timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        self.secret = secret
        self.request_type = request_type
        self.merchant_id = merchant_id
        self.order_id = order_id
        self.currency = currency
        self.amount = amount
        self.card = card
        self.tss_info = tss_info
        self.settle = settle
        self.account = account
        self.channel = channel
        self.comment1 = comment1
        self.comment2 = comment2
        self.past_reference = past_reference
        self.authorization_code = authorization_code
        self.refund_hash = refund_hash
        self.pares = pares
        self.mpi = mpi

    def __hash(self):
        """
        Builds the request hash from the data contained within
        :return: the hash string that will latter be cyphered
        """
        res = "%s.%s.%s.%s.%s." % (str(self.timestamp), str(self.merchant_id), str(self.order_id), str(self.amount),
                                  str(self.currency.value))
        if self.card:
            res += "%s" % str(self.card.number)

        return res.encode('utf-8')

    def sha1_hash(self):
        """
        returns a secure hash in SHA-1 for this request
        :return: secure hash in SHA-1
        """
        sha1_hash = hashlib.sha1(self.__hash()).hexdigest()
        sha1_hash += ".%s" % self.secret

        return hashlib.sha1(sha1_hash.encode('utf-8')).hexdigest()
        # return hashlib.sha1(self.__hash()).hexdigest()

    def md5_hash(self):
        """
        returns a secure hash in MD5 for this request
        :return: secure hash in MD5
        """
        md5_hash = hashlib.md5(self.__hash()).hexdigest()
        md5_hash += ".%s" % self.secret

        return hashlib.md5(md5_hash.encode('utf-8')).digest()

    def __basic_to_etree_element(self):
        """
        creates the basic structure of an Elavon request
        :return: the basic root element of the request containing those fields that exist en every request type
        """
        if self.request_type == RequestType.verify_enrolled:
            request_type = '3ds-verifyenrolled'
        elif self.request_type == RequestType.verify_sig:
            request_type = '3ds-verifysig'
        else:
            request_type = self.request_type.name

        request = Etree.Element('request')
        request.set('timestamp', self.timestamp)
        request.set('type', request_type)

        merchant_id = Etree.SubElement(request, 'merchantid')
        merchant_id.text = self.merchant_id

        if self.account:
            account = Etree.SubElement(request, 'account')
            account.text = self.account

        order_id = Etree.SubElement(request, 'orderid')
        order_id.text = self.order_id

        return request

    def __channel_to_etree_element(self):

        channel = Etree.Element('channel')
        channel.text = self.channel.value

        return channel

    def __past_reference_to_etree_element(self):

        past_reference = Etree.Element('pasref')
        past_reference.text = self.past_reference

        return past_reference

    def __pares_to_etree_element(self):

        pares = Etree.Element('pares')
        pares.text = self.pares

        return pares

    def __authorization_code_to_etree_element(self):

        authorization_code = Etree.Element('authcode')
        authorization_code.text = self.authorization_code

        return authorization_code

    def __amount_to_etree_element(self):

        amount = Etree.Element('amount')
        amount.set('currency', self.currency.value)
        amount.text = self.amount

        return amount

    def __auto_settle_to_etree_element(self):

        auto_settle = Etree.Element('autosettle')
        auto_settle.set('flag', '1' if self.settle else '0')

        return auto_settle

    def __comments_to_etree_element(self):
        comments = Etree.Element('comments')

        if self.comment1:
            comment1 = Etree.SubElement(comments, 'comment', id='1')
            comment1.text = self.comment1
        if self.comment2:
            comment2 = Etree.SubElement(comments, 'comment', id='2')
            comment2.text = self.comment2

        return comments

    def __refund_hash_to_etree_element(self):

        refundhash = Etree.Element('refundhash')
        refundhash.text = hashlib.sha1(self.refund_hash.encode('utf-8')).hexdigest()

        return refundhash

    def __sh1_hash_to_etree_element(self):

        sha1_hash = Etree.Element('sha1hash')
        sha1_hash.text = self.sha1_hash()

        return sha1_hash

    def __md5_hash_to_etree_element(self):

        md5_hash = Etree.Element('md5hash')
        md5_hash.text = self.md5_hash()

        return md5_hash

    def __auth_to_etree(self):
        request = self.__basic_to_etree_element()
        if not self.mpi:
            request.append(self.__channel_to_etree_element())
        request.append(self.__amount_to_etree_element())
        request.append(self.card.to_etree_element())
        if self.mpi:
            request.append(self.mpi.to_etree_element())
        request.append(self.__auto_settle_to_etree_element())
        if self.comment1 or self.comment2:
            request.append(self.__comments_to_etree_element())
        if self.tss_info:
            request.append(self.tss_info.to_etree_element())
        request.append(self.__sh1_hash_to_etree_element())
        # request.append(self.__md5_hash_to_etree_element())

        return Etree.ElementTree(request)

    def __manual_to_etree(self):
        request = self.__basic_to_etree_element()
        request.append(self.__channel_to_etree_element())
        request.append(self.__authorization_code_to_etree_element())
        request.append(self.__amount_to_etree_element())
        request.append(self.card.to_etree_element())
        request.append(self.__auto_settle_to_etree_element())
        if self.comment1 or self.comment2:
            request.append(self.__comments_to_etree_element())
        if self.tss_info:
            request.append(self.tss_info.to_etree_element())
        request.append(self.__sh1_hash_to_etree_element())
        # request.append(self.__md5_hash_to_etree_element())

        return Etree.ElementTree(request)

    def __obt_to_etree(self):
        request = self.__basic_to_etree_element()
        request.append(self.card.to_etree_element())
        request.append(self.__auto_settle_to_etree_element())
        request.append(self.__sh1_hash_to_etree_element())
        # request.append(self.__md5_hash_to_etree_element())

        return Etree.ElementTree(request)

    def __offline_to_etree(self):
        request = self.__basic_to_etree_element()
        request.append(self.__past_reference_to_etree_element())
        request.append(self.__authorization_code_to_etree_element())
        request.append(self.__amount_to_etree_element())
        request.append(self.card.to_etree_element())
        request.append(self.__auto_settle_to_etree_element())
        if self.comment1 or self.comment2:
            request.append(self.__comments_to_etree_element())
        if self.tss_info:
            request.append(self.tss_info.to_etree_element())
        request.append(self.__sh1_hash_to_etree_element())
        # request.append(self.__md5_hash_to_etree_element())

        return Etree.ElementTree(request)

    def __rebate_to_etree(self):
        request = self.__basic_to_etree_element()
        request.append(self.__past_reference_to_etree_element())
        request.append(self.__authorization_code_to_etree_element())
        request.append(self.__amount_to_etree_element())
        request.append(self.__auto_settle_to_etree_element())
        if self.comment1 or self.comment2:
            request.append(self.__comments_to_etree_element())
        request.append(self.__sh1_hash_to_etree_element())
        request.append(self.__refund_hash_to_etree_element())

        return Etree.ElementTree(request)

    def __void_to_etree(self):
        request = self.__basic_to_etree_element()
        request.append(self.__past_reference_to_etree_element())
        request.append(self.card.to_etree_element())
        request.append(self.__authorization_code_to_etree_element())
        if self.comment1 or self.comment2:
            request.append(self.__comments_to_etree_element())
        request.append(self.__sh1_hash_to_etree_element())
        # request.append(self.__md5_hash_to_etree_element())

        return Etree.ElementTree(request)

    def __tss_to_etree(self):
        request = self.__basic_to_etree_element()
        request.append(self.__amount_to_etree_element())
        request.append(self.card.to_etree_element())
        request.append(self.__auto_settle_to_etree_element())
        if self.comment1 or self.comment2:
            request.append(self.__comments_to_etree_element())
        if self.tss_info:
            request.append(self.tss_info.to_etree_element())
        request.append(self.__sh1_hash_to_etree_element())
        # request.append(self.__md5_hash_to_etree_element())

        return Etree.ElementTree(request)

    def __settle_to_etree(self):
        request = self.__basic_to_etree_element()
        request.append(self.__past_reference_to_etree_element())
        if self.amount and self.currency:
            request.append(self.__amount_to_etree_element())
        request.append(self.__authorization_code_to_etree_element())
        if self.comment1 or self.comment2:
            request.append(self.__comments_to_etree_element())
        request.append(self.__sh1_hash_to_etree_element())
        # request.append(self.__md5_hash_to_etree_element())

        return Etree.ElementTree(request)

    def __verify_enrolled_to_etree(self):
        request = self.__basic_to_etree_element()
        if self.amount and self.currency:
            request.append(self.__amount_to_etree_element())
        request.append(self.card.to_etree_element())
        request.append(self.__sh1_hash_to_etree_element())

        return Etree.ElementTree(request)

    def __verify_sig_to_etree(self):
        request = self.__basic_to_etree_element()
        if self.amount and self.currency:
            request.append(self.__amount_to_etree_element())
        request.append(self.card.to_etree_element())
        request.append(self.__pares_to_etree_element())
        request.append(self.__sh1_hash_to_etree_element())

        return Etree.ElementTree(request)

    def __to_etree(self):
        if self.request_type is RequestType.auth:
            return self.__auth_to_etree()
        elif self.request_type is RequestType.manual:
            return self.__manual_to_etree()
        elif self.request_type is RequestType.obt:
            return self.__obt_to_etree()
        elif self.request_type is RequestType.offline:
            return self.__offline_to_etree()
        elif self.request_type is RequestType.rebate:
            return self.__rebate_to_etree()
        elif self.request_type is RequestType.void:
            return self.__void_to_etree()
        elif self.request_type is RequestType.TSS:
            return self.__tss_to_etree()
        elif self.request_type is RequestType.settle:
            return self.__settle_to_etree()
        elif self.request_type is RequestType.verify_enrolled:
            return self.__verify_enrolled_to_etree()
        elif self.request_type is RequestType.verify_sig:
            return self.__verify_sig_to_etree()

    def to_xml_string(self):
        binary = Etree.tostring(self.__to_etree().getroot(), encoding='utf8', method='xml')
        return binary.decode('utf-8')

    def to_pretty_xml(self):
        return minidom.parseString(self.to_xml_string()).toprettyxml()

    def send(self, url):
        headers = {'Content-Type': 'application/xml'}
        response = requests.post(url=url, data=self.to_pretty_xml(), headers=headers)
        return Response(response.content)


text:
@interface PPLNotificationCenter : NSObject

+ (PPLNotificationCenter *)sharedClient;
- (void)registerNotificationPermission;
- (BOOL)checkIfRegistionSuccessful;

- (void)clearAllNotifications;
- (void)addNewNotificationAfterVote;

@end


text:
require 'spec_helper'
require 'ffi/disarm/types'

describe FFI::Disarm do
  let(:registers) { FFI::Disarm.enum_type(:da_reg_t) }

  describe "SP" do
    subject { FFI::Disarm::SP }

    it "should equal r13" do
      subject.should == registers[:r13]
    end
  end

  describe "LR" do
    subject { FFI::Disarm::LR }

    it "should equal r14" do
      subject.should == registers[:r14]
    end
  end

  describe "PC" do
    subject { FFI::Disarm::PC }

    it "should equal r15" do
      subject.should == registers[:r15]
    end
  end
end


text:
> Example Interpreter Configuration

```yaml
routers:
- ...
  interpreter:
    kind: io.l5d.namerd
    dst: /$/inet/1.2.3.4/4180
```

An interpreter determines how names are resolved.

<aside class="notice">
These parameters are available to the identifier regardless of kind. Identifiers may also have kind-specific parameters.
</aside>

Key | Default Value | Description
--- | ------------- | -----------
kind | `default` | Either [`default`](#default), [`io.l5d.namerd`](#namerd), or [`io.l5d.fs`](#file-system).
transformers | No transformers | A list of [transformers](#transformer) to apply to the resolved addresses.

## Default

kind: `default`

The default interpreter resolves names via the configured
[`namers`](#namers), with a fallback to the default Finagle
`Namer.Global` that handles paths of the form `/$/`.

## namerd

kind: `io.l5d.namerd`
kind: `io.l5d.namerd.http`

The namerd interpreter offloads the responsibilities of name resolution to the
namerd service.  Any namers configured in this linkerd are not used.  The
`io.l5d.namerd` interpreter uses namerd's long-poll thrift interface and the
`io.l5d.namerd.http` interpreter uses namerd's HTTP streaming interface.  Note
that the protocol that the interpreter uses to talk to namerd is unrelated to
the protocols of linkerd's routers.

Key | Default Value | Description
--- | ------------- | -----------
experimental | _required_ | Because the http version is still considered experimental, you must set this to `true` to use it.
dst | _required_ | A Finagle path locating the namerd service.
namespace | `default` | The name of the namerd dtab to use.
retry | see [namerd retry](#namerd-retry) | An object configuring retry backoffs for requests to namerd.
tls | no tls | Requests to namerd will be made using TLS if this parameter is provided.  It must be a [namerd client TLS](#namerd-client-tls) object.

### namerd retry

Key | Default Value | Description
--- | ------------- | -----------
baseSeconds | 5 seconds | The base number of seconds to wait before retrying.
maxSeconds | 10 minutes | The maximum number of seconds to wait before retrying.

### namerd client tls

Key | Default Value | Description
--- | ------------- | -----------
commonName | _required_ | The common name to use for namerd requests.
caCert | N/A | The path to the CA cert used for common name validation.

## File-System

kind: `io.l5d.fs`

The file-system interpreter resolves names via the configured
[`namers`](#namers), just like the default interpreter, but also uses
a dtab read from a file on the local file-system.  The specified file is watched
for changes so that the dtab may be edited live.

Key | Default Value | Description
--- | ------------- | -----------
dtabFile | _required_ | The file-system path to a file containing a dtab.


text:
layout: default
title: Новости
---

  {% for post in paginator.posts %}

        {{ post.title }}

    {{ post.date | date_to_string }}

    {{ post.content }}

  {% endfor %}

  {% if paginator.next_page %}
    Старее
  {% else %}
    Старее
  {% endif %}
  {% if paginator.previous_page %}
    {% if paginator.page == 2 %}
      Новее
    {% else %}
      Новее
    {% endif %}
  {% else %}
    Новее
  {% endif %}


text:
require 'spec_helper'

describe "books/new" do
  before(:each) do
    assign(:book, stub_model(Book,
      :title => "MyString",
      :author => "MyString"
    ).as_new_record)
  end

  it "renders new book form" do
    render

    # Run the generator again with the --webrat flag if you want to use webrat matchers
    assert_select "form[action=?][method=?]", books_path, "post" do
      assert_select "input#book_title[name=?]", "book[title]"
      assert_select "input#book_author[name=?]", "book[author]"
    end
  end
end


text:
from __future__ import absolute_import
__author__ = 'katharine'

from gevent import monkey
monkey.patch_all()

import collections
import zipfile
from uuid import UUID
import gevent
import json
import logging
import os
import os.path
import shutil
import urlparse
import urllib

from libpebble2.util.bundle import PebbleBundle
from libpebble2.services.appmessage import AppMessageService
import pypkjs.javascript as javascript
import pypkjs.javascript.runtime
from .pebble_manager import PebbleManager
from pypkjs.timeline import PebbleTimeline
from pypkjs.timeline.urls import URLManager

class Runner(object):
    PBW = collections.namedtuple('PBW', ('uuid', 'src', 'manifest', 'layouts', 'prefixes'))

    def __init__(self, qemu, pbws, persist_dir=None, oauth_token=None, layout_file=None, block_private_addresses=False):
        self.qemu = qemu
        self.pebble = PebbleManager(qemu)
        self.persist_dir = persist_dir
        self.oauth_token = oauth_token
        self.pebble.handle_start = self.handle_start
        self.pebble.handle_stop = self.handle_stop
        # PBL-26034: Due to PBL-24009 we must be sure to respond to appmessages received with no JS running.
        # However, libpebble2 presently provides no way of NACKing. Making sure this exists is sufficient for
        # ACKs, so we just create it and pass it off. We should add NACKs later, though.
        self.appmessage = AppMessageService(self.pebble.pebble)
        self.pbws = {}
        self.logger = logging.getLogger("pypkjs")
        self.running_uuid = None
        self.js = None
        self.urls = URLManager()
        self.timeline = PebbleTimeline(self, persist=persist_dir, oauth=oauth_token, layout_file=layout_file)
        self.block_private_addresses = block_private_addresses
        self.load_cached_pbws()
        self.load_pbws(pbws)

    def load_pbws(self, pbws, start=False, cache=False):
        for pbw_path in pbws:
            with zipfile.ZipFile(pbw_path) as z:
                appinfo = z.open('appinfo.json').read()
                try:
                    z.getinfo('pebble-js-app.js')
                except KeyError:
                    src = None
                else:
                    src = z.open('pebble-js-app.js').read().decode('utf-8')
                layouts = {}
                prefixes = [path[:-len(PebbleBundle.MANIFEST_FILENAME)] for path in z.namelist()
                            if PebbleBundle.MANIFEST_FILENAME in path]
                layout_platforms = [os.path.dirname(path) for path in z.namelist() if 'layouts.json' in path]
                for platform in layout_platforms:
                    try:
                        layouts[platform] = json.load(z.open('%s/layouts.json' % platform))
                    except (KeyError, ValueError):
                        layouts[platform] = {}
            manifest = json.loads(appinfo)
            uuid = UUID(manifest['uuid'])
            if cache and self._pbw_cache_dir is not None:
                shutil.copy(pbw_path, os.path.join(self._pbw_cache_dir, '%s.pbw' % uuid))
            self.pbws[uuid] = self.PBW(uuid, src, manifest, layouts, prefixes)
            if start:
                self.start_js(self.pbws[uuid])
        self.logger.info("Ready. Loaded apps: %s", ', '.join(map(str, self.pbws.keys())))

    def load_cached_pbws(self):
        cache_dir = self._pbw_cache_dir
        if cache_dir is not None:
            self.load_pbws([os.path.join(cache_dir, x) for x in os.listdir(cache_dir)])

    def handle_start(self, uuid):
        self.logger.info("Starting %s", uuid)
        if uuid in self.pbws:
            self.logger.info("starting js for %s", uuid)
            self.start_js(self.pbws[uuid])

    def handle_stop(self, uuid):
        if uuid == self.running_uuid:
            self.logger.info("stopping js")
            self.stop_js()

    def start_js(self, pbw):
        self.stop_js()
        if pbw.src is None:
            return
        self.running_uuid = pbw.uuid
        self.js = javascript.runtime.JSRuntime(self.pebble, pbw, self, persist_dir=self.persist_dir,
                                               block_private_addresses=self.block_private_addresses)
        self.js.log_output = lambda m: self.log_output(m)
        self.js.open_config_page = lambda url, callback: self.open_config_page(url, callback)
        gevent.spawn(self.js.run, pbw.src)

    def timeline_mapping_for_app(self, app_uuid):
        try:
            pbw = self.pbws[app_uuid]
        except KeyError:
            return None
        return pbw.layouts.get(self.pebble.pebble.watch_platform, {})

    def stop_js(self):
        if self.js is not None:
            self.js.stop()
            self.js = None
            self.running_uuid = None

    def run(self):
        self.logger.info('Connecting to pebble')
        greenlet = self.pebble.connect()
        if self.pebble.timeline_is_supported:
            self.timeline.continuous_sync()
            self.timeline.do_maintenance()
        greenlet.join()

    @property
    def account_token(self):
        return "0123456789abcdef0123456789abcdef"

    @property
    def watch_token(self):
        return "0123456789abcdef0123456789abcdef"

    def do_config(self):
        if self.js is None:
            self.log_output("No JS found, can't show configuration.")
            return
        self.js.do_config()

    def log_output(self, message):
        raise NotImplemented

    def open_config_page(self, url, callback):
        raise NotImplemented

    @staticmethod
    def url_append_params(url, params):
        parsed = urlparse.urlparse(url, "http")
        query = parsed.query
        if parsed.query != '':
            query += '&'

        encoded_params = urllib.urlencode(params)
        query += encoded_params
        return urlparse.urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, query, parsed.fragment))

    @property
    def _pbw_cache_dir(self):
        if self.persist_dir is None:
            return None
        path = os.path.join(self.persist_dir, 'app_cache')
        if not os.path.exists(path):
            os.makedirs(path)
        return path


text:
//
//  FXMountManager.h
//  FXShare
//
//  Created by Zeacone on 15/10/24.
//  Copyright © 2015年 Zeacone. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <NetFS/NetFS.h>

typedef void(^startBlock)();
typedef void(^endBlock)(NSInteger status, AsyncRequestID requestID, CFArrayRef mountpoints);

@interface FXMountManager : NSObject

@property (nonatomic, assign) startBlock startBlk;
@property (nonatomic, assign) endBlock endBlk;

/**
 *  Mount with parameter.
 *
 *  @param parameter         Parameter to mount. Include username, password, remote url and local path.
 *  @param startHandler      Callback of starting mount.
 *  @param completionHandler Callback of ending mount.
 *  @param timeout           Set timeout.
 */
- (void)mountWithParameter:(NSDictionary *)parameter onQueue:(dispatch_queue_t)queue start:(startBlock)startHandler completion:(endBlock)completionHandler timeout:(NSTimeInterval)timeout;

/**
 *  Unmount with parameter.
 *
 *  @param parameter         parameter Parameter to unmount include username, password, remote url and local path.
 *  @param completionHandler Callback of unmount result.
 */
- (void)unmountWithParameter:(NSDictionary *)parameter completion:(void(^)(BOOL result, NSString *reason))completionHandler;

/**
 *  Check if the mount disconnect.
 *
 *  @param parameter Mount parameter.
 */
- (BOOL)isMountParameterOnline:(NSDictionary *)parameter;

@end


text:
A command-line client for the Poke message transport server.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'poke-stick'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install poke-stick

## Usage

A command-line client for the Poke message transport server.  Performs a
GET request using the target URI, unless a --file is supplied, in which
case a POST request is made using the contents of the supplied file.
The mimetype is determined from the file's extension, but this can be
overridden (see options below).

    $ stick localhost:9995/foo

    $ stick localhost:9995/foo foo.xml

## Contributing

1. Fork it ( https://github.com/joelhelbling/poke-stick/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
{% extends "base.html" %}
{% load gross from prices_i18n %}
{% load i18n %}
{% load static from staticfiles %}
{% load render_bundle from webpack_loader %}

{% block title %}{% trans "Your cart" %} — {{ block.super }}{% endblock %}

{% block breadcrumb %}
    {{ block.super }}

{% trans "Cart" %}

{% endblock breadcrumb %}

{% block stylesheet %}
  {{ block.super }}
  {% render_bundle 'cart' 'css' %}
{% endblock stylesheet %}

{% block footer_scripts %}
  {{ block.super }}
  {% render_bundle 'cart' 'js' %}
{% endblock footer_scripts %}

{% block content %}
{% if cart_lines %}

            {% trans "Product" %}

            {% trans "Quantity" %}
            {% trans "Price" %}
            {% trans "Subtotal" %}

            {% trans "Total" %}:

                    {% spaceless %}
                        {% gross cart_total html=True %}
                        {% if local_cart_total %}

                                ≈
                                {% gross local_cart_total html=True %}

                        {% endif %}
                    {% endspaceless %}

            {% for line in cart_lines %}

                            {% if line.variant.product.images.first %}

                            {% else %}

                            {% endif %}

                            {{ line.variant.product }} - {{ line.variant.display_variant }}

                            <form role="form" action="{% url "cart:update-line" variant_id=line.variant.pk %}" method="post" class="form-cart">

                                    {{ line.form.quantity }}

                                        <button class="btn btn-info" type="submit">{% trans "Update" %}</button>

                                {% if line.form.quantity.errors %}
                                    {% for error in form.quantity.errors %}
                                        {{ error }}
                                    {% endfor %}
                                {% endif %}
                                {% csrf_token %}
                            </form>

                            <button type="submit" class="btn btn-link btn-sm cart-item-remove">
                                {% trans "Remove from cart" %}
                            </button>

                    {% gross line.get_price_per_item html=True %}
                    {% gross line.get_total html=True %}

            {% endfor %}

            {% trans "Proceed to checkout" %}

{% else %}

    {% trans 'Your cart is empty' %}

{% endif %}
{% endblock content %}


text:
require 'goliath'
# require 'ruby-debug' # *** Comment out when not in use ***
require 'em-mongo'
require 'em-http'
require 'em-synchrony/em-http'
require 'em-synchrony/em-mongo'
require 'yajl/json_gem'

$: << File.expand_path('../..', __FILE__)

# Middleware
require 'middleware/api_auth_barrier'

class Version < Goliath::API
  use ::Rack::ContentLength
  use Goliath::Rack::Heartbeat, { :path => '/status', :response => [200, {}, []] }
  use Goliath::Rack::Tracer, 'X-Tracer'
  use Goliath::Rack::Params
  use Goliath::Rack::DefaultMimeType
  use Goliath::Rack::Render, 'json'
  use Goliath::Rack::Validation::RequiredParam, :key => %w(_apikey)
  use Goliath::Rack::BarrierAroundwareFactory, ApiAuthBarrier

  def response(env)
    [200, {}, env]
  end
end


text:
This functionality is now native to serverless. See the docs at https://serverless.com/framework/docs/providers/aws/events/s3#using-existing-buckets for more information.

-----

# Why?

Overcomes the CloudFormation limitation on attaching an event to an uncontrolled bucket, for Serverless.com 1.11.0+. See [this stackoverflow issue](http://serverfault.com/questions/610788/using-cloudformation-with-an-existing-s3-bucket) for more information.

# How?

**1. NPM dependency**

```
> npm install --save-dev serverless-plugin-existing-s3
```

**Declare the plugin in your serverless.yml**

```serverless.yml

plugins:
 - serverless-plugin-existing-s3

```

**2. Give your deploy permission to access the bucket.**
The BUCKET_NAME variable within provider.iamRoleStatements.Resource.Fn::Join needs to be replaced with the name of the bucket you want to attach your event(s) to. If there are multiple buckets you want to attach events to add a new item for each bucket.

```serverless.yml
provider:
  name: aws
  runtime: nodejs4.3
  iamRoleStatements:
    ...
    -  Effect: "Allow"
       Action:
         - "s3:GetBucketNotification"
         - "s3:PutBucketNotification"
       Resource:
         Fn::Join:
           - ""
           - - "arn:aws:s3:::BUCKET_NAME or *"
```

**3. Attach an event to your target function.**
Add an -existingS3 event definition under 'events' of your function declaration. The 'events' value is optional under your -existingS3 event and if omitted, it will default to a single entry for "s3:ObjectCreated:\*".

The rules property is optional and can contain either a prefix, suffix or both of these properties as a rule for when the event will trigger.

Note: The bucketEvents and eventRules attributes introduced in 1.0.1 will still work, but will likely be deprecated in the future.

```serverless.yml

functions:
  someFunction:
    handler: index.handler
    events:
      - existingS3:
          bucket: BUCKET_NAME
          events:
            - s3:ObjectCreated:*
          rules:
            - prefix: images/
            - suffix: .jpg
```

**Multiple Prefixes**
As identified with [issue 62](https://github.com/matt-filion/serverless-external-s3-event/issues/62).

```
functions:
  myAmazingLambdaFunction:
    handler: lambda-to-be-triggered-by-s3.handler
    events:
      - existingS3:
          bucket: 'my-bucket'
          events:
            - s3:ObjectCreated:*
          rules:
            - prefix: some/prefix
      - existingS3:
          bucket: 'my-bucket'
          events:
            - s3:ObjectCreated:*
          rules:
            - prefix: someother/prefix
```

**Run the command.**
_I could not figure out how to hook into the existing deploy behaviors built into Serverless.com's deploy command. So as a result you have to run a separate command AFTER you do `sls deploy`._

```
> sls deploy
Serverless: Zipping service...
Serverless: Uploading CloudFormation file to S3...
Serverless: Removing old service versions...
Serverless: Uploading .zip file to S3...
Serverless: Updating Stack...
Serverless: Checking stack update progress...
..
Serverless: Deployment successful!

Service Information
service: service-name
stage: stage
region: region
endpoints:
  None
functions:
  someFunction: arn:aws:lambda:region:accountid:function:service-name-stage-someFunction

> sls s3deploy
Attaching event(s) to: someFunction
Done.

```

**Command line options**

- `--alias`: Use this option to specify the lambda function's alias to be set as the event handler. This is optional and if omitted, the lambda function without a qualifier will be used (the `$LATEST` version). Here's an example on how to use it:

```
> sls deploy --stage dev --alias dev
> sls s3deploy --stage dev --alias dev
> sls s3eventremove --stage dev --alias dev
```

# I haz an errawr

The only one I see, and quite regularly during my testing, is a result of having the wrong bucket name configured in the serverless.yml, either in the IAM configuration providing permissions or in the function definition where I'm attaching the event. Make sure your bucket names are right.

If you are really stuck, open an issue at https://github.com/matt-filion/serverless-external-s3-event/issues

# Contributing

You can run test by running

```
yarn install
yarn test
```


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<geonames style="FULL">
<totalResultsCount>270</totalResultsCount>
<geoname>
<toponymName>Lavaca County</toponymName>
<name>Lavaca County</name>
<lat>29.38435</lat>
<lng>-96.93015</lng>
<geonameId>4705575</geonameId>
<countryCode>US</countryCode>
<countryName>United States</countryName>
<fcl>A</fcl>
<fcode>ADM2</fcode>
<fclName>country, state, region,...</fclName>
<fcodeName>second-order administrative division</fcodeName>
<population>19263</population>
<alternateNames>Comte de Lavaca,Comté de Lavaca</alternateNames>
<elevation>80</elevation>
<continentCode>NA</continentCode>
<adminCode1 ISO3166-2="TX">TX</adminCode1>
<adminName1>Texas</adminName1>
<adminCode2>285</adminCode2>
<adminName2>Lavaca County</adminName2>
<alternateName lang="fr">Comté de Lavaca</alternateName>
<alternateName lang="link">http://en.wikipedia.org/wiki/Lavaca_County%2C_Texas</alternateName>
<timezone dstOffset="-5.0" gmtOffset="-6.0">America/Chicago</timezone>
<bbox>
<west>-97.23509</west>
<north>29.63236</north>
<east>-96.56081</east>
<south>29.0627</south>
</bbox>
<score>19.188770294189453</score>
</geoname>
<geoname>
<toponymName>Shiner</toponymName>
<name>Shiner</name>
<lat>29.42913</lat>
<lng>-97.17054</lng>
<geonameId>4728482</geonameId>
<countryCode>US</countryCode>
<countryName>United States</countryName>
<fcl>P</fcl>
<fcode>PPL</fcode>
<fclName>city, village,...</fclName>
<fcodeName>populated place</fcodeName>
<population>2069</population>
<alternateNames/>
<elevation>109</elevation>
<continentCode>NA</continentCode>
<adminCode1 ISO3166-2="TX">TX</adminCode1>
<adminName1>Texas</adminName1>
<adminCode2>285</adminCode2>
<adminName2>Lavaca County</adminName2>
<alternateName lang="link">http://en.wikipedia.org/wiki/Shiner%2C_Texas</alternateName>
<alternateName lang="post">77984</alternateName>
<alternateName lang="unlc">INR</alternateName>
<timezone dstOffset="-5.0" gmtOffset="-6.0">America/Chicago</timezone>
<bbox>
<west>-97.17571</west>
<north>29.43363</north>
<east>-97.16538</east>
<south>29.42463</south>
</bbox>
<score>12.245238304138184</score>
</geoname>
<geoname>
<toponymName>Port Lavaca</toponymName>
<name>Port Lavaca</name>
<lat>28.615</lat>
<lng>-96.62609</lng>
<geonameId>4720067</geonameId>
<countryCode>US</countryCode>
<countryName>United States</countryName>
<fcl>P</fcl>
<fcode>PPLA2</fcode>
<fclName>city, village,...</fclName>
<fcodeName>seat of a second-order administrative division</fcodeName>
<population>12248</population>
<alternateNames/>
<elevation>4</elevation>
<continentCode>NA</continentCode>
<adminCode1 ISO3166-2="TX">TX</adminCode1>
<adminName1>Texas</adminName1>
<adminCode2>057</adminCode2>
<adminName2>Calhoun County</adminName2>
<alternateName lang="link">http://en.wikipedia.org/wiki/Port_Lavaca%2C_Texas</alternateName>
<alternateName lang="post">77979</alternateName>
<alternateName lang="unlc">PLV</alternateName>
<timezone dstOffset="-5.0" gmtOffset="-6.0">America/Chicago</timezone>
<bbox>
<west>-96.66238</west>
<north>28.65957</north>
<east>-96.60011</east>
<south>28.57753</south>
</bbox>
<score>11.427148818969727</score>
</geoname>
<geoname>
<toponymName>Breslau</toponymName>
<name>Breslau</name>
<lat>29.52302</lat>
<lng>-96.99665</lng>
<geonameId>4676234</geonameId>
<countryCode>US</countryCode>
<countryName>United States</countryName>
<fcl>P</fcl>
<fcode>PPL</fcode>
<fclName>city, village,...</fclName>
<fcodeName>populated place</fcodeName>
<population/>
<alternateNames/>
<elevation>83</elevation>
<continentCode>NA</continentCode>
<adminCode1 ISO3166-2="TX">TX</adminCode1>
<adminName1>Texas</adminName1>
<adminCode2>285</adminCode2>
<adminName2>Lavaca County</adminName2>
<alternateName lang="link">http://en.wikipedia.org/wiki/Breslau%2C_Texas</alternateName>
<timezone dstOffset="-5.0" gmtOffset="-6.0">America/Chicago</timezone>
<bbox>
<west>-97.00699</west>
<north>29.53201</north>
<east>-96.98631</east>
<south>29.51402</south>
</bbox>
<score>10.204364776611328</score>
</geoname>
<geoname>
<toponymName>Hallettsville</toponymName>
<name>Hallettsville</name>
<lat>29.44385</lat>
<lng>-96.94109</lng>
<geonameId>4695866</geonameId>
<countryCode>US</countryCode>
<countryName>United States</countryName>
<fcl>P</fcl>
<fcode>PPLA2</fcode>
<fclName>city, village,...</fclName>
<fcodeName>seat of a second-order administrative division</fcodeName>
<population>2550</population>
<alternateNames/>
<elevation>71</elevation>
<continentCode>NA</continentCode>
<adminCode1 ISO3166-2="TX">TX</adminCode1>
<adminName1>Texas</adminName1>
<adminCode2>285</adminCode2>
<adminName2>Lavaca County</adminName2>
<alternateName lang="link">http://en.wikipedia.org/wiki/Hallettsville%2C_Texas</alternateName>
<alternateName lang="post">77964</alternateName>
<timezone dstOffset="-5.0" gmtOffset="-6.0">America/Chicago</timezone>
<bbox>
<west>-96.9484</west>
<north>29.45021</north>
<east>-96.93379</east>
<south>29.43749</south>
</bbox>
<score>10.204364776611328</score>
</geoname>
<geoname>
<toponymName>Moulton</toponymName>
<name>Moulton</name>
<lat>29.57496</lat>
<lng>-97.14276</lng>
<geonameId>4712587</geonameId>
<countryCode>US</countryCode>
<countryName>United States</countryName>
<fcl>P</fcl>
<fcode>PPL</fcode>
<fclName>city, village,...</fclName>
<fcodeName>populated place</fcodeName>
<population>886</population>
<alternateNames/>
<elevation>110</elevation>
<continentCode>NA</continentCode>
<adminCode1 ISO3166-2="TX">TX</adminCode1>
<adminName1>Texas</adminName1>
<adminCode2>285</adminCode2>
<adminName2>Lavaca County</adminName2>
<alternateName lang="link">http://en.wikipedia.org/wiki/Moulton%2C_Texas</alternateName>
<alternateName lang="post">77975</alternateName>
<timezone dstOffset="-5.0" gmtOffset="-6.0">America/Chicago</timezone>
<bbox>
<west>-97.1438</west>
<north>29.57586</north>
<east>-97.14173</east>
<south>29.57406</south>
</bbox>
<score>10.204364776611328</score>
</geoname>
<geoname>
<toponymName>Sublime</toponymName>
<name>Sublime</name>
<lat>29.47885</lat>
<lng>-96.79748</lng>
<geonameId>4734801</geonameId>
<countryCode>US</countryCode>
<countryName>United States</countryName>
<fcl>P</fcl>
<fcode>PPL</fcode>
<fclName>city, village,...</fclName>
<fcodeName>populated place</fcodeName>
<population/>
<alternateNames/>
<elevation>69</elevation>
<continentCode>NA</continentCode>
<adminCode1 ISO3166-2="TX">TX</adminCode1>
<adminName1>Texas</adminName1>
<adminCode2>285</adminCode2>
<adminName2>Lavaca County</adminName2>
<alternateName lang="link">http://en.wikipedia.org/wiki/Sublime%2C_Texas</alternateName>
<alternateName lang="post">77986</alternateName>
<timezone dstOffset="-5.0" gmtOffset="-6.0">America/Chicago</timezone>
<bbox>
<west>-96.80781</west>
<north>29.48785</north>
<east>-96.78715</east>
<south>29.46986</south>
</bbox>
<score>10.204364776611328</score>
</geoname>
<geoname>
<toponymName>Port Lavaca, Calhoun County Airport</toponymName>
<name>Port Lavaca, Calhoun County Airport</name>
<lat>28.65389</lat>
<lng>-96.68111</lng>
<geonameId>6301733</geonameId>
<countryCode>US</countryCode>
<countryName>United States</countryName>
<fcl>S</fcl>
<fcode>AIRP</fcode>
<fclName>spot, building, farm</fclName>
<fcodeName>airport</fcodeName>
<population/>
<alternateNames>KT97</alternateNames>
<elevation>9</elevation>
<continentCode>NA</continentCode>
<adminCode1 ISO3166-2="TX">TX</adminCode1>
<adminName1>Texas</adminName1>
<adminCode2/>
<adminName2/>
<alternateName lang="icao">KT97</alternateName>
<timezone dstOffset="-5.0" gmtOffset="-6.0">America/Chicago</timezone>
<score>9.141718864440918</score>
</geoname>
<geoname>
<toponymName>City of Port Lavaca</toponymName>
<name>City of Port Lavaca</name>
<lat>28.61807</lat>
<lng>-96.62784</lng>
<geonameId>7174115</geonameId>
<countryCode>US</countryCode>
<countryName>United States</countryName>
<fcl>A</fcl>
<fcode>ADMD</fcode>
<fclName>country, state, region,...</fclName>
<fcodeName>administrative division</fcodeName>
<population>12248</population>
<alternateNames/>
<elevation>5</elevation>
<continentCode>NA</continentCode>
<adminCode1 ISO3166-2="TX">TX</adminCode1>
<adminName1>Texas</adminName1>
<adminCode2>057</adminCode2>
<adminName2>Calhoun County</adminName2>
<timezone dstOffset="-5.0" gmtOffset="-6.0">America/Chicago</timezone>
<bbox>
<west>-96.66238</west>
<north>28.65957</north>
<east>-96.60011</east>
<south>28.57753</south>
</bbox>
<score>9.141718864440918</score>
</geoname>
<geoname>
<toponymName>Dean Ranch Airport</toponymName>
<name>Dean Ranch Airport</name>
<lat>29.49024</lat>
<lng>-97.12193</lng>
<geonameId>4685602</geonameId>
<countryCode>US</countryCode>
<countryName>United States</countryName>
<fcl>S</fcl>
<fcode>AIRP</fcode>
<fclName>spot, building, farm</fclName>
<fcodeName>airport</fcodeName>
<population/>
<alternateNames/>
<elevation>118</elevation>
<continentCode>NA</continentCode>
<adminCode1 ISO3166-2="TX">TX</adminCode1>
<adminName1>Texas</adminName1>
<adminCode2>285</adminCode2>
<adminName2>Lavaca County</adminName2>
<timezone dstOffset="-5.0" gmtOffset="-6.0">America/Chicago</timezone>
<score>8.163492202758789</score>
</geoname>
</geonames>


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <winpr/crt.h>
#include <winpr/stream.h>

#include "rdpdr_main.h"
#include "devman.h"
#include "irp.h"

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT irp_free(IRP* irp)
{
	if (!irp)
		return CHANNEL_RC_OK;

	Stream_Free(irp->input, TRUE);
	Stream_Free(irp->output, TRUE);

	_aligned_free(irp);
	return CHANNEL_RC_OK;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT irp_complete(IRP* irp)
{
	size_t pos;
	rdpdrPlugin* rdpdr;
	UINT error;

	rdpdr = (rdpdrPlugin*)irp->devman->plugin;

	pos = Stream_GetPosition(irp->output);
	Stream_SetPosition(irp->output, RDPDR_DEVICE_IO_RESPONSE_LENGTH - 4);
	Stream_Write_UINT32(irp->output, irp->IoStatus); /* IoStatus (4 bytes) */
	Stream_SetPosition(irp->output, pos);

	error = rdpdr_send(rdpdr, irp->output);
	irp->output = NULL;

	irp_free(irp);
	return error;
}

IRP* irp_new(DEVMAN* devman, wStream* s, UINT* error)
{
	IRP* irp;
	DEVICE* device;
	UINT32 DeviceId;

	if (Stream_GetRemainingLength(s) < 20)
	{
		if (error)
			*error = ERROR_INVALID_DATA;
		return NULL;
	}

	Stream_Read_UINT32(s, DeviceId); /* DeviceId (4 bytes) */
	device = devman_get_device_by_id(devman, DeviceId);

	if (!device)
	{
		WLog_WARN(TAG, "devman_get_device_by_id failed!");
		if (error)
			*error = CHANNEL_RC_OK;

		return NULL;
	};

	irp = (IRP*)_aligned_malloc(sizeof(IRP), MEMORY_ALLOCATION_ALIGNMENT);

	if (!irp)
	{
		WLog_ERR(TAG, "_aligned_malloc failed!");
		if (error)
			*error = CHANNEL_RC_NO_MEMORY;
		return NULL;
	}

	ZeroMemory(irp, sizeof(IRP));

	irp->input = s;
	irp->device = device;
	irp->devman = devman;

	Stream_Read_UINT32(s, irp->FileId);        /* FileId (4 bytes) */
	Stream_Read_UINT32(s, irp->CompletionId);  /* CompletionId (4 bytes) */
	Stream_Read_UINT32(s, irp->MajorFunction); /* MajorFunction (4 bytes) */
	Stream_Read_UINT32(s, irp->MinorFunction); /* MinorFunction (4 bytes) */

	irp->output = Stream_New(NULL, 256);
	if (!irp->output)
	{
		WLog_ERR(TAG, "Stream_New failed!");
		_aligned_free(irp);
		if (error)
			*error = CHANNEL_RC_NO_MEMORY;
		return NULL;
	}
	Stream_Write_UINT16(irp->output, RDPDR_CTYP_CORE);                /* Component (2 bytes) */
	Stream_Write_UINT16(irp->output, PAKID_CORE_DEVICE_IOCOMPLETION); /* PacketId (2 bytes) */
	Stream_Write_UINT32(irp->output, DeviceId);                       /* DeviceId (4 bytes) */
	Stream_Write_UINT32(irp->output, irp->CompletionId);              /* CompletionId (4 bytes) */
	Stream_Write_UINT32(irp->output, 0);                              /* IoStatus (4 bytes) */

	irp->Complete = irp_complete;
	irp->Discard = irp_free;

	irp->thread = NULL;
	irp->cancelled = FALSE;

	if (error)
		*error = CHANNEL_RC_OK;

	return irp;
}


text:
<?php

include_once 'phing/types/DataType.php';
include_once 'phing/filters/HeadFilter.php';
include_once 'phing/filters/IconvFilter.php';
include_once 'phing/filters/TailFilter.php';
include_once 'phing/filters/LineContains.php';
include_once 'phing/filters/LineContainsRegexp.php';
include_once 'phing/filters/ExpandProperties.php';
include_once 'phing/filters/PrefixLines.php';
include_once 'phing/filters/ReplaceRegexp.php';
include_once 'phing/filters/ReplaceTokens.php';
include_once 'phing/filters/ReplaceTokensWithFile.php';
include_once 'phing/filters/StripPhpComments.php';
include_once 'phing/filters/StripLineBreaks.php';
include_once 'phing/filters/StripLineComments.php';
include_once 'phing/filters/StripWhitespace.php';
include_once 'phing/filters/TabToSpaces.php';
include_once 'phing/filters/TidyFilter.php';
include_once 'phing/filters/TranslateGettext.php';
include_once 'phing/filters/XincludeFilter.php';
include_once 'phing/filters/XsltFilter.php';

/**
 * FilterChain may contain a chained set of filter readers.
 *
 * @author    Yannick Lecaillez <yl@seasonfive.com>
 * @version   $Id$
 * @package   phing.types
 */
class FilterChain extends DataType {

    private $filterReaders = array();

    function __construct($project = null) {
        if ($project)
        {
            $this->project = $project;
        }
    }

    function getFilterReaders() {
        return $this->filterReaders;
    }

    function addExpandProperties(ExpandProperties $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addGettext(TranslateGettext $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addHeadFilter(HeadFilter $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addIconvFilter(IconvFilter $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addTailFilter(TailFilter $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addLineContains(LineContains $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addLineContainsRegExp(LineContainsRegExp $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addPrefixLines(PrefixLines $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addReplaceTokens(ReplaceTokens $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addReplaceTokensWithFile(ReplaceTokensWithFile $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addReplaceRegexp(ReplaceRegexp $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addStripPhpComments(StripPhpComments $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addStripLineBreaks(StripLineBreaks $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addStripLineComments(StripLineComments $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addStripWhitespace(StripWhitespace $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addTidyFilter(TidyFilter $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addTabToSpaces(TabToSpaces $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addXincludeFilter(XincludeFilter $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addXsltFilter(XsltFilter $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    function addFilterReader(PhingFilterReader $o) {
        $o->setProject($this->project);
        $this->filterReaders[] = $o;
    }

    /*
     * Makes this instance in effect a reference to another FilterChain
     * instance.
     *
     *
You must not set another attribute or nest elements inside
     * this element if you make it a reference.

     *
     * @param  $r the reference to which this instance is associated
     * @throws BuildException if this instance already has been configured.
    */
    function setRefid(Reference $r) {

        if ( count($this->filterReaders) !== 0 ) {
            throw $this->tooManyAttributes();
        }

        // change this to get the objects from the other reference
        $o = $r->getReferencedObject($this->getProject());
        if ( $o instanceof FilterChain ) {
            $this->filterReaders = $o->getFilterReaders();
        } else {
            throw new BuildException($r->getRefId()." doesn't refer to a FilterChain");
        }
        parent::setRefid($r);
    }

}


text:
run-time type information (rtti)
================================
because somebody's going to want to shut this off, too...
---------------------------------------------------------

Sol does not use RTTI anymore.

*THE BELOW IS NO LONGER NEEDED.*

Not compiling with C++'s run-time type information? Do a ``#define SOL_NO_RTII`` before you include ``sol.hpp`` or define ``SOL_NO_RTTI`` on your command line. Be sure to understand the :ref:`implications<usertype-inheritance>` of doing so if you also turn off exceptions.

If you come across bugs or can't compile because there's a stray `typeid` or `typeinfo` that wasn't hidden behind a ``#ifndef SOL_NO_RTTI``, please file `an issue`_ or even make a pull request so it can be fixed for everyone.

.. _an issue: https://github.com/ThePhD/sol2/issues