text:
(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    return mod(require("../lib/infer"), require("../lib/tern"), require("../lib/comment"),
               require("acorn"), require("acorn/dist/walk"));
  if (typeof define == "function" && define.amd) // AMD
    return define(["../lib/infer", "../lib/tern", "../lib/comment", "acorn/dist/acorn", "acorn/dist/walk"], mod);
  mod(tern, tern, tern.comment, acorn, acorn.walk);
})(function(infer, tern, comment, acorn, walk) {
  "use strict";

  var WG_MADEUP = 1, WG_STRONG = 101;

  tern.registerPlugin("doc_comment", function(server, options) {
    server.mod.jsdocTypedefs = Object.create(null);
    server.on("reset", function() {
      server.mod.jsdocTypedefs = Object.create(null);
    });
    server.mod.docComment = {
      weight: options && options.strong ? WG_STRONG : undefined,
      fullDocs: options && options.fullDocs
    };

    server.on("postParse", postParse)
    server.on("postInfer", postInfer)
    server.on("postLoadDef", postLoadDef)
  });

  function postParse(ast, text) {
    function attachComments(node) { comment.ensureCommentsBefore(text, node); }

    walk.simple(ast, {
      VariableDeclaration: attachComments,
      FunctionDeclaration: attachComments,
      MethodDefinition: attachComments,
      Property: attachComments,
      AssignmentExpression: function(node) {
        if (node.operator == "=") attachComments(node);
      },
      CallExpression: function(node) {
        if (isDefinePropertyCall(node)) attachComments(node);
      },
      ExportNamedDeclaration: attachComments,
      ExportDefaultDeclaration: attachComments,
      ClassDeclaration: attachComments
    });
  }

  function isDefinePropertyCall(node) {
    return node.callee.type == "MemberExpression" &&
      node.callee.object.name == "Object" &&
      node.callee.property.name == "defineProperty" &&
      node.arguments.length >= 3 &&
      typeof node.arguments[1].value == "string";
  }

  function postInfer(ast, scope) {
    jsdocParseTypedefs(ast.sourceFile.text, scope);

    walk.simple(ast, {
      VariableDeclaration: function(node, scope) {
        var decl = node.declarations[0].id
        if (node.commentsBefore && decl.type == "Identifier")
          interpretComments(node, node.commentsBefore, scope,
                            scope.getProp(node.declarations[0].id.name));
      },
      FunctionDeclaration: function(node, scope) {
        if (node.commentsBefore)
          interpretComments(node, node.commentsBefore, scope,
                            scope.getProp(node.id.name),
                            node.scope.fnType);
      },
      ClassDeclaration: function(node, scope) {
        if (node.commentsBefore)
          interpretComments(node, node.commentsBefore, scope,
                            scope.getProp(node.id.name),
                            node.objType);
      },
      AssignmentExpression: function(node, scope) {
        if (node.commentsBefore)
          interpretComments(node, node.commentsBefore, scope,
                            infer.expressionType({node: node.left, state: scope}));
      },
      ObjectExpression: function(node, scope) {
        for (var i = 0; i < node.properties.length; ++i) {
          var prop = node.properties[i], name = infer.propName(prop)
          if (name != "<i>" && prop.commentsBefore)
            interpretComments(prop, prop.commentsBefore, scope, node.objType.getProp(name))
        }
      },
      Class: function(node, scope) {
        var proto = node.objType.getProp("prototype").getObjType()
        if (!proto) return
        for (var i = 0; i < node.body.body.length; i++) {
          var method = node.body.body[i], name
          if (!method.commentsBefore) continue
          if (method.kind == "constructor")
            interpretComments(method, method.commentsBefore, scope, node.objType)
          else if ((name = infer.propName(method)) != "<i>")
            interpretComments(method, method.commentsBefore, scope, proto.getProp(name))
        }
      },
      CallExpression: function(node, scope) {
        if (node.commentsBefore && isDefinePropertyCall(node)) {
          var type = infer.expressionType({node: node.arguments[0], state: scope}).getObjType();
          if (type && type instanceof infer.Obj) {
            var prop = type.props[node.arguments[1].value];
            if (prop) interpretComments(node, node.commentsBefore, scope, prop);
          }
        }
      },
      ExportNamedDeclaration: function(node, scope) {
        if (node.commentsBefore && node.declaration && node.declaration.type === 'FunctionDeclaration') {
          interpretComments(node.declaration, node.commentsBefore, scope,
                            scope.getProp(node.declaration.id.name),
                            node.declaration.scope.fnType);
        }
      },
      ExportDefaultDeclaration: function(node, scope) {
        if (node.commentsBefore && node.declaration && node.declaration.type === 'FunctionDeclaration') {
          interpretComments(node.declaration, node.commentsBefore, scope,
                            scope.getProp(node.declaration.id.name),
                            node.declaration.scope.fnType);
        }
      }
    }, infer.searchVisitor, scope);
  }

  function postLoadDef(data) {
    var defs = data["!typedef"];
    var cx = infer.cx(), orig = data["!name"];
    if (defs) for (var name in defs)
      cx.parent.mod.jsdocTypedefs[name] =
        maybeInstance(infer.def.parse(defs[name], orig, name), name);
  }

  // COMMENT INTERPRETATION

  function stripLeadingChars(lines) {
    for (var head, i = 1; i < lines.length; i++) {
      var line = lines[i], lineHead = line.match(/^[\s\*]*/)[0];
      if (lineHead != line) {
        if (head == null) {
          head = lineHead;
        } else {
          var same = 0;
          while (same < head.length && head.charCodeAt(same) == lineHead.charCodeAt(same)) ++same;
          if (same < head.length) head = head.slice(0, same)
        }
      }
    }
    lines = lines.map(function(line, i) {
      line = line.replace(/\s+$/, "");
      if (i == 0 && head != null) {
        for (var j = 0; j < head.length; j++) {
          var found = line.indexOf(head.slice(j));
          if (found == 0) return line.slice(head.length - j);
        }
      }
      if (head == null || i == 0) return line.replace(/^[\s\*]*/, "");
      if (line.length < head.length) return "";
      return line.slice(head.length);
    });
    while (lines.length && !lines[lines.length - 1]) lines.pop();
    while (lines.length && !lines[0]) lines.shift();
    return lines;
  }

  function interpretComments(node, comments, scope, aval, type) {
    jsdocInterpretComments(node, scope, aval, comments);
    var cx = infer.cx();

    if (!type && aval instanceof infer.AVal && aval.types.length) {
      type = aval.types[aval.types.length - 1];
      if (!(type instanceof infer.Obj) || type.origin != cx.curOrigin || type.doc)
        type = null;
    }

    for (var i = comments.length - 1; i >= 0; i--) {
      var text = stripLeadingChars(comments[i].split(/\r\n?|\n/)).join("\n");
      if (text) {
        if (aval instanceof infer.AVal) aval.doc = text;
        if (type) type.doc = text;
        break;
      }
    }
  }

  // Parses a subset of JSDoc-style comments in order to include the
  // explicitly defined types in the analysis.

  function skipSpace(str, pos) {
    while (/\s/.test(str.charAt(pos))) ++pos;
    return pos;
  }

  function isIdentifier(string) {
    if (!acorn.isIdentifierStart(string.charCodeAt(0))) return false;
    for (var i = 1; i < string.length; i++)
      if (!acorn.isIdentifierChar(string.charCodeAt(i))) return false;
    return true;
  }

  function parseLabelList(scope, str, pos, close) {
    var labels = [], types = [], madeUp = false;
    for (var first = true; ; first = false) {
      pos = skipSpace(str, pos);
      if (first && str.charAt(pos) == close) break;
      var colon = str.indexOf(":", pos);
      if (colon < 0) return null;
      var label = str.slice(pos, colon);
      if (!isIdentifier(label)) return null;
      labels.push(label);
      pos = colon + 1;
      var type = parseType(scope, str, pos);
      if (!type) return null;
      pos = type.end;
      madeUp = madeUp || type.madeUp;
      types.push(type.type);
      pos = skipSpace(str, pos);
      var next = str.charAt(pos);
      ++pos;
      if (next == close) break;
      if (next != ",") return null;
    }
    return {labels: labels, types: types, end: pos, madeUp: madeUp};
  }

  function parseTypeAtom(scope, str, pos) {
    var result = parseTypeInner(scope, str, pos)
    if (!result) return null
    if (str.slice(result.end, result.end + 2) == "[]")
      return {madeUp: result.madeUp, end: result.end + 2, type: new infer.Arr(result.type)}
    else return result
  }

  function parseType(scope, str, pos) {
    var type, union = false, madeUp = false;
    for (;;) {
      var inner = parseTypeAtom(scope, str, pos);
      if (!inner) return null;
      madeUp = madeUp || inner.madeUp;
      if (union) inner.type.propagate(union);
      else type = inner.type;
      pos = skipSpace(str, inner.end);
      if (str.charAt(pos) != "|") break;
      pos++;
      if (!union) {
        union = new infer.AVal;
        type.propagate(union);
        type = union;
      }
    }
    var isOptional = false;
    if (str.charAt(pos) == "=") {
      ++pos;
      isOptional = true;
    }
    return {type: type, end: pos, isOptional: isOptional, madeUp: madeUp};
  }

  function parseTypeInner(scope, str, pos) {
    pos = skipSpace(str, pos);
    if (/[?!]/.test(str.charAt(pos))) pos++
    var type, madeUp = false;

    if (str.indexOf("function(", pos) == pos) {
      var args = parseLabelList(scope, str, pos + 9, ")"), ret = infer.ANull;
      if (!args) return null;
      pos = skipSpace(str, args.end);
      if (str.charAt(pos) == ":") {
        ++pos;
        var retType = parseType(scope, str, pos + 1);
        if (!retType) return null;
        pos = retType.end;
        ret = retType.type;
        madeUp = retType.madeUp;
      }
      type = new infer.Fn(null, infer.ANull, args.types, args.labels, ret);
    } else if (str.charAt(pos) == "[") {
      var inner = parseType(scope, str, pos + 1);
      if (!inner) return null;
      pos = skipSpace(str, inner.end);
      madeUp = inner.madeUp;
      if (str.charAt(pos) != "]") return null;
      ++pos;
      type = new infer.Arr(inner.type);
    } else if (str.charAt(pos) == "{") {
      var fields = parseLabelList(scope, str, pos + 1, "}");
      if (!fields) return null;
      type = new infer.Obj(true);
      for (var i = 0; i < fields.types.length; ++i) {
        var field = type.defProp(fields.labels[i]);
        field.initializer = true;
        fields.types[i].propagate(field);
      }
      pos = fields.end;
      madeUp = fields.madeUp;
    } else if (str.charAt(pos) == "(") {
      var inner = parseType(scope, str, pos + 1);
      if (!inner) return null;
      pos = skipSpace(str, inner.end);
      if (str.charAt(pos) != ")") return null;
      ++pos;
      type = inner.type;
    } else {
      var start = pos;
      if (!acorn.isIdentifierStart(str.charCodeAt(pos))) return null;
      while (acorn.isIdentifierChar(str.charCodeAt(pos))) ++pos;
      if (start == pos) return null;
      var word = str.slice(start, pos);
      if (/^(number|integer)$/i.test(word)) type = infer.cx().num;
      else if (/^bool(ean)?$/i.test(word)) type = infer.cx().bool;
      else if (/^string$/i.test(word)) type = infer.cx().str;
      else if (/^(null|undefined)$/i.test(word)) type = infer.ANull;
      else if (/^array$/i.test(word)) {
        var inner = null;
        if (str.charAt(pos) == "." && str.charAt(pos + 1) == "<") {
          var inAngles = parseType(scope, str, pos + 2);
          if (!inAngles) return null;
          pos = skipSpace(str, inAngles.end);
          madeUp = inAngles.madeUp;
          if (str.charAt(pos++) != ">") return null;
          inner = inAngles.type;
        }
        type = new infer.Arr(inner);
      } else if (/^object$/i.test(word)) {
        type = new infer.Obj(true);
        if (str.charAt(pos) == "." && str.charAt(pos + 1) == "<") {
          var key = parseType(scope, str, pos + 2);
          if (!key) return null;
          pos = skipSpace(str, key.end);
          if (str.charAt(pos++) != ",") return null;
          var val = parseType(scope, str, pos);
          if (!val) return null;
          pos = skipSpace(str, val.end);
          madeUp = key.madeUp || val.madeUp;
          if (str.charAt(pos++) != ">") return null;
          val.type.propagate(type.defProp("<i>"));
        }
      } else {
        while (str.charCodeAt(pos) == 46 ||
               acorn.isIdentifierChar(str.charCodeAt(pos))) ++pos;
        var path = str.slice(start, pos);
        var cx = infer.cx(), defs = cx.parent && cx.parent.mod.jsdocTypedefs, found;
        if (defs && (path in defs)) {
          type = defs[path];
        } else if (found = infer.def.parsePath(path, scope).getObjType()) {
          type = maybeInstance(found, path);
        } else {
          if (!cx.jsdocPlaceholders) cx.jsdocPlaceholders = Object.create(null);
          if (!(path in cx.jsdocPlaceholders))
            type = cx.jsdocPlaceholders[path] = new infer.Obj(null, path);
          else
            type = cx.jsdocPlaceholders[path];
          madeUp = true;
        }
      }
    }

    return {type: type, end: pos, madeUp: madeUp};
  }

  function maybeInstance(type, path) {
    if (type instanceof infer.Fn && /(?:^|\.)[A-Z][^\.]*$/.test(path)) {
      var proto = type.getProp("prototype").getObjType();
      if (proto instanceof infer.Obj) return infer.getInstance(proto);
    }
    return type;
  }

  function parseTypeOuter(scope, str, pos) {
    pos = skipSpace(str, pos || 0);
    if (str.charAt(pos) != "{") return null;
    var result = parseType(scope, str, pos + 1);
    if (!result) return null;
    var end = skipSpace(str, result.end);
    if (str.charAt(end) != "}") return null;
    result.end = end + 1;
    return result;
  }

  function jsdocInterpretComments(node, scope, aval, comments) {
    var type, args, ret, foundOne, self, parsed;

    for (var i = 0; i < comments.length; ++i) {
      var comment = comments[i];
      var decl = /(?:\n|\*)\s*@(type|param|arg(?:ument)?|returns?|this|class|constructor)\s+(.*)/g, m;
      while (m = decl.exec(comment)) {
        if (m[1] == "class" || m[1] == "constructor") {
          self = foundOne = true;
          continue;
        }

        if (m[1] == "this" && (parsed = parseType(scope, m[2], 0))) {
          self = parsed;
          foundOne = true;
          continue;
        }

        if (!(parsed = parseTypeOuter(scope, m[2]))) continue;
        foundOne = true;

        switch(m[1]) {
        case "returns": case "return":
          ret = parsed; break;
        case "type":
          type = parsed; break;
        case "param": case "arg": case "argument":
            // Possible jsdoc param name situations:
            // employee
            // [employee]
            // [employee=John Doe]
            // employee.name
            // employees[].name
            var name = m[2].slice(parsed.end).match(/^\s*(\[?)\s*([^\[\]\s=]+(\[\][^\[\]\s=]+)?)\s*(?:=[^\]]+\s*)?(\]?).*/);
            if (!name) continue;
            var argname = name[2] + (parsed.isOptional || (name[1] === '[' && name[4] === ']') ? "?" : "");

            // Check to see if the jsdoc is indicating a property of a previously documented parameter
            var isObjProp = false;
            var parts = argname.split('.');
            if (args && parts.length == 2) {
              var objname = parts[0];
              argname = parts[1];

              // Go through each of the previously found parameter to find the
              // object or array for which this new parameter should be a part
              // of
              var key, value;
              for (key in args) {
                value = args[key];

                if (key === objname && value.type instanceof infer.Obj) {
                  isObjProp = true;
                  parsed.type.propagate(value.type.defProp(argname));
                }
                else if (key + '[]' === objname && value.type instanceof infer.Arr) {
                  isObjProp = true;
                  parsed.type.propagate(value.type.getProp("<i>").getType().defProp(argname));
                }
              }
            }
            if (!isObjProp) {
              (args || (args = Object.create(null)))[argname] = parsed;
            }
          break;
        }
      }
    }

    if (foundOne) applyType(type, self, args, ret, node, aval);
  };

  function jsdocParseTypedefs(text, scope) {
    var cx = infer.cx();

    var re = /\s@typedef\s+(.*)/g, m;
    while (m = re.exec(text)) {
      var parsed = parseTypeOuter(scope, m[1]);
      var name = parsed && m[1].slice(parsed.end).match(/^\s*(\S+)/);
      if (name && parsed.type instanceof infer.Obj) {
        var rest = text.slice(m.index + m[0].length)
        while (m = /\s+@prop(?:erty)?\s+(.*)/.exec(rest)) {
          var propType = parseTypeOuter(scope, m[1]), propName
          if (propType && (propName = m[1].slice(propType.end).match(/^\s*(\S+)/)))
            propType.type.propagate(parsed.type.defProp(propName[1]))
          rest = rest.slice(m[0].length)
        }
        cx.parent.mod.jsdocTypedefs[name[1]] = parsed.type;
      }
    }
  }

  function propagateWithWeight(type, target) {
    var weight = infer.cx().parent.mod.docComment.weight;
    type.type.propagate(target, weight || (type.madeUp ? WG_MADEUP : undefined));
  }

  function isFunExpr(node) { return node.type == "FunctionExpression" || node.type == "ArrowFunctionExpression" }

  function applyType(type, self, args, ret, node, aval) {
    var fn;
    if (node.type == "VariableDeclaration") {
      var decl = node.declarations[0];
      if (decl.init && isFunExpr(decl.init)) fn = decl.init.scope.fnType;
    } else if (node.type == "FunctionDeclaration") {
      fn = node.scope.fnType;
    } else if (node.type == "AssignmentExpression") {
      if (isFunExpr(node.right))
        fn = node.right.scope.fnType;
    } else if (node.type == "CallExpression" || node.type === "ClassDeclaration") {
    } else { // An object property
      if (isFunExpr(node.value)) fn = node.value.scope.fnType;
    }

    if (fn && (args || ret || self)) {
      if (args) for (var i = 0; i < fn.argNames.length; ++i) {
        var name = fn.argNames[i], known = args[name];
        if (!known && (known = args[name + "?"]))
          fn.argNames[i] += "?";
        if (known) propagateWithWeight(known, fn.args[i]);
      }
      if (ret) {
        if (fn.retval == infer.ANull) fn.retval = new infer.AVal;
        propagateWithWeight(ret, fn.retval);
      }
      if (self === true) {
        var proto = fn.getProp("prototype").getObjType();
        self = proto && {type: infer.getInstance(proto, fn)};
      }
      if (self) propagateWithWeight(self, fn.self);
    } else if (type) {
      propagateWithWeight(type, aval);
    }
  };
});


text:
package org.onosproject.openstacknetworking.impl;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.onlab.packet.DHCP;
import org.onlab.packet.Ethernet;
import org.onlab.packet.IPv4;
import org.onlab.packet.Ip4Address;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onlab.packet.TpPort;
import org.onlab.packet.UDP;
import org.onlab.packet.dhcp.DhcpOption;
import org.onlab.util.Tools;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.LeadershipService;
import org.onosproject.cluster.NodeId;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.packet.DefaultOutboundPacket;
import org.onosproject.net.packet.PacketContext;
import org.onosproject.net.packet.PacketProcessor;
import org.onosproject.net.packet.PacketService;
import org.onosproject.openstacknetworking.api.Constants;
import org.onosproject.openstacknetworking.api.InstancePort;
import org.onosproject.openstacknetworking.api.InstancePortService;
import org.onosproject.openstacknetworking.api.OpenstackFlowRuleService;
import org.onosproject.openstacknetworking.api.OpenstackNetworkService;
import org.onosproject.openstacknode.api.OpenstackNode;
import org.onosproject.openstacknode.api.OpenstackNodeEvent;
import org.onosproject.openstacknode.api.OpenstackNodeListener;
import org.onosproject.openstacknode.api.OpenstackNodeService;
import org.openstack4j.model.network.HostRoute;
import org.openstack4j.model.network.IP;
import org.openstack4j.model.network.Network;
import org.openstack4j.model.network.Port;
import org.openstack4j.model.network.Subnet;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;

import java.nio.ByteBuffer;
import java.util.Dictionary;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_BroadcastAddress;
import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_Classless_Static_Route;
import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_DHCPServerIp;
import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_DomainServer;
import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_END;
import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_LeaseTime;
import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType;
import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_RouterAddress;
import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_SubnetMask;
import static org.onlab.packet.DHCP.MsgType.DHCPACK;
import static org.onlab.packet.DHCP.MsgType.DHCPOFFER;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.openstacknetworking.api.Constants.DHCP_TABLE;
import static org.onosproject.openstacknetworking.api.Constants.PRIORITY_DHCP_RULE;
import static org.onosproject.openstacknetworking.impl.OsgiPropertyConstants.DHCP_SERVER_MAC;
import static org.onosproject.openstacknetworking.impl.OsgiPropertyConstants.DHCP_SERVER_MAC_DEFAULT;
import static org.onosproject.openstacknode.api.OpenstackNode.NodeType.COMPUTE;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Handles DHCP requests for the virtual instances.
 */
@Component(
    immediate = true,
    property = {
        DHCP_SERVER_MAC + "=" + DHCP_SERVER_MAC_DEFAULT
    }
)
public class OpenstackSwitchingDhcpHandler {
    protected final Logger log = getLogger(getClass());

    private static final Ip4Address DEFAULT_PRIMARY_DNS = Ip4Address.valueOf("8.8.8.8");
    private static final Ip4Address DEFAULT_SECONDARY_DNS = Ip4Address.valueOf("8.8.4.4");
    private static final byte PACKET_TTL = (byte) 127;
    // TODO add MTU, static route option codes to ONOS DHCP and remove here
    private static final byte DHCP_OPTION_MTU = (byte) 26;
    private static final byte[] DHCP_DATA_LEASE_INFINITE =
            ByteBuffer.allocate(4).putInt(-1).array();

    private static final int OCTET_BIT_LENGTH = 8;
    private static final int V4_BYTE_SIZE = 4;
    private static final int V4_CIDR_LOWER_BOUND = -1;
    private static final int V4_CIDR_UPPER_BOUND = 33;
    private static final int PADDING_SIZE = 4;

    private static final byte HARDWARE_ADDR_LENGTH = (byte) 6;
    private static final byte DHCP_OPTION_DATA_LENGTH = (byte) 4;
    private static final int DHCP_OPTION_DNS_LENGTH = 8;
    private static final int DHCP_OPTION_MTU_LENGTH = 2;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected CoreService coreService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected ComponentConfigService configService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected PacketService packetService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected InstancePortService instancePortService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected OpenstackNetworkService osNetworkService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected OpenstackNodeService osNodeService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected OpenstackFlowRuleService osFlowRuleService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected ClusterService clusterService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected LeadershipService leadershipService;

    /** Fake MAC address for virtual network subnet gateway. */
    private String dhcpServerMac = DHCP_SERVER_MAC_DEFAULT;

    private final PacketProcessor packetProcessor = new InternalPacketProcessor();
    private final OpenstackNodeListener osNodeListener = new InternalNodeEventListener();

    private final ExecutorService eventExecutor = newSingleThreadExecutor(
            groupedThreads(this.getClass().getSimpleName(), "event-handler"));

    private ApplicationId appId;
    private NodeId localNodeId;

    @Activate
    protected void activate() {
        appId = coreService.registerApplication(Constants.OPENSTACK_NETWORKING_APP_ID);
        localNodeId = clusterService.getLocalNode().id();
        osNodeService.addListener(osNodeListener);
        configService.registerProperties(getClass());
        packetService.addProcessor(packetProcessor, PacketProcessor.director(0));
        leadershipService.runForLeadership(appId.name());

        log.info("Started");
    }

    @Deactivate
    protected void deactivate() {
        packetService.removeProcessor(packetProcessor);
        osNodeService.removeListener(osNodeListener);
        configService.unregisterProperties(getClass(), false);
        leadershipService.withdraw(appId.name());
        eventExecutor.shutdown();

        log.info("Stopped");
    }

    @Modified
    protected void modified(ComponentContext context) {
        Dictionary<?, ?> properties = context.getProperties();
        String updatedMac;

        updatedMac = Tools.get(properties, DHCP_SERVER_MAC);

        if (!Strings.isNullOrEmpty(updatedMac) && !updatedMac.equals(dhcpServerMac)) {
            dhcpServerMac = updatedMac;
        }

        log.info("Modified");
    }

    private class InternalPacketProcessor implements PacketProcessor {

        @Override
        public void process(PacketContext context) {
            if (context.isHandled()) {
                return;
            }

            Ethernet ethPacket = context.inPacket().parsed();
            if (ethPacket == null || ethPacket.getEtherType() != Ethernet.TYPE_IPV4) {
                return;
            }
            IPv4 ipv4Packet = (IPv4) ethPacket.getPayload();
            if (ipv4Packet.getProtocol() != IPv4.PROTOCOL_UDP) {
                return;
            }
            UDP udpPacket = (UDP) ipv4Packet.getPayload();
            if (udpPacket.getDestinationPort() != UDP.DHCP_SERVER_PORT ||
                    udpPacket.getSourcePort() != UDP.DHCP_CLIENT_PORT) {
                return;
            }

            DHCP dhcpPacket = (DHCP) udpPacket.getPayload();

            eventExecutor.execute(() -> processDhcp(context, dhcpPacket));
        }

        private void processDhcp(PacketContext context, DHCP dhcpPacket) {
            if (dhcpPacket == null) {
                log.trace("DHCP packet without payload received, do nothing");
                return;
            }

            DHCP.MsgType inPacketType = getPacketType(dhcpPacket);
            if (inPacketType == null || dhcpPacket.getClientHardwareAddress() == null) {
                log.trace("Malformed DHCP packet received, ignore it");
                return;
            }

            MacAddress clientMac = MacAddress.valueOf(dhcpPacket.getClientHardwareAddress());
            InstancePort reqInstPort = instancePortService.instancePort(clientMac);
            if (reqInstPort == null) {
                log.trace("Failed to find host(MAC:{})", clientMac);
                return;
            }
            Ethernet ethPacket = context.inPacket().parsed();
            switch (inPacketType) {
                case DHCPDISCOVER:
                    processDhcpDiscover(context, clientMac, reqInstPort, ethPacket);
                    break;
                case DHCPREQUEST:
                    processDhcpRequest(context, clientMac, reqInstPort, ethPacket);
                    break;
                case DHCPRELEASE:
                    log.trace("DHCP RELEASE received from {}", clientMac);
                    // do nothing
                    break;
                default:
                    break;
            }
        }

        private void processDhcpDiscover(PacketContext context, MacAddress clientMac,
                                         InstancePort instPort, Ethernet ethPacket) {
            log.trace("DHCP DISCOVER received from {}", clientMac);
            Ethernet discoverReply = buildReply(ethPacket,
                                                (byte) DHCPOFFER.getValue(),
                                                instPort);
            sendReply(context, discoverReply);
            log.trace("DHCP OFFER({}) is sent for {}", instPort.ipAddress(), clientMac);
        }

        private void processDhcpRequest(PacketContext context, MacAddress clientMac,
                                        InstancePort instPort, Ethernet ethPacket) {
            log.trace("DHCP REQUEST received from {}", clientMac);
            Ethernet requestReply = buildReply(ethPacket,
                                                (byte) DHCPACK.getValue(),
                                                instPort);
            sendReply(context, requestReply);
            log.trace("DHCP ACK({}) is sent for {}", instPort.ipAddress(), clientMac);
        }

        private DHCP.MsgType getPacketType(DHCP dhcpPacket) {
            DhcpOption optType = dhcpPacket.getOption(OptionCode_MessageType);
            if (optType == null) {
                log.trace("DHCP packet with no message type, ignore it");
                return null;
            }

            DHCP.MsgType inPacketType = DHCP.MsgType.getType(optType.getData()[0]);
            if (inPacketType == null) {
                log.trace("DHCP packet with no packet type, ignore it");
            }
            return inPacketType;
        }

        private Ethernet buildReply(Ethernet ethRequest, byte packetType,
                                    InstancePort reqInstPort) {
            log.trace("Build for DHCP reply msg for instance port {}", reqInstPort.toString());
            Port osPort = osNetworkService.port(reqInstPort.portId());
            if (osPort == null) {
                log.error("Failed to retrieve openstack port information for instance port {}",
                        reqInstPort.toString());
                return null;
            }
            // pick one IP address to make a reply
            IP fixedIp = osPort.getFixedIps().stream().findFirst().get();
            Subnet osSubnet = osNetworkService.subnet(fixedIp.getSubnetId());

            Ethernet ethReply = new Ethernet();
            ethReply.setSourceMACAddress(dhcpServerMac);
            ethReply.setDestinationMACAddress(ethRequest.getSourceMAC());
            ethReply.setEtherType(Ethernet.TYPE_IPV4);

            IPv4 ipv4Request = (IPv4) ethRequest.getPayload();
            IPv4 ipv4Reply = new IPv4();

            ipv4Reply.setSourceAddress(
                    clusterService.getLocalNode().ip().getIp4Address().toString());
            ipv4Reply.setDestinationAddress(reqInstPort.ipAddress().getIp4Address().toInt());
            ipv4Reply.setTtl(PACKET_TTL);

            UDP udpRequest = (UDP) ipv4Request.getPayload();
            UDP udpReply = new UDP();
            udpReply.setSourcePort((byte) UDP.DHCP_SERVER_PORT);
            udpReply.setDestinationPort((byte) UDP.DHCP_CLIENT_PORT);

            DHCP dhcpRequest = (DHCP) udpRequest.getPayload();
            DHCP dhcpReply = buildDhcpReply(
                    dhcpRequest,
                    packetType,
                    reqInstPort.ipAddress().getIp4Address(),
                    osSubnet);

            udpReply.setPayload(dhcpReply);
            ipv4Reply.setPayload(udpReply);
            ethReply.setPayload(ipv4Reply);

            return ethReply;
        }

        private void sendReply(PacketContext context, Ethernet ethReply) {
            if (ethReply == null) {
                return;
            }
            ConnectPoint srcPoint = context.inPacket().receivedFrom();
            TrafficTreatment treatment = DefaultTrafficTreatment
                    .builder()
                    .setOutput(srcPoint.port())
                    .build();

            packetService.emit(new DefaultOutboundPacket(
                    srcPoint.deviceId(),
                    treatment,
                    ByteBuffer.wrap(ethReply.serialize())));
            context.block();
        }

        private DHCP buildDhcpReply(DHCP request, byte msgType, Ip4Address yourIp,
                                    Subnet osSubnet) {
            Ip4Address gatewayIp = clusterService.getLocalNode().ip().getIp4Address();
            int subnetPrefixLen = IpPrefix.valueOf(osSubnet.getCidr()).prefixLength();

            DHCP dhcpReply = new DHCP();
            dhcpReply.setOpCode(DHCP.OPCODE_REPLY);
            dhcpReply.setHardwareType(DHCP.HWTYPE_ETHERNET);
            dhcpReply.setHardwareAddressLength(HARDWARE_ADDR_LENGTH);
            dhcpReply.setTransactionId(request.getTransactionId());
            dhcpReply.setFlags(request.getFlags());
            dhcpReply.setYourIPAddress(yourIp.toInt());
            dhcpReply.setServerIPAddress(gatewayIp.toInt());
            dhcpReply.setClientHardwareAddress(request.getClientHardwareAddress());

            List<DhcpOption> options = Lists.newArrayList();

            // message type
            options.add(doMsgType(msgType));

            // server identifier
            options.add(doServerId(gatewayIp));

            // lease time
            options.add(doLeaseTime());

            // subnet mask
            options.add(doSubnetMask(subnetPrefixLen));

            // broadcast address
            options.add(doBroadcastAddr(yourIp, subnetPrefixLen));

            // domain server
            options.add(doDomainServer(osSubnet));

            // mtu
            options.add(doMtu(osSubnet));

            // classless static route
            if (!osSubnet.getHostRoutes().isEmpty()) {
                options.add(doClasslessSr(osSubnet));
            }

            // Sets the default router address up.
            // Performs only if the gateway is set in subnet.
            if (!Strings.isNullOrEmpty(osSubnet.getGateway())) {
                options.add(doRouterAddr(osSubnet));
            }

            // end option
            options.add(doEnd());

            dhcpReply.setOptions(options);
            return dhcpReply;
        }

        private DhcpOption doMsgType(byte msgType) {
            DhcpOption option = new DhcpOption();
            option.setCode(OptionCode_MessageType.getValue());
            option.setLength((byte) 1);
            byte[] optionData = {msgType};
            option.setData(optionData);
            return option;
        }

        private DhcpOption doServerId(IpAddress gatewayIp) {
            DhcpOption option = new DhcpOption();
            option.setCode(OptionCode_DHCPServerIp.getValue());
            option.setLength(DHCP_OPTION_DATA_LENGTH);
            option.setData(gatewayIp.toOctets());
            return option;
        }

        private DhcpOption doLeaseTime() {
            DhcpOption option = new DhcpOption();
            option.setCode(OptionCode_LeaseTime.getValue());
            option.setLength(DHCP_OPTION_DATA_LENGTH);
            option.setData(DHCP_DATA_LEASE_INFINITE);
            return option;
        }

        private DhcpOption doSubnetMask(int subnetPrefixLen) {
            Ip4Address subnetMask = Ip4Address.makeMaskPrefix(subnetPrefixLen);
            DhcpOption option = new DhcpOption();
            option.setCode(OptionCode_SubnetMask.getValue());
            option.setLength(DHCP_OPTION_DATA_LENGTH);
            option.setData(subnetMask.toOctets());
            return option;
        }

        private DhcpOption doBroadcastAddr(Ip4Address yourIp, int subnetPrefixLen) {
            Ip4Address broadcast = Ip4Address.makeMaskedAddress(yourIp, subnetPrefixLen);
            DhcpOption option = new DhcpOption();
            option.setCode(OptionCode_BroadcastAddress.getValue());
            option.setLength(DHCP_OPTION_DATA_LENGTH);
            option.setData(broadcast.toOctets());
            return option;
        }

        private DhcpOption doDomainServer(Subnet osSubnet) {
            DhcpOption option = new DhcpOption();

            List<String> dnsServers = osSubnet.getDnsNames();
            option.setCode(OptionCode_DomainServer.getValue());

            if (dnsServers.isEmpty()) {
                option.setLength((byte) DHCP_OPTION_DNS_LENGTH);
                ByteBuffer dnsByteBuf = ByteBuffer.allocate(DHCP_OPTION_DNS_LENGTH);
                dnsByteBuf.put(DEFAULT_PRIMARY_DNS.toOctets());
                dnsByteBuf.put(DEFAULT_SECONDARY_DNS.toOctets());

                option.setData(dnsByteBuf.array());
            } else {
                int dnsLength = 4 * dnsServers.size();

                option.setLength((byte) dnsLength);

                ByteBuffer dnsByteBuf = ByteBuffer.allocate(DHCP_OPTION_DNS_LENGTH);

                for (String dnsServer : dnsServers) {
                    dnsByteBuf.put(IpAddress.valueOf(dnsServer).toOctets());
                }
                option.setData(dnsByteBuf.array());
            }

            return option;
        }

        private DhcpOption doMtu(Subnet osSubnet) {
            DhcpOption option = new DhcpOption();
            option.setCode(DHCP_OPTION_MTU);
            option.setLength((byte) DHCP_OPTION_MTU_LENGTH);
            Network osNetwork = osNetworkService.network(osSubnet.getNetworkId());
            checkNotNull(osNetwork);
            checkNotNull(osNetwork.getMTU());

            option.setData(ByteBuffer.allocate(DHCP_OPTION_MTU_LENGTH)
                            .putShort(osNetwork.getMTU().shortValue()).array());

            return option;
        }

        private DhcpOption doClasslessSr(Subnet osSubnet) {
            DhcpOption option = new DhcpOption();
            option.setCode(OptionCode_Classless_Static_Route.getValue());

            int hostRoutesSize = hostRoutesSize(ImmutableList.copyOf(osSubnet.getHostRoutes()));
            if (hostRoutesSize == 0) {
                throw new IllegalArgumentException("Illegal CIDR hostRoutesSize value!");
            }

            log.trace("hostRouteSize: {}", hostRoutesSize);

            option.setLength((byte) hostRoutesSize);
            ByteBuffer hostRouteByteBuf = ByteBuffer.allocate(hostRoutesSize);

            osSubnet.getHostRoutes().forEach(h -> {
                log.debug("processing host route information: {}", h.toString());

                IpPrefix ipPrefix = IpPrefix.valueOf(h.getDestination());

                hostRouteByteBuf.put(Objects.requireNonNull(bytesDestinationDescriptor(ipPrefix)));

                hostRouteByteBuf.put(Ip4Address.valueOf(h.getNexthop()).toOctets());
            });

            option.setData(hostRouteByteBuf.array());
            return option;
        }

        private DhcpOption doRouterAddr(Subnet osSubnet) {
            DhcpOption option = new DhcpOption();
            option.setCode(OptionCode_RouterAddress.getValue());
            option.setLength(DHCP_OPTION_DATA_LENGTH);
            option.setData(Ip4Address.valueOf(osSubnet.getGateway()).toOctets());
            return option;
        }

        private DhcpOption doEnd() {
            DhcpOption option = new DhcpOption();
            option.setCode(OptionCode_END.getValue());
            option.setLength((byte) 1);
            return option;
        }

        private int hostRoutesSize(List<HostRoute> hostRoutes) {
            int size = 0;
            int preFixLen;

            for (HostRoute h : hostRoutes) {
                preFixLen = IpPrefix.valueOf(h.getDestination()).prefixLength();
                if (Math.max(V4_CIDR_LOWER_BOUND, preFixLen) == V4_CIDR_LOWER_BOUND ||
                        Math.min(preFixLen, V4_CIDR_UPPER_BOUND) == V4_CIDR_UPPER_BOUND) {
                    throw new IllegalArgumentException("Illegal CIDR length value!");
                }

                for (int i = 0; i <= V4_BYTE_SIZE; i++) {
                    if (preFixLen == Math.min(preFixLen, i * OCTET_BIT_LENGTH)) {
                        size = size + i + 1 + PADDING_SIZE;
                        break;
                    }
                }
            }
            return size;
        }

        private byte[] bytesDestinationDescriptor(IpPrefix ipPrefix) {
            ByteBuffer byteBuffer;
            int prefixLen = ipPrefix.prefixLength();

            // retrieve ipPrefix to the destination descriptor format
            // ex) 10.1.1.0/24 -> [10,1,1,0]
            String[] ipPrefixString = ipPrefix.getIp4Prefix().toString()
                    .split("/")[0]
                    .split("\\.");

            // retrieve destination descriptor and put this to byte buffer
            // according to RFC 3442
            // ex) 0.0.0.0/0 -> 0
            // ex) 10.0.0.0/8 -> 8.10
            // ex) 10.17.0.0/16 -> 16.10.17
            // ex) 10.27.129.0/24 -> 24.10.27.129
            // ex) 10.229.0.128/25 -> 25.10.229.0.128
            for (int i = 0; i <= V4_BYTE_SIZE; i++) {
                if (prefixLen == Math.min(prefixLen, i * OCTET_BIT_LENGTH)) {
                    byteBuffer = ByteBuffer.allocate(i + 1);
                    byteBuffer.put((byte) prefixLen);

                    for (int j = 0; j < i; j++) {
                        byteBuffer.put((byte) Integer.parseInt(ipPrefixString[j]));
                    }
                    return byteBuffer.array();
                }
            }

            return null;
        }
    }

    private class InternalNodeEventListener implements OpenstackNodeListener {
        @Override
        public boolean isRelevant(OpenstackNodeEvent event) {
            return event.subject().type() == COMPUTE;
        }

        private boolean isRelevantHelper() {
            return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
        }

        @Override
        public void event(OpenstackNodeEvent event) {
            OpenstackNode osNode = event.subject();
            switch (event.type()) {
                case OPENSTACK_NODE_COMPLETE:
                    eventExecutor.execute(() -> processNodeCompletion(osNode));
                    break;
                case OPENSTACK_NODE_INCOMPLETE:
                    eventExecutor.execute(() -> processNodeIncompletion(osNode));
                    break;
                case OPENSTACK_NODE_CREATED:
                case OPENSTACK_NODE_UPDATED:
                case OPENSTACK_NODE_REMOVED:
                default:
                    break;
            }
        }

        private void processNodeCompletion(OpenstackNode osNode) {
            if (!isRelevantHelper()) {
                return;
            }
            setDhcpRule(osNode, true);
        }

        private void processNodeIncompletion(OpenstackNode osNode) {
            if (!isRelevantHelper()) {
                return;
            }
            setDhcpRule(osNode, false);
        }

        private void setDhcpRule(OpenstackNode openstackNode, boolean install) {
            TrafficSelector selector = DefaultTrafficSelector.builder()
                    .matchEthType(Ethernet.TYPE_IPV4)
                    .matchIPProtocol(IPv4.PROTOCOL_UDP)
                    .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
                    .matchUdpSrc(TpPort.tpPort(UDP.DHCP_CLIENT_PORT))
                    .build();

            TrafficTreatment treatment = DefaultTrafficTreatment.builder()
                    .punt()
                    .build();

            osFlowRuleService.setRule(
                    appId,
                    openstackNode.intgBridge(),
                    selector,
                    treatment,
                    PRIORITY_DHCP_RULE,
                    DHCP_TABLE,
                    install);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        android:id="@+id/back_toolbar"
        layout="@layout/simple_toolbar" />

    <android.support.v7.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/activity_find_recycler_view"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</LinearLayout>


text:
/**
 * Better alternative to "keyof" in TypeScript.
 * Key of T and it's all strings.
 */
export type Key<T> = Extract<keyof T, string>;

export type Diff<T, U> = T extends U ? never : T;

export type NonNullable<T> = Diff<T, null | undefined>;

export type Nullable<T> = T | null | undefined;

export type ObjectMap = { [key: string]: any };


text:
namespace net {

class CryptoHandshakeMessage;
class QuicSession;

// Crypto handshake messages in QUIC take place over a reserved
// reliable stream with the id 1.  Each endpoint (client and server)
// will allocate an instance of a subclass of QuicCryptoStream
// to send and receive handshake messages.  (In the normal 1-RTT
// handshake, the client will send a client hello, CHLO, message.
// The server will receive this message and respond with a server
// hello message, SHLO.  At this point both sides will have established
// a crypto context they can use to send encrypted messages.
//
// For more details: http://goto.google.com/quic-crypto
class NET_EXPORT_PRIVATE QuicCryptoStream
    : public ReliableQuicStream,
      public CryptoFramerVisitorInterface {
 public:
  explicit QuicCryptoStream(QuicSession* session);

  // CryptoFramerVisitorInterface implementation
  virtual void OnError(CryptoFramer* framer) OVERRIDE;
  virtual void OnHandshakeMessage(
      const CryptoHandshakeMessage& message) OVERRIDE;

  // ReliableQuicStream implementation
  virtual uint32 ProcessData(const char* data, uint32 data_len) OVERRIDE;

  // Sends |message| to the peer.
  // TODO(wtc): return a success/failure status.
  void SendHandshakeMessage(const CryptoHandshakeMessage& message);

  bool encryption_established() { return encryption_established_; }
  bool handshake_confirmed() { return handshake_confirmed_; }

  const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const;

 protected:
  // Closes the connection
  void CloseConnection(QuicErrorCode error);
  void CloseConnectionWithDetails(QuicErrorCode error, const string& details);

  bool encryption_established_;
  bool handshake_confirmed_;

  QuicCryptoNegotiatedParameters crypto_negotiated_params_;

 private:
  CryptoFramer crypto_framer_;

  DISALLOW_COPY_AND_ASSIGN(QuicCryptoStream);
};

}  // namespace net

#endif  // NET_QUIC_QUIC_CRYPTO_STREAM_H_


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Pleurothallis brevipes H.Focke

### Remarks
null


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Package org.jboss.netty.logging (The Netty Project API Reference (3.2.5.Final))
</TITLE>

<META NAME="date" CONTENT="2011-08-02">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.jboss.netty.logging

Packages that use org.jboss.netty.logging

org.jboss.netty.handler.logging
Logs a ChannelEvent for debugging purpose
 using an InternalLogger.

org.jboss.netty.logging
Simplistic internal-use-only logging layer which allows a user to
 decide what logging framework Netty should use.

Classes in org.jboss.netty.logging used by org.jboss.netty.handler.logging

InternalLogger

          Internal-use-only logger used by Netty.

InternalLogLevel

          The log level that InternalLogger can log at.

Classes in org.jboss.netty.logging used by org.jboss.netty.logging

InternalLogger

          Internal-use-only logger used by Netty.

InternalLoggerFactory

          Creates an InternalLogger or changes the default factory
 implementation.

InternalLogLevel

          The log level that InternalLogger can log at.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2008-2011 JBoss, a division of Red Hat, Inc.. All Rights Reserved.


text:
package tutorial_2;

import java.util.Scanner;

public class IntEven {

  /**
   * Returns true if given integer is even, false otherwise * @param number
   */
  public static boolean isEven(int number) {
    // boolean isEven = (number % 2 == 0) ? true : false;
    // return isEven;
    return (number % 2 == 0);
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int num = sc.nextInt();
    sc.close();
    System.out.println(isEven(num));
  }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("organisations", "0001_initial")]

    operations = [
        migrations.AddField(
            model_name="organisation",
            name="organisation_type",
            field=models.CharField(blank=True, max_length=255),
        )
    ]


text:
static NSString * const kTelephoneScheme = @"tel";
static NSString * const kTelephonePromptScheme = @"telprompt";

// Share Constants
static NSString * const kMoPubShareScheme = @"mopubshare";
static NSString * const kMoPubShareTweetHost = @"tweet";

// Commands Constants
static NSString * const kMoPubURLScheme = @"mopub";
static NSString * const kMoPubCloseHost = @"close";
static NSString * const kMoPubFinishLoadHost = @"finishLoad";
static NSString * const kMoPubFailLoadHost = @"failLoad";
static NSString * const kMoPubPrecacheCompleteHost = @"precacheComplete";
static NSString * const kMoPubRewardedVideoEndedHost = @"rewardedVideoEnded";

@implementation NSURL (MPAdditions)

- (NSString *)mp_queryParameterForKey:(NSString *)key
{
    NSArray *queryElements = [self.query componentsSeparatedByString:@"&"];
    for (NSString *element in queryElements) {
        NSArray *keyAndValue = [element componentsSeparatedByString:@"="];
        if (keyAndValue.count >= 2 &&
            [[keyAndValue objectAtIndex:0] isEqualToString:key] &&
            [[keyAndValue objectAtIndex:1] length] > 0) {
            return [[keyAndValue objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
    }
    return nil;
}

- (NSArray *)mp_queryParametersForKey:(NSString *)key
{
    NSMutableArray *matchingParameters = [NSMutableArray array];
    NSArray *queryElements = [self.query componentsSeparatedByString:@"&"];
    for (NSString *element in queryElements) {
        NSArray *keyAndValue = [element componentsSeparatedByString:@"="];
        if (keyAndValue.count >= 2 &&
            [[keyAndValue objectAtIndex:0] isEqualToString:key] &&
            [[keyAndValue objectAtIndex:1] length] > 0) {
            [matchingParameters addObject:[[keyAndValue objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    return [NSArray arrayWithArray:matchingParameters];
}

- (NSDictionary *)mp_queryAsDictionary
{
    NSMutableDictionary *queryDict = [NSMutableDictionary dictionary];
    NSArray *queryElements = [self.query componentsSeparatedByString:@"&"];
    for (NSString *element in queryElements) {
        NSArray *keyVal = [element componentsSeparatedByString:@"="];
        if (keyVal.count >= 2) {
            NSString *key = [keyVal objectAtIndex:0];
            NSString *value = [keyVal objectAtIndex:1];
            [queryDict setObject:[value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                          forKey:key];
        }
    }
    return queryDict;
}

- (BOOL)mp_hasTelephoneScheme
{
    return [[[self scheme] lowercaseString] isEqualToString:kTelephoneScheme];
}

- (BOOL)mp_hasTelephonePromptScheme
{
    return [[[self scheme] lowercaseString] isEqualToString:kTelephonePromptScheme];
}

- (BOOL)mp_isSafeForLoadingWithoutUserAction
{
    return [[self scheme].lowercaseString isEqualToString:@"http"] ||
        [[self scheme].lowercaseString isEqualToString:@"https"] ||
        [[self scheme].lowercaseString isEqualToString:@"about"];
}

- (BOOL)mp_isMoPubScheme
{
    return [[self scheme] isEqualToString:kMoPubURLScheme];
}

- (MPMoPubShareHostCommand)mp_MoPubShareHostCommand
{
    NSString *host = [self host];
    if (![self mp_isMoPubShareScheme]) {
        return MPMoPubShareHostCommandUnrecognized;
    } else if ([host isEqualToString:kMoPubShareTweetHost]) {
        return MPMoPubShareHostCommandTweet;
    } else {
        return MPMoPubShareHostCommandUnrecognized;
    }
}

- (MPMoPubHostCommand)mp_mopubHostCommand
{
    NSString *host = [self host];
    if (![self mp_isMoPubScheme]) {
        return MPMoPubHostCommandUnrecognized;
    } else if ([host isEqualToString:kMoPubCloseHost]) {
        return MPMoPubHostCommandClose;
    } else if ([host isEqualToString:kMoPubFinishLoadHost]) {
        return MPMoPubHostCommandFinishLoad;
    } else if ([host isEqualToString:kMoPubFailLoadHost]) {
        return MPMoPubHostCommandFailLoad;
    } else if ([host isEqualToString:kMoPubPrecacheCompleteHost]) {
        return MPMoPubHostCommandPrecacheComplete;
    } else if ([host isEqualToString:kMoPubRewardedVideoEndedHost]) {
        return MPMoPubHostCommandRewardedVideoEnded;
    } else {
        return MPMoPubHostCommandUnrecognized;
    }
}

- (BOOL)mp_isMoPubShareScheme
{
    return [[self scheme] isEqualToString:kMoPubShareScheme];
}

@end


text:
/* eslint-disable react/no-array-index-key */

import React from 'react';
import { Text, View, StyleSheet } from '@react-pdf/renderer';

import Title from './Title';
import List, { Item } from './List';

const styles = StyleSheet.create({
  title: {
    fontFamily: 'Lato Bold',
    fontSize: 11,
    marginBottom: 10,
  },
  skills: {
    fontFamily: 'Lato',
    fontSize: 10,
    marginBottom: 10,
  },
});

const SkillEntry = ({ name, skills }) => (
  <View>
    <Text style={styles.title}>{name}</Text>
    <List>
      {skills.map((skill, i) => (
        <Item key={i}>{skill}</Item>
      ))}
    </List>
  </View>
);

const Skills = () => (
  <View>
    <Title>Skills</Title>
    <SkillEntry
      name="Combat Abilities"
      skills={[
        'Completed Jedi Master training and built a lightsaber from scratch in order to do battle against the Empire',
        'Defeated the Rancor and rescued Princess Leia from Jabba the Hutt',
        'Competent fighter pilot as well as an excelent shot with nearly any weapon',
      ]}
    />
  </View>
);

export default Skills;


text:
namespace Envoy {
namespace Api {
namespace {

using WSAMSGPtr = std::unique_ptr<WSAMSG>;

struct wsamsgResult {
  WSAMSGPtr wsamsg_;
  std::vector<WSABUF> buff_data_;
};

std::vector<WSABUF> iovecToWSABUF(const iovec* vec, int in_vec) {

  DWORD num_vec = 0;
  for (int i = 0; i < in_vec; i++) {
    size_t cur_len = vec[i].iov_len;
    num_vec++;
    while (cur_len > DWORD_MAX) {
      num_vec++;
      cur_len -= DWORD_MAX;
    }
  }

  std::vector<WSABUF> buff(num_vec);
  auto it = buff.begin();

  std::vector<iovec> vecs(vec, vec + in_vec);
  for (const auto& vec : vecs) {
    auto chunk = (CHAR*)vec.iov_base;
    size_t chunk_len = vec.iov_len;
    // There is the case that the chunk does not fit into a single WSABUF buffer
    // this is the case because sizeof(size_t) > sizeof(DWORD).
    // In this case we split the chunk into multiple WSABUF buffers
    auto remaining_data = chunk_len;
    do {
      (*it).buf = chunk;
      (*it).len = (remaining_data > DWORD_MAX) ? DWORD_MAX : static_cast<ULONG>(chunk_len);
      remaining_data -= (*it).len;
      chunk += (*it).len;
      it++;
    } while (remaining_data > 0);
  }
  return buff;
}

LPFN_WSARECVMSG getFnPtrWSARecvMsg() {
  LPFN_WSARECVMSG recvmsg_fn_ptr = NULL;
  GUID recvmsg_guid = WSAID_WSARECVMSG;
  SOCKET sock = INVALID_SOCKET;
  DWORD bytes_received = 0;

  sock = socket(AF_INET6, SOCK_DGRAM, 0);

  RELEASE_ASSERT(
      WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &recvmsg_guid, sizeof(recvmsg_guid),
               &recvmsg_fn_ptr, sizeof(recvmsg_fn_ptr), &bytes_received, NULL,
               NULL) != SOCKET_ERROR,
      "WSAIoctl SIO_GET_EXTENSION_FUNCTION_POINTER for WSARecvMsg failed, not implemented?");

  closesocket(sock);

  return recvmsg_fn_ptr;
}

wsamsgResult msghdrToWSAMSG(const msghdr* msg) {
  WSAMSGPtr wsa_msg(new WSAMSG);

  wsa_msg->name = reinterpret_cast<SOCKADDR*>(msg->msg_name);
  wsa_msg->namelen = msg->msg_namelen;
  auto buffer = iovecToWSABUF(msg->msg_iov, msg->msg_iovlen);
  wsa_msg->lpBuffers = buffer.data();
  wsa_msg->dwBufferCount = buffer.size();

  WSABUF control;
  control.buf = reinterpret_cast<CHAR*>(msg->msg_control);
  control.len = msg->msg_controllen;
  wsa_msg->Control = control;
  wsa_msg->dwFlags = msg->msg_flags;

  return wsamsgResult{std::move(wsa_msg), std::move(buffer)};
}

} // namespace

SysCallIntResult OsSysCallsImpl::bind(os_fd_t sockfd, const sockaddr* addr, socklen_t addrlen) {
  const int rc = ::bind(sockfd, addr, addrlen);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallIntResult OsSysCallsImpl::chmod(const std::string& path, mode_t mode) {
  const int rc = ::_chmod(path.c_str(), mode);
  return {rc, rc != -1 ? 0 : errno};
}

SysCallIntResult OsSysCallsImpl::ioctl(os_fd_t sockfd, unsigned long int request, void* argp) {
  const int rc = ::ioctlsocket(sockfd, request, static_cast<u_long*>(argp));
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallIntResult OsSysCallsImpl::close(os_fd_t fd) {
  const int rc = ::closesocket(fd);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallSizeResult OsSysCallsImpl::writev(os_fd_t fd, const iovec* iov, int num_iov) {
  DWORD bytes_sent;
  auto buffer = iovecToWSABUF(iov, num_iov);

  const int rc = ::WSASend(fd, buffer.data(), buffer.size(), &bytes_sent, 0, nullptr, nullptr);
  if (SOCKET_FAILURE(rc)) {
    return {-1, ::WSAGetLastError()};
  }
  return {bytes_sent, 0};
}

SysCallSizeResult OsSysCallsImpl::readv(os_fd_t fd, const iovec* iov, int num_iov) {
  DWORD bytes_received;
  DWORD flags = 0;
  auto buffer = iovecToWSABUF(iov, num_iov);

  const int rc =
      ::WSARecv(fd, buffer.data(), buffer.size(), &bytes_received, &flags, nullptr, nullptr);
  if (SOCKET_FAILURE(rc)) {
    return {-1, ::WSAGetLastError()};
  }
  return {bytes_received, 0};
}

SysCallSizeResult OsSysCallsImpl::recv(os_fd_t socket, void* buffer, size_t length, int flags) {
  const ssize_t rc = ::recv(socket, static_cast<char*>(buffer), length, flags);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallSizeResult OsSysCallsImpl::recvmsg(os_fd_t sockfd, msghdr* msg, int flags) {
  DWORD bytes_received;
  LPFN_WSARECVMSG recvmsg_fn_ptr = getFnPtrWSARecvMsg();
  wsamsgResult wsamsg = msghdrToWSAMSG(msg);
  // Windows supports only a single flag on input to WSARecvMsg
  wsamsg.wsamsg_->dwFlags = flags & MSG_PEEK;
  const int rc = recvmsg_fn_ptr(sockfd, wsamsg.wsamsg_.get(), &bytes_received, nullptr, nullptr);
  if (rc == SOCKET_ERROR) {
    return {-1, ::WSAGetLastError()};
  }
  msg->msg_namelen = wsamsg.wsamsg_->namelen;
  msg->msg_flags = wsamsg.wsamsg_->dwFlags;
  msg->msg_controllen = wsamsg.wsamsg_->Control.len;
  return {bytes_received, 0};
}

SysCallIntResult OsSysCallsImpl::recvmmsg(os_fd_t sockfd, struct mmsghdr* msgvec, unsigned int vlen,
                                          int flags, struct timespec* timeout) {
  NOT_IMPLEMENTED_GCOVR_EXCL_LINE;
}

bool OsSysCallsImpl::supportsMmsg() const {
  // Windows doesn't support it.
  return false;
}

bool OsSysCallsImpl::supportsUdpGro() const {
  // Windows doesn't support it.
  return false;
}

bool OsSysCallsImpl::supportsUdpGso() const {
  // Windows doesn't support it.
  return false;
}

bool OsSysCallsImpl::supportsIpTransparent() const {
  // Windows doesn't support it.
  return false;
}

SysCallIntResult OsSysCallsImpl::ftruncate(int fd, off_t length) {
  const int rc = ::_chsize_s(fd, length);
  return {rc, rc == 0 ? 0 : errno};
}

SysCallPtrResult OsSysCallsImpl::mmap(void* addr, size_t length, int prot, int flags, int fd,
                                      off_t offset) {
  PANIC("mmap not implemented on Windows");
}

SysCallIntResult OsSysCallsImpl::stat(const char* pathname, struct stat* buf) {
  const int rc = ::stat(pathname, buf);
  return {rc, rc != -1 ? 0 : errno};
}

SysCallIntResult OsSysCallsImpl::setsockopt(os_fd_t sockfd, int level, int optname,
                                            const void* optval, socklen_t optlen) {
  const int rc = ::setsockopt(sockfd, level, optname, static_cast<const char*>(optval), optlen);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallIntResult OsSysCallsImpl::getsockopt(os_fd_t sockfd, int level, int optname, void* optval,
                                            socklen_t* optlen) {
  const int rc = ::getsockopt(sockfd, level, optname, static_cast<char*>(optval), optlen);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallSocketResult OsSysCallsImpl::socket(int domain, int type, int protocol) {
  const os_fd_t rc = ::socket(domain, type, protocol);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallSizeResult OsSysCallsImpl::sendmsg(os_fd_t sockfd, const msghdr* msg, int flags) {
  DWORD bytes_received;
  // if overlapped and/or completion routines are supported adjust the arguments accordingly
  wsamsgResult wsamsg = msghdrToWSAMSG(msg);
  const int rc =
      ::WSASendMsg(sockfd, wsamsg.wsamsg_.get(), flags, &bytes_received, nullptr, nullptr);
  if (rc == SOCKET_ERROR) {
    return {-1, ::WSAGetLastError()};
  }
  return {bytes_received, 0};
}

SysCallIntResult OsSysCallsImpl::getsockname(os_fd_t sockfd, sockaddr* addr, socklen_t* addrlen) {
  const int rc = ::getsockname(sockfd, addr, addrlen);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallIntResult OsSysCallsImpl::gethostname(char* name, size_t length) {
  const int rc = ::gethostname(name, length);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallIntResult OsSysCallsImpl::getpeername(os_fd_t sockfd, sockaddr* name, socklen_t* namelen) {
  const int rc = ::getpeername(sockfd, name, namelen);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallIntResult OsSysCallsImpl::setsocketblocking(os_fd_t sockfd, bool blocking) {
  u_long io_mode = blocking ? 0 : 1;
  const int rc = ::ioctlsocket(sockfd, FIONBIO, &io_mode);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallIntResult OsSysCallsImpl::connect(os_fd_t sockfd, const sockaddr* addr, socklen_t addrlen) {
  const int rc = ::connect(sockfd, addr, addrlen);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallIntResult OsSysCallsImpl::shutdown(os_fd_t sockfd, int how) {
  const int rc = ::shutdown(sockfd, how);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallIntResult OsSysCallsImpl::socketpair(int domain, int type, int protocol, os_fd_t sv[2]) {
  if (sv == nullptr) {
    return {SOCKET_ERROR, SOCKET_ERROR_INVAL};
  }

  sv[0] = sv[1] = INVALID_SOCKET;

  SysCallSocketResult socket_result = socket(domain, type, protocol);
  if (SOCKET_INVALID(socket_result.rc_)) {
    return {SOCKET_ERROR, socket_result.errno_};
  }

  os_fd_t listener = socket_result.rc_;

  typedef union {
    struct sockaddr_storage sa;
    struct sockaddr_in in;
    struct sockaddr_in6 in6;
  } sa_union;
  sa_union a = {};
  socklen_t sa_size = sizeof(a);

  a.sa.ss_family = domain;
  if (domain == AF_INET) {
    a.in.sin_addr.s_addr = ::htonl(INADDR_LOOPBACK);
    a.in.sin_port = 0;
  } else if (domain == AF_INET6) {
    a.in6.sin6_addr = in6addr_loopback;
    a.in6.sin6_port = 0;
  } else {
    return {SOCKET_ERROR, SOCKET_ERROR_INVAL};
  }

  auto onErr = [this, listener, sv]() -> void {
    ::closesocket(listener);
    ::closesocket(sv[0]);
    ::closesocket(sv[1]);
    sv[0] = INVALID_SOCKET;
    sv[1] = INVALID_SOCKET;
  };

  SysCallIntResult int_result = bind(listener, reinterpret_cast<sockaddr*>(&a), sa_size);
  if (int_result.rc_ == SOCKET_ERROR) {
    onErr();
    return int_result;
  }

  int_result = listen(listener, 1);
  if (int_result.rc_ == SOCKET_ERROR) {
    onErr();
    return int_result;
  }

  socket_result = socket(domain, type, protocol);
  if (SOCKET_INVALID(socket_result.rc_)) {
    onErr();
    return {SOCKET_ERROR, socket_result.errno_};
  }
  sv[0] = socket_result.rc_;

  a = {};
  int_result = getsockname(listener, reinterpret_cast<sockaddr*>(&a), &sa_size);
  if (int_result.rc_ == SOCKET_ERROR) {
    onErr();
    return int_result;
  }

  int_result = connect(sv[0], reinterpret_cast<sockaddr*>(&a), sa_size);
  if (int_result.rc_ == SOCKET_ERROR) {
    onErr();
    return int_result;
  }

  socket_result.rc_ = ::accept(listener, nullptr, nullptr);
  if (SOCKET_INVALID(socket_result.rc_)) {
    socket_result.errno_ = ::WSAGetLastError();
    onErr();
    return {SOCKET_ERROR, socket_result.errno_};
  }
  sv[1] = socket_result.rc_;

  ::closesocket(listener);
  return {0, 0};
}

SysCallIntResult OsSysCallsImpl::listen(os_fd_t sockfd, int backlog) {
  const int rc = ::listen(sockfd, backlog);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallSizeResult OsSysCallsImpl::write(os_fd_t sockfd, const void* buffer, size_t length) {
  const ssize_t rc = ::send(sockfd, static_cast<const char*>(buffer), length, 0);
  return {rc, rc != -1 ? 0 : ::WSAGetLastError()};
}

SysCallSocketResult OsSysCallsImpl::accept(os_fd_t sockfd, sockaddr* addr, socklen_t* addrlen) {
  const os_fd_t rc = ::accept(sockfd, addr, addrlen);
  if (SOCKET_INVALID(rc)) {
    return {rc, ::WSAGetLastError()};
  }

  setsocketblocking(rc, false);
  return {rc, 0};
}

} // namespace Api
} // namespace Envoy


text:
html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var,optgroup{font-style:inherit;font-weight:inherit;}del,ins{text-decoration:none;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:baseline;}sub{vertical-align:baseline;}legend{color:#000;}input,button,textarea,select,optgroup,option{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;}input,button,textarea,select{*font-size:100%;}

html, body {
    background-color: #efefef;
}
body {
    font: 1em "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
    text-align: left;
}

p {
    font-size: 14px;
    line-height: 20px;
    color: #313131;
    padding-bottom: 20px
}

strong {
    color: #313131;
    font-weight: bold;
}
em {
    font-style: italic;
}

a {
    color: #6c6159;
}
a img {
    border: none;
}
a:hover {
    text-decoration: underline;
}

button::-moz-focus-inner {
    padding: 0;
    border: none;
}
button {
    overflow: visible;
    width: auto;
    background-color: transparent;
    font-weight: bold;
}

caption {
    margin-bottom: 7px;
}
table, tr, th, td {
    border-collapse: collapse;
    border: 1px solid #d0dbb3;
}
table {
    width: 100%;
    margin: 10px 0 30px;
}
table th {
    font-weight: bold;
    background-color: #f1f7e2;
}
table th, table td {
    font-size: 12px;
    padding: 8px 10px;
}

fieldset {
    border: none;
}

abbr {
    border-bottom: 1px dotted #000;
    cursor: help;
}

.clear {
    clear: both;
    height: 0;
    font-size: 0;
    line-height: 0;
}
.clear_fix:after
{
    content: "\0020";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
* html .clear_fix
{
    height: 1%;
}
.clear_fix
{
    display: block;
}

#content {
    padding: 0 50px;
    margin: 0 auto;
    font-family: Arial, Helvetica, sans-serif;
    min-width: 970px;
}

#header {
    padding: 30px 30px 20px;
}

#header h1 {
    float: left;
}

.search {
    float: right;
}

#menu_profiler {
    border-right: 1px solid #dfdfdf;
}

#menu_profiler li {
    border-bottom: 1px solid #dfdfdf;
    position: relative;
    padding-bottom: 0;
    display: block;
    background-color: #f6f6f6;
}

#menu_profiler li a {
    color: #404040;
    display: block;
    font-size: 13px;
    text-transform: uppercase;
    text-decoration: none;
    cursor: pointer;
}

#menu_profiler li a span.label {
    display: block;
    padding: 20px 20px 16px 65px;
    min-height: 24px;
    _height: 24px;
}

#menu_profiler li a span.icon {
    display: block;
    position: absolute;
    left: 0;
    top: 12px;
    width: 60px;
    text-align: center;
}

#menu_profiler li.selected a,
#menu_profiler li a:hover {
    background: #d1d1d1 url(../images/profiler/bg_submenu.png) repeat-x 0 0;
}

#navigation div:first-child,
#menu_profiler li:first-child,
#menu_profiler li:first-child a,
#menu_profiler li:first-child a span.label {
    -moz-border-radius: 16px 0 0 0;
    -webkit-border-radius: 16px 0 0 0;
    border-radius: 16px 0 0 0;
}

#menu_profiler li a span.count {
    padding: 0;
    position: absolute;
    right: 10px;
    top: 20px;
}

#collector_wrapper {
    float: left;
    width: 100%;
}

#collector_content {
    margin-left: 250px;
    padding: 40px 50px;
}

#navigation {
    float: left;
    width: 250px;
    margin-left: -100%;
}

#collector_content table td {
    background-color: white;
}

h1 {
    font-family: Georgia, "Times New Roman", Times, serif;
    color: #404040;
}
h2, h3 {
    font-weight: bold;
    margin-bottom: 20px;
}

li {
    padding-bottom: 10px;

}

#main {
    -moz-border-radius: 16px;
    -webkit-border-radius: 16px;
    border-radius: 16px;
    margin-bottom: 20px;
}

#menu_profiler span.count span {
    display: inline-block;
    background-color: #aacd4e;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 6px;
    padding: 4px;
    color: #fff;
    margin-right: 2px;
    font-size: 11px;
}

#resume {
    background-color: #f6f6f6;
    border-bottom: 1px solid #dfdfdf;
    padding: 10px 50px;
    margin-left: 250px;
    color: #313131;
    font-size: 12px;
    -moz-border-radius-topright: 16px;
    -webkit-border-top-right-radius: 16px;
    border-top-right-radius: 16px;
}

table th.value {
    width: 450px;
    background-color: #dfeeb8;
}

#content h2 {
    font-size: 24px;
    color: #313131;
    font-weight: bold;
}

#content #main {
    padding: 0;
    background-color: #FFF;
    border: 1px solid #dfdfdf;
}

#content #main p {
    color: #313131;
    font-size: 14px;
    padding-bottom: 20px;
}

.sf-toolbarreset {
    border-top: 0;
    padding: 0;
}

.sf-exceptionreset .block_exception_detected .text_exception {
    width: 520px;
}

.sf-exceptionreset .block_exception_detected .illustration_exception {
    display: none;
}

ul.alt {
    margin: 10px 0 30px;
}

ul.alt li {
    padding: 5px 7px;
    font-size: 13px;
}

ul.alt li.even {
    background: #f1f7e2;
}

ul.alt li.error {
    background-color: #f66;
    margin-bottom: 1px;
}

td.main, td.menu {
    text-align: left;
    margin: 0;
    padding: 0;
    border: 0;
    vertical-align: top;
}

.search {
    padding-top: 20px;
}

.search label {
    line-height: 28px;
    vertical-align: middle;
}

.search input {
    width: 188px;
    margin-right: 10px;
    font-size: 12px;
    border: 1px solid #dadada;
    background: #FFF url(../images/profiler/input_bg.gif) repeat-x left top;
    padding: 5px 6px;
    color: #565656;
}

.search input[type="search"] {
    -webkit-appearance: textfield;
}

.search button {
    -webkit-appearance: button-bevel;
    float: none;
    padding: 0;
    margin: 0;
    border: 0;
    text-decoration: none;
    cursor: pointer;
    white-space: nowrap;
    display: inline-block;
    text-align: center;
    vertical-align: middle;
    background: none;
}

.search button:hover {
    text-decoration: none;
}

.search button span span,
.search button span span span {
    position: static;
}

.search button span {
    position: relative;
    text-decoration: none;
    display: block;
    height: 28px;
    float: left;
    padding: 0 0 0 8px;
    background: transparent url(../images/profiler/border_l.png) no-repeat top left;
}

.search button span span {
    padding: 0 8px 0 0;
    background: transparent url(../images/profiler/border_r.png) right top no-repeat;
}

.search button span span span {
    padding: 0 7px;
    font: bold 11px Arial, Helvetica, sans-serif;
    color: #6b6b6b;
    line-height: 28px;
    background: transparent url(../images/profiler/btn_bg.png) repeat-x top left;
}

#navigation div:first-child {
    margin: 0 0 20px;
    border-top: 0;
}

#navigation .search {
    padding-top: 15px;
    float: none;
    background: none repeat scroll 0 0 #f6f6f6;
    color: #333;
    margin: 20px 0;
    border: 1px solid #dfdfdf;
    border-left: none;
}

#navigation .search h3 {
    font-family: Arial, Helvetica, sans-serif;
    text-transform: uppercase;
    margin-left: 10px;
    font-size: 13px;
}

#navigation .search form {
    padding: 15px 0;
}

#navigation .search button {
    float: right;
    margin-right: 20px;
}

#navigation .search label {
    display: block;
    float: left;
    width: 50px;
}

#navigation .search input,
#navigation .search select,
#navigation .search label,
#navigation .search a {
    font-size: 12px;
}

#navigation .search form {
    padding-left: 10px;
}

#navigation .search input {
    width: 160px;
}

#navigation .import label {
    float: none;
    display: inline;
}

#navigation .import input {
    width: 100px;
}

.timeline {
    background-color: #fbfbfb;
    margin-bottom: 15px;
    margin-top: 5px;
}

#collector_content .routing tr.matches td {
    background-color: #0e0;
}

#collector_content .routing tr.almost td {
    background-color: #fa0;
}

.loading {
    background: transparent url(../images/profiler/spinner.gif) scroll no-repeat 50% 50%;
    height: 30px;
    display: none;
}


text:
{
  const doIt = expressMiddleware(compiler, option);

  const fun = function*(next) {
    const ctx = this;
    ctx.webpack = doIt;
    const req = this.req;
    const runNext = yield middleware(doIt, req, {
      end: content => {
        ctx.body = content;
      },
      setHeader: () => {
        ctx.set.apply(ctx, arguments);
      }
    });

    if (runNext) {
      yield* next;
    }
  };

  fun.fileSystem = doIt.fileSystem;
  return fun;
}


text:
    <button type="button" class="close" data-dismiss="modal" ng-click="vm.close()" aria-hidden="true">×</button>

Request a song

        Got a song, artist, or album you'd like to hear? Type the name below, we'll play it for everyone listening.

            Tell me more.

    <input class="form-control"
           type="text"
           ng-model="vm.songRequestText"
           ng-model-options="{ debounce: 250 }"
           ng-hide="vm.selectedSongRequest"
           placeholder="Type a song, artist, or album"
           uib-typeahead="match.name for match in vm.getSongMatches($viewValue)"
           typeahead-template-url="{{vm.songRequestResultView}}"
           typeahead-on-select="vm.songChosen($item)" />

            Loading results...

                {{vm.selectedSongRequest.name}}
                <button type="button" class="close" ng-click="vm.selectedSongRequest = null" aria-hidden="true">×</button>

            By
            {{vm.selectedSongRequest.artist}}

            On
            {{vm.selectedSongRequest.album}}

    <button type="button" class="btn btn-primary btn-lg" ng-disabled="!vm.selectedSongRequest" ng-click="vm.requestSelectedSong()">Request</button>


text:
require 'test_helper'
require 'ostruct'

Endeavour.hook!

class EndeavourTest < Minitest::Test
  def test_call_with_object
    color = OpenStruct.new(name: 'Red')
    assert_equal 'Red', color.try(:name)

    color = nil
    assert_equal nil, color.try(:name)
  end

  def test_call_with_hash
    colors = { red: :rojo }
    assert_equal :rojo, colors.try(:[], :red)

    colors = nil
    assert_equal nil, colors.try(:[], :red)
  end

  def test_delegate_with_object
    color = OpenStruct.new(name: 'Red')
    assert_equal 'Red', color.try.name

    color = nil
    assert_equal nil, color.try.name
  end

  def test_delegate_with_hash
    colors = { red: :rojo }
    assert_equal :rojo, colors.try[:red]

    colors = nil
    assert_equal nil, colors.try[:red]
  end

  def test_delegate_block
    numbers = 1.upto(5)
    assert_equal [1, 4, 9, 16, 25], numbers.try.map { |n| n * n }

    numbers = nil
    assert_equal nil, numbers.try.map { |n| n * n }
  end

  def test_to_s
    color = :yellow
    assert_equal 'yellow', color.try.to_s
  end

  def test_remove_hook
    Endeavour.remove_hook!
    assert_raises 'NoMethodError' do
      colors = { red: :rojo }
      colors.try[:red]
    end
    Endeavour.instance_eval { remove_instance_variable :@try_removed }
    load 'endeavour/core_ext/object/try.rb'
    load 'endeavour/core_ext/nil_class/try.rb'
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    public interface ICreateFactory
    {
          T CreateInstance<T>();
    }
}


text:
#ifndef _EXTHDFS_COMMON_H_
#define _EXTHDFS_COMMON_H_

#include "postgres.h"
#include "fmgr.h"
#include "funcapi.h"
#include "access/extprotocol.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_exttable.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "miscadmin.h"

#include <fcntl.h>

#endif  // _EXTHDFS_COMMON_H_


text:
package org.xbib.netty.http.client.transport;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpDataFactory;
import io.netty.handler.ssl.SslHandler;
import org.xbib.net.PercentDecoder;
import org.xbib.net.URL;
import org.xbib.net.URLSyntaxException;
import org.xbib.netty.http.client.Client;
import org.xbib.netty.http.client.api.ClientTransport;
import org.xbib.netty.http.common.HttpAddress;
import org.xbib.netty.http.client.api.Request;
import org.xbib.netty.http.client.api.BackOff;
import org.xbib.netty.http.common.HttpResponse;
import org.xbib.netty.http.common.cookie.Cookie;
import org.xbib.netty.http.common.cookie.CookieBox;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.net.ConnectException;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnmappableCharacterException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public abstract class BaseTransport implements ClientTransport {

    private static final Logger logger = Logger.getLogger(BaseTransport.class.getName());

    protected final Client client;

    protected final HttpAddress httpAddress;

    protected Throwable throwable;

    private static final Request DUMMY = Request.builder(HttpMethod.GET).build();

    private final Map<Request, Channel> channels;

    private SSLSession sslSession;

    public final Map<String, Flow> flowMap;

    protected final SortedMap<String, Request> requests;

    private CookieBox cookieBox;

    protected HttpDataFactory httpDataFactory;

    public BaseTransport(Client client, HttpAddress httpAddress) {
        this.client = client;
        this.httpAddress = httpAddress;
        this.channels = new ConcurrentHashMap<>();
        this.flowMap = new ConcurrentHashMap<>();
        this.requests = new ConcurrentSkipListMap<>();
        this.httpDataFactory = new DefaultHttpDataFactory();
    }

    @Override
    public HttpAddress getHttpAddress() {
        return httpAddress;
    }

    /**
     * Method for executing the request and respond in a completable future.
     *
     * @param request request
     * @param supplier supplier
     * @param <T> supplier result
     * @return completable future
     */
    @Override
    public <T> CompletableFuture<T> execute(Request request, Function<HttpResponse, T> supplier)
            throws IOException {
        Objects.requireNonNull(supplier);
        final CompletableFuture<T> completableFuture = new CompletableFuture<>();
        request.setResponseListener(response -> {
            if (response != null) {
                completableFuture.complete(supplier.apply(response));
            } else {
                completableFuture.cancel(true);
            }
            close();
        });
        request.setTimeoutListener(req -> completableFuture.completeExceptionally(new TimeoutException()));
        request.setExceptionListener(completableFuture::completeExceptionally);
        execute(request);
        return completableFuture;
    }

    @Override
    public void close() {
        get();
        cancel();
    }

    @Override
    public boolean isFailed() {
        return throwable != null;
    }

    @Override
    public Throwable getFailure() {
        return throwable;
    }

    /**
     * The underlying network layer failed.
     * So we fail all (open) promises.
     * @param throwable the exception
     */
    @Override
    public void fail(Channel channel, Throwable throwable) {
        // do not fail more than once
        if (this.throwable != null) {
            return;
        }
        this.throwable = throwable;
        logger.log(Level.SEVERE, "channel " + channel + " failing: " + throwable.getMessage(), throwable);
        for (Flow flow : flowMap.values()) {
            flow.fail(throwable);
        }
    }

    @Override
    public void inactive(Channel channel) {
        // do nothing
    }

    @Override
    public ClientTransport get() {
        return get(client.getClientConfig().getReadTimeoutMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public ClientTransport get(long value, TimeUnit timeUnit) {
        if (!flowMap.isEmpty()) {
            for (Map.Entry<String, Flow> entry : flowMap.entrySet()) {
                Flow flow = entry.getValue();
                if (!flow.isClosed()) {
                    for (Integer key : flow.keys()) {
                        String requestKey = getRequestKey(entry.getKey(), key);
                        try {
                            CompletableFuture<Boolean> timeoutFuture = flow.get(key);
                            Boolean timeout = timeoutFuture.get(value, timeUnit);
                            if (timeout) {
                                completeRequest(requestKey);
                            } else {
                                completeRequestTimeout(requestKey, new TimeoutException());
                            }
                        } catch (TimeoutException e) {
                            completeRequestTimeout(requestKey, new TimeoutException());
                        } catch (Exception e) {
                            completeRequestExceptionally(requestKey, e);
                            flow.fail(e);
                        } finally {
                            flow.remove(key);
                        }
                    }
                    flow.close();
                }
            }
            flowMap.clear();
        }
        channels.values().forEach(channel -> {
            try {
                client.releaseChannel(channel, true);
            } catch (IOException e) {
                logger.log(Level.WARNING, e.getMessage(), e);
            }
        });
        return this;
    }

    @Override
    public void cancel() {
        if (!flowMap.isEmpty()) {
            for (Map.Entry<String, Flow> entry : flowMap.entrySet()) {
                Flow flow = entry.getValue();
                for (Integer key : flow.keys()) {
                    try {
                        flow.get(key).cancel(true);
                    } catch (Exception e) {
                        completeRequestExceptionally(getRequestKey(entry.getKey(), key), e);
                        flow.fail(e);
                    } finally {
                        flow.remove(key);
                    }
                }
                flow.close();
            }
        }
        channels.values().forEach(channel -> {
            try {
                client.releaseChannel(channel, true);
            } catch (IOException e) {
                logger.log(Level.WARNING, e.getMessage(), e);
            }
        });
        flowMap.clear();
        channels.clear();
        requests.clear();
        httpDataFactory.cleanAllHttpData();
    }

    @Override
    public SSLSession getSession() {
        return sslSession;
    }

    protected abstract String getRequestKey(String channelId, Integer streamId);

    Channel mapChannel(Request request) throws IOException {
        Channel channel;
        if (!client.hasPooledConnections()) {
            channel = channels.get(DUMMY);
            if (channel == null) {
                channel = switchNextChannel();
            }
            channels.put(DUMMY, channel);
        } else {
            channel = switchNextChannel();
            channels.put(request, channel);
        }
        SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
        sslSession = sslHandler != null ? sslHandler.engine().getSession() : null;
        return channel;
    }

    private Channel switchNextChannel() throws IOException {
        Channel channel = client.newChannel(httpAddress);
        if (channel != null) {
            channel.attr(TRANSPORT_ATTRIBUTE_KEY).set(this);
            waitForSettings();
        } else {
            ConnectException connectException;
            if (httpAddress != null) {
                connectException = new ConnectException("unable to connect to " + httpAddress);
            } else if (client.hasPooledConnections()) {
                connectException = new ConnectException("unable to get channel from pool");
            } else {
                // API misuse
                connectException = new ConnectException("unable to get channel");
            }
            this.throwable = connectException;
            throw connectException;
        }
        return channel;
    }

    protected Request continuation(Request request, HttpResponse httpResponse) throws URLSyntaxException {
        if (httpResponse == null) {
            return null;
        }
        if (request == null) {
            // push promise or something else
            return null;
        }
        try {
            if (request.canRedirect()) {
                int status = httpResponse.getStatus().getCode();
                switch (status) {
                    case 300:
                    case 301:
                    case 302:
                    case 303:
                    case 305:
                    case 307:
                    case 308:
                        String location = httpResponse.getHeaders().getHeader(HttpHeaderNames.LOCATION);
                        location = new PercentDecoder(StandardCharsets.UTF_8.newDecoder()).decode(location);
                        if (location != null) {
                            logger.log(Level.FINE, "found redirect location: " + location);
                            URL redirUrl = URL.base(request.url()).resolve(location);
                            HttpMethod method = httpResponse.getStatus().getCode() == 303 ? HttpMethod.GET : request.httpMethod();
                            Request.Builder newHttpRequestBuilder = Request.builder(method, request)
                                    .url(redirUrl);
                            request.url().getQueryParams().forEach(pair ->
                                newHttpRequestBuilder.addParameter(pair.getFirst(), pair.getSecond())
                            );
                            request.cookies().forEach(newHttpRequestBuilder::addCookie);
                            Request newHttpRequest = newHttpRequestBuilder.build();
                            StringBuilder hostAndPort = new StringBuilder();
                            hostAndPort.append(redirUrl.getHost());
                            if (redirUrl.getPort() != null) {
                                hostAndPort.append(':').append(redirUrl.getPort());
                            }
                            newHttpRequest.headers().set(HttpHeaderNames.HOST, hostAndPort.toString());
                            logger.log(Level.FINE, "redirect url: " + redirUrl);
                            return newHttpRequest;
                        }
                        break;
                    default:
                        break;
                }
            }
        } catch (MalformedInputException | UnmappableCharacterException e) {
            this.throwable = e;
        }
        return null;
    }

    protected Request retry(Request request, HttpResponse httpResponse) {
        if (httpResponse == null) {
            // no response present, invalid in any way
            return null;
        }
        if (request == null) {
            // push promise or something else
            return null;
        }
        if (request.isBackOff()) {
            BackOff backOff = request.getBackOff() != null ?
                    request.getBackOff() :
                    client.getClientConfig().getBackOff();
            int status = httpResponse.getStatus ().getCode();
            switch (status) {
                case 403:
                case 404:
                case 500:
                case 502:
                case 503:
                case 504:
                case 507:
                case 509:
                    if (backOff != null) {
                        long millis = backOff.nextBackOffMillis();
                        if (millis != BackOff.STOP) {
                            logger.log(Level.FINE, () -> "status = " + status + " backing off request by " + millis + " milliseconds");
                            try {
                                Thread.sleep(millis);
                            } catch (InterruptedException e) {
                                // ignore
                            }
                            return request;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        return null;
    }

    private void completeRequest(String requestKey) {
        if (requestKey != null) {
            Request request = requests.get(requestKey);
            if (request != null && request.getCompletableFuture() != null) {
                request.getCompletableFuture().complete(request);
            }
        }
    }

    private void completeRequestExceptionally(String requestKey, Throwable throwable) {
        if (requestKey != null) {
            Request request = requests.get(requestKey);
            if (request != null) {
                request.onException(throwable);
            }
        }
    }

    private void completeRequestTimeout(String requestKey, TimeoutException timeoutException) {
        if (requestKey != null) {
            Request request = requests.get(requestKey);
            if (request != null) {
                request.onTimeout();
            }
        }
    }

    @Override
    public void setCookieBox(CookieBox cookieBox) {
        this.cookieBox = cookieBox;
    }

    @Override
    public CookieBox getCookieBox() {
        return cookieBox;
    }

    void addCookie(Cookie cookie) {
        if (cookieBox == null) {
            this.cookieBox = new CookieBox(32);
        }
        cookieBox.put(cookie, true);
    }

    List<Cookie> matchCookiesFromBox(Request request) {
        return cookieBox == null ? Collections.emptyList() : cookieBox.keySet().stream().filter(cookie ->
                matchCookie(request.url(), cookie)
        ).collect(Collectors.toList());
    }

    List<Cookie> matchCookies(Request request) {
        return request.cookies().stream().filter(cookie ->
                matchCookie(request.url(), cookie)
        ).collect(Collectors.toList());
    }

    private boolean matchCookie(URL url, Cookie cookie) {
        boolean domainMatch = cookie.domain() == null || url.getHost().endsWith(cookie.domain());
        if (!domainMatch) {
            return false;
        }
        boolean pathMatch = "/".equals(cookie.path()) || url.getPath().startsWith(cookie.path());
        if (!pathMatch) {
            return false;
        }
        boolean secureScheme = "https".equals(url.getScheme());
        return (secureScheme && cookie.isSecure()) || (!secureScheme && !cookie.isSecure());
    }

}


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > The Rental Car (1)

						Expand All | Collapse All

The Rental Car (1)

 "You should pay the extra $45," Amelia said. He told her that the extra money was just another corporate rip-off, like the extended insurance that Best Buy offers customers on new computers. Only one percent of the time is the insurance ever needed; the rest of the time, the company makes a fortune off customers' fear. Ryan figured he would take his chances. He had used rental cars many times without any problems.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
namespace NServiceBus
{
    public partial class SqlDialect
    {
        public partial class PostgreSql
        {
            internal override string GetOutboxTableName(string tablePrefix)
            {
                return $"\"{Schema}\".\"{tablePrefix}OutboxData\"";
            }

            internal override string GetOutboxSetAsDispatchedCommand(string tableName)
            {
                return $@"
update {tableName}
set
    ""Dispatched"" = true,
    ""DispatchedAt"" = @DispatchedAt,
    ""Operations"" = '[]'
where ""MessageId"" = @MessageId";
            }

            internal override string GetOutboxGetCommand(string tableName)
            {
                return $@"
select
    ""Dispatched"",
    ""Operations""
from {tableName}
where ""MessageId"" = @MessageId";
            }

            internal override string GetOutboxStoreCommand(string tableName)
            {
                return $@"
insert into {tableName}
(
    ""MessageId"",
    ""Operations"",
    ""PersistenceVersion""
)
values
(
    @MessageId,
    @Operations,
    @PersistenceVersion
)";
            }

            internal override string GetOutboxCleanupCommand(string tableName)
            {
                return $@"
delete from {tableName}
where ctid in
(
    select ctid
    from {tableName}
    where
        ""Dispatched"" = true and
        ""DispatchedAt"" < @DispatchedBefore
    limit @BatchSize
)";
            }
        }
    }
}


text:
package net.dirtyfilthy.bouncycastle.asn1.x9;

import net.dirtyfilthy.bouncycastle.asn1.ASN1Encodable;
import net.dirtyfilthy.bouncycastle.asn1.ASN1OctetString;
import net.dirtyfilthy.bouncycastle.asn1.DERObject;
import net.dirtyfilthy.bouncycastle.asn1.DEROctetString;
import net.dirtyfilthy.bouncycastle.math.ec.ECCurve;
import net.dirtyfilthy.bouncycastle.math.ec.ECPoint;

/**
 * class for describing an ECPoint as a DER object.
 */
public class X9ECPoint
    extends ASN1Encodable
{
    ECPoint p;

    public X9ECPoint(
        ECPoint p)
    {
        this.p = p;
    }

    public X9ECPoint(
        ECCurve          c,
        ASN1OctetString  s)
    {
        this.p = c.decodePoint(s.getOctets());
    }

    public ECPoint getPoint()
    {
        return p;
    }

    /**
     * Produce an object suitable for an ASN1OutputStream.
     *

     *  ECPoint ::= OCTET STRING
     *

     *

     * Octet string produced using ECPoint.getEncoded().
     */
    public DERObject toASN1Object()
    {
        return new DEROctetString(p.getEncoded());
    }
}