text:
"""Defines a collection of classes for running unit-tests."""

import build_project
import cStringIO
import datetime
import hashlib
import logging
import optparse
import os
import presubmit
import re
import subprocess
import sys
import temp_watcher

_LOGGER = logging.getLogger(os.path.basename(__file__))

class Error(Exception):
  """An error class used for reporting problems while running tests."""
  pass

class BuildFailure(Error):
  """The error thrown to indicate that BuildProjectConfig has failed."""
  pass

class RunFailure(Error):
  """The error thrown to indicate that a sub-command has failed."""
  pass

class TestFailure(Error):
  """An error that can be thrown to indicate that a test has failed."""
  pass

def AddThirdPartyToPath():
  """Drags in the colorama module from third party."""
  third_party = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                             '..', '..', '..', 'third_party'))
  if third_party not in sys.path:
    sys.path.insert(0, third_party)

AddThirdPartyToPath()
import colorama

def BuildProjectConfig(*args, **kwargs):
  """Wraps build_project.BuildProjectConfig, but ensures that if it throws
  an error it is of type testing.Error.
  """
  try:
    build_project.BuildProjectConfig(*args, **kwargs)
  except build_project.Error:
    # Convert the exception to an instance of testing.BuildFailure, but preserve
    # the original message and stack-trace.
    raise BuildFailure, sys.exc_info()[1], sys.exc_info()[2]

def RunCommand(cmd, *args, **kwargs):
  """Runs the provided command using subprocess.

  Args:
    cmd: The command to be run, as a list.

  Returns:
    A tuple of (stdout, stderr).

  Raises:
    RunFailure: If the command fails.
  """
  _LOGGER.debug('Running %s.', cmd)
  popen = subprocess.Popen(cmd, *args, **kwargs)
  (stdout, stderr) = popen.communicate()
  if popen.returncode != 0:
    raise RunFailure('Command %s failed with return code %d.' %
        (cmd, popen.returncode))
  return (stdout, stderr)

class Test(object):
  """A base class embodying the notion of a test. A test has a name, and is
  invokable by calling 'Run' with a given configuration. Upon success, the
  test will create a success file in the appropriate configuration
  directory.

  The 'Main' routine of any Test object may also be called to have it
  run as as stand-alone command line test.
  """

  def __init__(self, build_dir, name, leaf):
    """Initializes this test.

    Args:
      build_dir: The root build output directory.
      name: The name of this test.
      leaf: If true this test is a leaf. That is, it actually runs an
          executable. Otherwise it is a non-leaf test that simply aggregates
          results from other tests.
    """

    self._build_dir = build_dir
    self._name = name
    self._force = False
    self._leaf = leaf

    # Tests are to direct all of their output to these streams.
    # NOTE: These streams aren't directly compatible with subprocess.Popen.
    self._stdout = cStringIO.StringIO()
    self._stderr = cStringIO.StringIO()

  def GetSuccessFilePath(self, configuration):
    """Returns the path to the success file associated with this test."""
    success_path = presubmit.GetTestSuccessPath(self._build_dir,
                                                configuration,
                                                self._name)
    return success_path

  def LastRunTime(self, configuration):
    """Returns the time this test was last run in the given configuration.
    Returns 0 if the test has no success file (equivalent to never having
    been run).
    """
    try:
      return os.stat(self.GetSuccessFilePath(configuration)).st_mtime
    except (IOError, WindowsError):
      return 0

  def _CanRun(self, configuration):  # pylint: disable=R0201,W0613
    """Indicates whether this test can run the given configuration.

    Derived classes may override this in order to indicate that they
    should not be run in certain configurations. This stub always returns
    True.

    If the derived class wants to indicate that the test has failed it can
    also raise a TestFailure error here.

    Args:
      configuration: the configuration to test.

    Returns:
      True if this test can run in the given configuration, False otherwise.

    Raises:
      TestFailure if the test should be considered as failed.
    """
    return True

  def _NeedToRun(self, configuration):  # pylint: disable=R0201,W0613
    """Determines whether this test needs to be run in the given configuration.

    Derived classes may override this if they can determine ahead of time
    whether the given test needs to be run. This stub always returns True.

    If the derived class wants to indicate that the test has failed it can
    also raise a TestFailure error here.

    Args:
      configuration: the configuration to test.

    Returns:
      True if this test can run in the given configuration, False otherwise.

    Raises:
      TestFailure if the test should be considered as failed.
    """
    return True

  def _MakeSuccessFile(self, configuration):
    """Makes the success file corresponding to this test in the given
    configuration.
    """
    success_path = self.GetSuccessFilePath(configuration)
    _LOGGER.debug('Creating success file "%s".',
                  os.path.relpath(success_path, self._build_dir))
    success_file = open(success_path, 'wb')
    success_file.write(str(datetime.datetime.now()))
    success_file.close()

  def _Run(self, configuration):
    """This is as a stub of the functionality that must be implemented by
    child classes.

    Args:
      configuration: the configuration in which to run the test.

    Returns:
      True on success, False on failure. If a test fails by returning False
      all of the others test will continue to run. If an exception is raised
      then all tests are stopped."""
    raise NotImplementedError('_Run not overridden.')

  def _WriteStdout(self, value):
    """Appends a value to stdout.

    Args:
      value: the value to append to stdout.
    """
    self._stdout.write(value)
    return

  def _WriteStderr(self, value):
    """Appends a value to stderr.

    Args:
      value: the value to append to stderr.
    """
    self._stderr.write(value)
    return

  def _GetStdout(self):
    """Returns any accumulated stdout, and erases the buffer."""
    stdout = self._stdout.getvalue()
    self._stdout = cStringIO.StringIO()
    return stdout

  def _GetStderr(self):
    """Returns any accumulated stderr, and erases the buffer."""
    stderr = self._stderr.getvalue()
    self._stderr = cStringIO.StringIO()
    return stderr

  def Run(self, configuration, force=False):
    """Runs the test in the given configuration. The derived instance of Test
    must implement '_Run(self, configuration)', which raises an exception on
    error or does nothing on success. Upon success of _Run, this will generate
    the appropriate success file. If the test fails, the exception is left
    to propagate.

    Args:
      configuration: The configuration in which to run.
      force: If True, this will force the test to re-run even if _NeedToRun
          would return False.

    Returns:
      True on success, False otherwise.
    """
    # Store optional arguments in a side-channel, so as to allow additions
    # without changing the _Run/_NeedToRun/_CanRun API.
    self._force = force

    success = True
    try:
      if not self._CanRun(configuration):
        _LOGGER.info('Skipping test "%s" in invalid configuration "%s".',
                     self._name, configuration)
        return True

      # Always run _NeedToRun, even if force is true. This is because it may
      # do some setup work that is required prior to calling _Run.
      _LOGGER.debug('Checking to see if we need to run test "%s" in '
                    'configuration "%s".', self._name, configuration)
      need_to_run = self._NeedToRun(configuration)

      if need_to_run:
        _LOGGER.info('Running test "%s" in configuration "%s".',
                     self._name, configuration)
      else:
        _LOGGER.debug('No need to re-run test "%s" in configuration "%s".',
                      self._name, configuration)

      if not need_to_run and force:
        _LOGGER.info('Forcing re-run of test "%s" in configuration "%s".',
                     self._name, configuration)
        need_to_run = True

      if need_to_run:
        if not self._Run(configuration):
          raise TestFailure('Test "%s" failed in configuration "%s".' %
                                (self._name, configuration))

      self._MakeSuccessFile(configuration)
    except TestFailure, e:
      fore = colorama.Fore
      style = colorama.Style
      self._WriteStdout(style.BRIGHT + fore.RED + str(e) + '\n' +
                            style.RESET_ALL)
      success = False
    finally:
      # Forward the stdout, which we've caught and stuffed in a string.
      sys.stdout.write(self._GetStdout())

    return success

  @staticmethod
  def _GetOptParser():
    """Builds an option parser for this class. This function is static as
    it may be called by the constructor of derived classes before the object
    is fully initialized. It may also be overridden by derived classes so that
    they may augment the option parser with additional options.
    """
    parser = optparse.OptionParser()
    parser.add_option('-c', '--config', dest='configs',
                      action='append', default=[],
                      help='The configuration in which you wish to run '
                           'this test. This option may be invoked multiple '
                           'times. If not specified, defaults to '
                           '["Debug", "Release"].')
    parser.add_option('-f', '--force', dest='force',
                      action='store_true', default=False,
                      help='Force tests to re-run even if not necessary.')
    parser.add_option('--verbose', dest='log_level', action='store_const',
                      const=logging.DEBUG, default=logging.INFO,
                      help='Run the script with verbose logging.')
    return parser

  def Main(self):
    t1 = datetime.datetime.now()
    colorama.init()

    opt_parser = self._GetOptParser()
    options, dummy_args = opt_parser.parse_args()

    logging.basicConfig(level=options.log_level)

    # If no configurations are specified, run all configurations.
    if not options.configs:
      options.configs = ['Debug', 'Release']

    result = 0
    for config in set(options.configs):
      # We don't catch any exceptions that may be raised as these indicate
      # something has gone really wrong, and we want them to interrupt further
      # tests.
      if not self.Run(config, force=options.force):
        _LOGGER.error('Configuration "%s" of test "%s" failed.',
                      config, self._name)
        result = 1

    # Now dump all error messages.
    sys.stdout.write(self._GetStderr())

    t2 = datetime.datetime.now()
    _LOGGER.info('Unittests took %s to run.', t2 - t1)

    return result

class ExecutableTest(Test):
  """An executable test is a Test that is run by launching a single
  executable file, and inspecting its return value.
  """

  def __init__(self, build_dir, name, extra_args=None):
    """Initializes this object.

    Args:
      build_dir: The build output directory.
      name: The name of the executable being testing, without an extension.
          The binary will be looked for in the following location:
              <build_dir>/<build_configuration>/<name>.exe
      extra_args: Extra arguments that will be used when invoking the
          executable. If these are specified the test name (used for generating
          the success file) will be decorated to reflect the contents of the
          extra arguments.
    """
    if extra_args is None:
      extra_args = []

    # Remember the raw name and generate a decorated name which reflects the
    # additional arguments.
    raw_name = name
    if extra_args:
      name = '%s_%s' % (name, hashlib.md5(' '.join(extra_args)).hexdigest())

    Test.__init__(self, build_dir, name, True)
    self._raw_name = raw_name
    self._extra_args = extra_args

  def _GetTestPath(self, configuration):
    """Returns the path to the test executable. This stub may be overridden,
    but it defaults to self._build_dir/<build_configuration>/<name>.exe
    """
    return os.path.join(
        self._build_dir, configuration, '%s.exe' % self._raw_name)

  def _NeedToRun(self, configuration):
    test_path = self._GetTestPath(configuration)
    if not os.path.exists(test_path):
      return True
    return os.stat(test_path).st_mtime > self.LastRunTime(configuration)

  def _GetCmdLine(self, configuration):
    """Returns the command line to run."""
    return [self._GetTestPath(configuration)] + self._extra_args

  def _Run(self, configuration):
    test_path = self._GetTestPath(configuration)

    # Run the executable. We do this using a 'temp_watcher' Popen wrapper
    # which redirects and monitors the temp directory.
    command = self._GetCmdLine(configuration)
    popen = temp_watcher.Popen(command,
                               cleanup=True,
                               fail=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT)
    (stdout, dummy_stderr) = popen.communicate()
    self._WriteStdout(stdout)

    # If the test has failed, dump its output to stderr as well. These are
    # buffered and replayed at the end of all unittests so that errors have
    # better visibility.
    if popen.returncode != 0:
      # We output the test name so we can easily find out to which unittest
      # the error message belongs.
      self._WriteStderr('Error: Test "%s" failed in configuration "%s".\n' % (
          self._name, configuration))

      # If the unittest executable itself failed, replay its output.
      if popen.origreturncode != 0:
        self._WriteStderr(stdout)

      # If there are orphaned files, dump a warning. We output to both stdout
      # and stderr so that it is seen at the time it happens, and again at
      # the end of running all tests.
      if popen.orphaned_files:
        msg = 'Error: Found %d orphaned files/directories in ' \
              'temp directory.\n' % len(popen.orphaned_files)
        self._WriteStdout(msg)
        self._WriteStderr(msg)

    # Bail if we had any errors.
    if popen.returncode != 0:
      msg = 'Test "%s" failed in configuration "%s". Exit code %d.' % \
                (self._name, configuration, popen.returncode)
      raise TestFailure(msg)

    # If we get here, all has gone well.
    return True

def _GTestColorize(text):
  """Colorizes the given Gtest output with ANSI color codes."""
  fore = colorama.Fore
  style = colorama.Style
  def _ColorizeLine(line):
    line = re.sub('^(\[\s*(?:-+|=+|RUN|PASSED|OK)\s*\])',
                  style.BRIGHT + fore.GREEN + '\\1' + style.RESET_ALL,
                  line)
    line = re.sub('^(\[\s*FAILED\s*\])',
                  style.BRIGHT + fore.RED + '\\1' + style.RESET_ALL,
                  line)
    line = re.sub('^(\s*(?:Note:|YOU HAVE .* DISABLED TEST).*)',
                  style.BRIGHT + fore.YELLOW + '\\1' + style.RESET_ALL,
                  line)
    # This colorizes the error messages inserted for orphaned files.
    line = re.sub('(^Error: .*)',
                  style.BRIGHT + fore.RED + '\\1' + style.RESET_ALL,
                  line)
    return line

  return '\n'.join([_ColorizeLine(line) for line in text.split('\n')])

class GTest(ExecutableTest):
  """This wraps a GTest unittest, with colorized output."""
  def __init__(self, *args, **kwargs):
    # Syzygy unittests all use the sharded Chrome launcher, so by default
    # shard them across a few CPUs. Some tests are quite long so provide a
    # generous 5 minute timeout (300,000 ms).
    extra_args = kwargs.get('extra_args', [])
    extra_args.append('--test-launcher-jobs=5')
    extra_args.append('--test-launcher-timeout=300000')
    kwargs['extra_args'] = extra_args

    ExecutableTest.__init__(self, *args, **kwargs)

  def _WriteStdout(self, value):
    """Colorizes the stdout of this test."""
    return super(GTest, self)._WriteStdout(_GTestColorize(value))

  def _WriteStderr(self, value):
    """Colorizes the stderr of this test."""
    return super(GTest, self)._WriteStderr(_GTestColorize(value))

class TestSuite(Test):
  """A test suite is a collection of tests that generates a catch-all
  success file upon successful completion. It is itself an instance of a
  Test, so may be nested.
  """

  def __init__(self, build_dir, name, tests, stop_on_first_failure=False):
    Test.__init__(self, build_dir, name, False)
    # tests may be anything iterable, but we want it to be a list when
    # stored internally.
    self._tests = list(tests)
    self._stop_on_first_failure = stop_on_first_failure

  def AddTest(self, test):
    self._tests.append(test)

  def AddTests(self, tests):
    self._tests.extend(self, tests)

  def _CanRun(self, configuration):
    """Determines if any of the tests can run in the given configuration."""
    can_run = False
    for test in self._tests:
      try:
        if test._CanRun(configuration):
          can_run = True
      except:
        # Output some context before letting the exception continue.
        _LOGGER.error('Configuration "%s" of test "%s" failed.',
                      configuration, test._name)  # pylint: disable=W0212
    return can_run

  def _NeedToRun(self, configuration):
    """Determines if any of the tests in this suite need to run in the given
    configuration.
    """
    need_to_run = False
    for test in self._tests:
      try:
        if test._NeedToRun(configuration):  # pylint: disable=W0212
          need_to_run = True
      except:
        # Output some context before letting the exception continue.
        _LOGGER.error('Configuration "%s" of test "%s" failed.',
                      configuration, test._name)  # pylint: disable=W0212
        raise
    return need_to_run

  def _Run(self, configuration):
    """Implementation of this Test object.

    Runs the provided collection of tests, generating a global success file
    upon completion of them all. Runs all tests even if any test fails. Stops
    running all tests if any of them raises an exception.
    """
    success = True
    for test in self._tests:
      if not test.Run(configuration, force=self._force):
        # Keep a cumulative log of all stderr from each test that fails.
        self._WriteStderr(test._GetStderr())  # pylint: disable=W0212
        if self._stop_on_first_failure:
          return False
        success = False

    return success


text:
class PlanYear
  include Mongoid::Document
  include Mongoid::Timestamps
#  include Mongoid::Versioning
  include MergingModel

  field :start_date, type: Date
  field :end_date, type: Date
  field :open_enrollment_start, type: Date
  field :open_enrollment_end, type: Date
  field :fte_count, type: Integer
  field :pte_count, type: Integer

  belongs_to :employer
  belongs_to :broker

  index({:employer_id => 1})
  index({:broker_id => 1})
  index({:start_date => 1})
  index({:end_date => 1})
  index({:employer_id => 1, :start_date => 1, :end_date => 1})
  index({:start_date => 1, :end_date => 1})
  index({:employer_id => 1, :open_enrollment_start => 1, :open_enrollment_end => 1})
  index({:open_enrollment_start => 1, :open_enrollment_end => 1})
  index({:open_enrollment_start => 1})
  index({:open_enrollment_end => 1})

  embeds_many :elected_plans

  has_one :contribution_strategy, :class_name => "EmployerContributions::Strategy", :inverse_of => :plan_year

  def self.make(data)
    plan_year = PlanYear.new
    plan_year.open_enrollment_start = data[:open_enrollment_start]
    plan_year.open_enrollment_end = data[:open_enrollment_end]
    plan_year.start_date = Date.parse(data[:start_date])
    plan_year.end_date = Date.parse(data[:end_date]) unless data[:end_date].blank?
    plan_year.broker = Broker.find_by_npn(data[:broker_npn])
    plan_year.fte_count = data[:fte_count]
    plan_year.pte_count = data[:pte_count]
    e_plans = []

    data[:plans].each do |plan_data|
      plan = Plan.find_by_hios_id_and_year(plan_data[:qhp_id], plan_year.start_date.year)
      raise plan_data[:qhp_id].inspect if plan.nil?
      e_plans << ElectedPlan.new(
        :carrier_id => plan.carrier_id,
        :qhp_id => plan_data[:qhp_id],
        :coverage_type => plan_data[:coverage_type],
        :metal_level => plan.metal_level,
        :hbx_plan_id => plan.hbx_plan_id,
        :original_effective_date => plan_data[:original_effective_date],
        :plan_name => plan.name,
        :carrier_policy_number => plan_data[:policy_number],
        :carrier_employer_group_id => plan_data[:group_id]
      )
    end
    plan_year.elected_plans.concat(e_plans)
    plan_year
  end

  def update_group_ids(carrier_id, g_id)
    plans_to_update = self.elected_plans.select do |ep|
      ep.carrier_id == carrier_id
    end
    plans_to_update.each do |ep|
      ep.carrier_employer_group_id = g_id
      ep.touch
      ep.save!
    end
  end

  def match(other)
    return false if other.nil?
    attrs_to_match = [:start_date, :end_date]
    attrs_to_match.all? { |attr| attribute_matches?(attr, other) }
  end

  def attribute_matches?(attribute, other)
    self[attribute] == other[attribute]
  end

  def overlaps?(other_plan_year)
    (start_date - other_plan_year.end_date) * (other_plan_year.start_date - end_date) >= 0
  end

end

redpajama_set_name: RedPajamaGithub


text:
{% extends "cradmin_legacy/base.django.html" %}

{% load static %}
{% load i18n %}
{% load cradmin_legacy_tags %}
{% load cradmin_legacy_icon_tags %}

{% block title %}
    {{ pagetitle }}
{% endblock title %}

{% block pageheader-outer-extraclasses %}
    {{ block.super }}
    devilry-page-header-with-backlink
{% endblock pageheader-outer-extraclasses %}

{% block pageheader-inner %}

            {% trans "Back to overview" %}

        {% blocktrans trimmed with assignmentname=assignment.long_name %}
            {{ pageheading }}
        {% endblocktrans %}

        {{ page_subheading }}

{% endblock pageheader-inner %}

{% block content %}

        {% cradmin_render_renderable listbuilder_list %}

{% endblock content %}


text:
package archive

// Result is archive model.
type Result struct {
	Aid       int64  `json:"aid"`
	Mid       int64  `json:"mid"`
	TypeID    int16  `json:"tid"`
	Title     string `json:"title"`
	Author    string `json:"author"`
	Cover     string `json:"cover"`
	Tag       string `json:"tag"`
	Duration  int64  `json:"duration"`
	Copyright int8   `json:"copyright"`
	Desc      string `json:"desc"`
	Round     int8   `json:"round"`
	Forward   int64  `json:"forward"`
	Attribute int32  `json:"attribute"`
	HumanRank int    `json:"humanrank"`
	Access    int16  `json:"access"`
	State     int8   `json:"state"`
	Reason    string `json:"reject_reason"`
	PTime     string `json:"ptime"`
	CTime     string `json:"ctime"`
	MTime     string `json:"mtime"`
	Dynamic   string `json:"dynamic"`
}

// IsNormal check archive is open.
func (a *Result) IsNormal() bool {
	return a.State >= StateOpen || a.State == StateForbidFixed
}

// NotAllowUp check archive is or not allow update state.
func (a *Result) NotAllowUp() bool {
	return a.State == StateForbidUpDelete || a.State == StateForbidLater || a.State == StateForbidLock || a.State == StateForbidPolice
}

// IsForbid check archive state forbid by admin or delete.
func (a *Result) IsForbid() bool {
	return a.State == StateForbidUpDelete || a.State == StateForbidRecicle || a.State == StateForbidPolice || a.State == StateForbidLock || a.State == StateForbidLater || a.State == StateForbidXcodeFail
}

// AttrVal get attribute value.
func (a *Result) AttrVal(bit uint) int32 {
	return (a.Attribute >> bit) & int32(1)
}

// AttrSet set attribute value.
func (a *Result) AttrSet(v int32, bit uint) {
	a.Attribute = a.Attribute&(^(1 << bit)) | (v << bit)
}

// WithAttr set attribute value with a attr value.
func (a *Result) WithAttr(attr Attr) {
	a.Attribute = a.Attribute | int32(attr)
}


text:
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';

import * as utils
  from 'jupyter-js-utils';

import {
  IDisposable, DisposableDelegate
} from 'phosphor-disposable';

import {
  Widget
} from 'phosphor-widget';

import {
  IModelFactory, IWidgetFactory, IWidgetFactoryOptions,
  IFileType, IKernelPreference, IFileCreator, IWidgetExtension
} from './interfaces';

/**
 * The document registery.
 *
 * #### Notes
 * The document registry is used to register model and widget creators.
 */
export
class DocumentRegistry implements IDisposable {
  /**
   * The name of the default widget factory.
   *
   * #### Notes
   * This is a read-only property.
   */
  get defaultWidgetFactory(): string {
    return this._defaultWidgetFactory;
  }

  /**
   * Get whether the document registry has been disposed.
   */
  get isDisposed(): boolean {
    return this._widgetFactories === null;
  }

  /**
   * Dispose of the resources held by the document registery.
   */
  dispose(): void {
    if (this.isDisposed) {
      return;
    }
    for (let modelName in this._modelFactories) {
      this._modelFactories[modelName].dispose();
    }
    this._modelFactories = null;
    for (let widgetName in this._widgetFactories) {
      this._widgetFactories[widgetName].factory.dispose();
    }
    this._widgetFactories = null;
  }

  /**
   * Register a widget factory with the document registry.
   *
   * @param factory - The factory instance.
   *
   * @param options - The options used to register the factory.
   *
   * @returns A disposable used to unregister the factory.
   *
   * #### Notes
   * If a factory with the given `displayName` is already registered,
   * an error will be thrown.
   * If `'.*'` is given as a default extension, the factory will be registered
   * as the global default.
   * If a factory is already registered as a default for a given extension or
   * as the global default, this factory will override the existing default.
   */
  registerWidgetFactory(factory: IWidgetFactory<Widget>, options: IWidgetFactoryOptions): IDisposable {
    let name = options.displayName;
    let exOpt = utils.copy(options) as Private.IWidgetFactoryEx;
    exOpt.factory = factory;
    if (this._widgetFactories[name]) {
      throw new Error(`Duplicate registered factory ${name}`);
    }
    this._widgetFactories[name] = exOpt;
    if (options.defaultFor) {
      for (let option of options.defaultFor) {
        if (option === '.*') {
          this._defaultWidgetFactory = name;
        } else if (options.fileExtensions.indexOf(option) !== -1) {
          this._defaultWidgetFactories[option] = name;
        }
      }
    }
    return new DisposableDelegate(() => {
      delete this._widgetFactories[name];
      if (this._defaultWidgetFactory === name) {
        this._defaultWidgetFactory = '';
      }
      for (let opt of Object.keys(this._defaultWidgetFactories)) {
        let n = this._defaultWidgetFactories[opt];
        if (n === name) {
          delete this._defaultWidgetFactories[opt];
        }
      }
    });
  }

  /**
   * Register a model factory.
   *
   * @param factory - The factory instance.
   *
   * @returns A disposable used to unregister the factory.
   *
   * #### Notes
   * If a factory with the given `name` is already registered, an error
   * will be thrown.
   */
  registerModelFactory(factory: IModelFactory): IDisposable {
    let name = factory.name;
    if (this._modelFactories[name]) {
      throw new Error(`Duplicate registered factory ${name}`);
    }
    this._modelFactories[name] = factory;
    return new DisposableDelegate(() => {
      delete this._modelFactories[name];
    });
  }

  /**
   * Register a widget extension.
   *
   * @param extension - A widget extension.
   *
   * @returns A disposable that can be used to unregister the extension.
   */
  registerExtension(widgetName: string, extension: IWidgetExtension<Widget>): IDisposable {
    if (!(widgetName in this._extenders)) {
      this._extenders[widgetName] = [];
    }
    this._extenders[widgetName].push(extension);
    return new DisposableDelegate(() => {
      let index = this._extenders[widgetName].indexOf(extension);
      this._extenders[widgetName].splice(index, 1);
    });
  }

  /**
   * Register a file type with the document registry.
   *
   * #### Notes
   * These are used to populate the "Create New" dialog.
   */
  registerFileType(fileType: IFileType): IDisposable {
    this._fileTypes.push(fileType);
    this._fileTypes.sort((a, b) => a.name.localeCompare(b.name));
    return new DisposableDelegate(() => {
      let index = this._fileTypes.indexOf(fileType);
      this._fileTypes.splice(index, 1);
    });
  }

  /**
   * Register a Create New handler.
   *
   * @params creator - The file creator object.
   *
   * @params after - The optional item name to insert after.
   *
   * #### Notes
   * If `after` is not given or not already registered, it will be moved
   * to the end.
   */
  registerCreator(creator: IFileCreator, after?: string): IDisposable {
    let added = false;
    if (after) {
      for (let existing of this._creators) {
        if (existing.name === after) {
          let index = this._creators.indexOf(existing);
          this._creators.splice(index, 0, creator);
          added = true;
        }
      }
    }
    if (!added) {
      this._creators.push(creator);
    }
    return new DisposableDelegate(() => {
      let index = this._creators.indexOf(creator);
      this._creators.splice(index, 1);
    });
  }

  /**
   * Get the list of registered widget factory display names.
   *
   * @param path - An optional file path to filter the results.
   *
   * #### Notes
   * The first item in the list is considered the default.
   */
  listWidgetFactories(ext?: string): string[] {
    ext = ext || '';
    let factories: string[] = [];
    let options: Private.IWidgetFactoryEx;
    let name = '';
    // If an extension was given, filter by extension.
    // Make sure the modelFactory is registered.
    if (ext.length > 1) {
      if (ext in this._defaultWidgetFactories) {
        name = this._defaultWidgetFactories[ext];
        options = this._widgetFactories[name];
        if (options.modelName in this._modelFactories) {
          factories.push(name);
        }
      }
    }
    // Add the rest of the valid widgetFactories that can open the path.
    for (name in this._widgetFactories) {
      if (factories.indexOf(name) !== -1) {
        continue;
      }
      options = this._widgetFactories[name];
      if (!(options.modelName in this._modelFactories)) {
        continue;
      }
      let exts = options.fileExtensions;
      if ((exts.indexOf(ext) !== -1) || (exts.indexOf('.*') !== -1)) {
        factories.push(name);
      }
    }
    // Add the default widget if it was not already added.
    name = this._defaultWidgetFactory;
    if (name && factories.indexOf(name) === -1) {
      options = this._widgetFactories[name];
      if (options.modelName in this._modelFactories) {
        factories.push(name);
      }
    }
    return factories;
  }

  /**
   * Get a list of file types that have been registered.
   */
  listFileTypes(): IFileType[] {
    return this._fileTypes.slice();
  }

  /**
   * Get the ordered list of file creator names.
   */
  listCreators(): IFileCreator[] {
    return this._creators.slice();
  }

  /**
   * Get the kernel preference.
   */
  getKernelPreference(ext: string, widgetName: string): IKernelPreference {
    let widgetFactoryEx = this._getWidgetFactoryEx(widgetName);
    let modelFactory = this.getModelFactory(widgetName);
    let language = modelFactory.preferredLanguage(ext);
    return {
      language,
      preferKernel: widgetFactoryEx.preferKernel,
      canStartKernel: widgetFactoryEx.canStartKernel
    };
  }

  /**
   * Get the model factory registered for a given widget factory.
   *
   */
  getModelFactory(widgetName: string): IModelFactory {
    let wFactoryEx = this._getWidgetFactoryEx(widgetName);
    if (!wFactoryEx) {
      return;
    }
    return this._modelFactories[wFactoryEx.modelName];
  }

  /**
   * Get a widget factory by name.
   */
  getWidgetFactory(widgetName: string): IWidgetFactory<Widget> {
    return this._getWidgetFactoryEx(widgetName).factory;
  }

  /**
   * Get the registered extensions for a given widget.
   */
  getWidgetExtensions(widgetName: string): IWidgetExtension<Widget>[] {
    if (!(widgetName in this._extenders)) {
      return [];
    }
    return this._extenders[widgetName].slice();
  }

  /**
   * Get the appropriate widget factory by name.
   */
  private _getWidgetFactoryEx(widgetName: string): Private.IWidgetFactoryEx {
    let options: Private.IWidgetFactoryEx;
    if (widgetName === 'default') {
      options = this._widgetFactories[this._defaultWidgetFactory];
    } else {
      options = this._widgetFactories[widgetName];
    }
    return options;
  }

  private _modelFactories: { [key: string]: IModelFactory } = Object.create(null);
  private _widgetFactories: { [key: string]: Private.IWidgetFactoryEx } = Object.create(null);
  private _defaultWidgetFactory = '';
  private _defaultWidgetFactories: { [key: string]: string } = Object.create(null);
  private _fileTypes: IFileType[] = [];
  private _creators: IFileCreator[] = [];
  private _extenders: { [key: string] : IWidgetExtension<Widget>[] } = Object.create(null);
}

/**
 * A private namespace for DocumentRegistry data.
 */
namespace Private {
  /**
   * An extended interface for a widget factory and its options.
   */
  export
  interface IWidgetFactoryEx extends IWidgetFactoryOptions {
    factory: IWidgetFactory<Widget>;
  }
}


text:
<!doctype html>

  <link rel="shortcut icon" href="static/images/favicon.ico" type="image/x-icon">
  <title>custombuttonrenderer.js (Closure Library API Documentation - JavaScript)</title>
  <link rel="stylesheet" href="static/css/base.css">
  <link rel="stylesheet" href="static/css/doc.css">
  <link rel="stylesheet" href="static/css/sidetree.css">
  <link rel="stylesheet" href="static/css/prettify.css">

  <meta charset="utf8">

      Closure Library API Documentation

        Go to class or file:
        <input type="text" id="ac">

custombuttonrenderer.js

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

// Copyright 2008 Google Inc. All Rights Reserved.

/**
 * @fileoverview A custom button renderer that uses CSS voodoo to render a
 * button-like object with fake rounded corners.
 *
 */

goog.provide('goog.ui.CustomButtonRenderer');

goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.string');
goog.require('goog.ui.ButtonRenderer');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.INLINE_BLOCK_CLASSNAME');

/**
 * Custom renderer for {@link goog.ui.Button}s.  Custom buttons can contain
 * almost arbitrary HTML content, will flow like inline elements, but can be
 * styled like block-level elements.
 *
 * @constructor
 * @extends {goog.ui.ButtonRenderer}
 */
goog.ui.CustomButtonRenderer = function() {
  goog.ui.ButtonRenderer.call(this);
};
goog.inherits(goog.ui.CustomButtonRenderer, goog.ui.ButtonRenderer);
goog.addSingletonGetter(goog.ui.CustomButtonRenderer);

/**
 * Default CSS class to be applied to the root element of components rendered
 * by this renderer.
 * @type {string}
 */
goog.ui.CustomButtonRenderer.CSS_CLASS = goog.getCssName('goog-custom-button');

/**
 * Returns the button's contents wrapped in the following DOM structure:
 *    <div class="goog-inline-block goog-custom-button">
 *      <div class="goog-inline-block goog-custom-button-outer-box">
 *        <div class="goog-inline-block goog-custom-button-inner-box">
 *          Contents...
 *        </div>
 *      </div>
 *    </div>
 * Overrides {@link goog.ui.ButtonRenderer#createDom}.
 * @param {goog.ui.Button} button Button to render.
 * @return {Element} Root element for the button.
 */
goog.ui.CustomButtonRenderer.prototype.createDom = function(button) {
  var classNames = this.getClassNames(button);
  var attributes = {
    'class': goog.ui.INLINE_BLOCK_CLASSNAME + ' ' + classNames.join(' '),
    'title': button.getTooltip() || ''
  };
  return button.getDomHelper().createDom('div', attributes,
      this.createButton(button.getContent(), button.getDomHelper()));
};

/**
 * Takes the button's root element and returns the parent element of the
 * button's contents.  Overrides the superclass implementation by taking
 * the nested DIV structure of custom buttons into account.
 * @param {Element?} element Root element of the button whose content
 *     element is to be returned.
 * @return {Element?} The button's content element (if any).
 */
goog.ui.CustomButtonRenderer.prototype.getContentElement = function(element) {
  return element && /** @type {Element?} */ (element.firstChild.firstChild);
};

/**
 * Takes a text caption or existing DOM structure, and returns the content
 * wrapped in a pseudo-rounded-corner box.  Creates the following DOM structure:
 *  <div class="goog-inline-block goog-custom-button-outer-box">
 *    <div class="goog-inline-block goog-custom-button-inner-box">
 *      Contents...
 *    </div>
 *  </div>
 * Used by both {@link #createDom} and {@link #decorate}.  To be overridden
 * by subclasses.
 * @param {goog.ui.ControlContent} content Text caption or DOM structure to wrap
 *     in a box.
 * @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
 * @return {Element} Pseudo-rounded-corner box containing the content.
 */
goog.ui.CustomButtonRenderer.prototype.createButton = function(content, dom) {
  return dom.createDom('div',
      goog.ui.INLINE_BLOCK_CLASSNAME + ' ' +
      goog.getCssName(this.getCssClass(), 'outer-box'),
      dom.createDom('div',
          goog.ui.INLINE_BLOCK_CLASSNAME + ' ' +
          goog.getCssName(this.getCssClass(), 'inner-box'), content));
};

/**
 * Returns true if this renderer can decorate the element.  Overrides
 * {@link goog.ui.ButtonRenderer#canDecorate} by returning true if the
 * element is a DIV, false otherwise.
 * @param {Element} element Element to decorate.
 * @return {boolean} Whether the renderer can decorate the element.
 */
goog.ui.CustomButtonRenderer.prototype.canDecorate = function(element) {
  return element.tagName == 'DIV';
};

/**
 * Check if the button's element has a box structure.
 * @param {goog.ui.Button} button Button instance whose structure is being
 *     checked.
 * @param {Element} element Element of the button.
 * @return {boolean} Whether the element has a box structure.
 * @protected
 */
goog.ui.CustomButtonRenderer.prototype.hasBoxStructure = function(
    button, element) {
  var outer = button.getDomHelper().getFirstElementChild(element);
  if (outer && outer.className.indexOf(goog.getCssName(this.getCssClass(),
          'outer-box')) != -1) {
    var inner = button.getDomHelper().getFirstElementChild(outer);
    if (inner && inner.className.indexOf(goog.getCssName(this.getCssClass(),
            'inner-box')) != -1) {
      // We have a proper box structure.
      return true;
    }
  }
  return false;
};

/**
 * Takes an existing element and decorates it with the custom button control.
 * Initializes the control's ID, content, tooltip, value, and state based
 * on the ID of the element, its child nodes, and its CSS classes, respectively.
 * Returns the element.  Overrides {@link goog.ui.ButtonRenderer#decorate}.
 * @param {goog.ui.Button} button Button instance to decorate the element.
 * @param {Element} element Element to decorate.
 * @return {Element} Decorated element.
 */
goog.ui.CustomButtonRenderer.prototype.decorate = function(button, element) {
  // Trim text nodes in the element's child node list; otherwise madness
  // ensues (i.e. on Gecko, buttons will flicker and shift when moused over).
  goog.ui.CustomButtonRenderer.trimTextNodes_(element, true);
  goog.ui.CustomButtonRenderer.trimTextNodes_(element, false);

  // Create the buttom dom if it has not been created.
  if (!this.hasBoxStructure(button, element)) {
    element.appendChild(
        this.createButton(element.childNodes, button.getDomHelper()));
  }

  goog.dom.classes.add(element,
      goog.ui.INLINE_BLOCK_CLASSNAME, this.getCssClass());
  return goog.ui.CustomButtonRenderer.superClass_.decorate.call(this, button,
      element);
};

/**
 * Returns the CSS class to be applied to the root element of components
 * rendered using this renderer.
 * @return {string} Renderer-specific CSS class.
 */
goog.ui.CustomButtonRenderer.prototype.getCssClass = function() {
  return goog.ui.CustomButtonRenderer.CSS_CLASS;
};

/**
 * Takes an element and removes leading or trailing whitespace from the start
 * or the end of its list of child nodes.  The Boolean argument determines
 * whether to trim from the start or the end of the node list.  Empty text
 * nodes are removed, and the first non-empty text node is trimmed from the
 * left or the right as appropriate.  For example,
 *    <div class="goog-inline-block">
 *      #text ""
 *      #text "\n    Hello "
 *      <span>...</span>
 *      #text " World!    \n"
 *      #text ""
 *    </div>
 * becomes
 *    <div class="goog-inline-block">
 *      #text "Hello "
 *      <span>...</span>
 *      #text " World!"
 *    </div>
 * This is essential for Gecko, where leading/trailing whitespace messes with
 * the layout of elements with -moz-inline-box (used in goog-inline-block), and
 * optional but harmless for non-Gecko.
 *
 * @param {Element} element Element whose child node list is to be trimmed.
 * @param {boolean} fromStart Whether to trim from the start or from the end.
 * @private
 */
goog.ui.CustomButtonRenderer.trimTextNodes_ = function(element, fromStart) {
  if (element) {
    var node = fromStart ? element.firstChild : element.lastChild, next;
    // Tag soup HTML may result in a DOM where siblings have different parents.
    while (node && node.parentNode == element) {
      // Get the next/previous sibling here, since the node may be removed.
      next = fromStart ? node.nextSibling : node.previousSibling;
      if (node.nodeType == goog.dom.NodeType.TEXT) {
        // Found a text node.
        var text = node.nodeValue;
        if (goog.string.trim(text) == '') {
          // Found an empty text node; remove it.
          element.removeChild(node);
        } else {
          // Found a non-empty text node; trim from the start/end, then exit.
          node.nodeValue = fromStart ?
              goog.string.trimLeft(text) : goog.string.trimRight(text);
          break;
        }
      } else {
        // Found a non-text node; done.
        break;
      }
      node = next;
    }
  }
};


text:
class CreateSkillTypes < ActiveRecord::Migration
  def change
    create_table :skill_types do |t|
      t.string :reference, unique: true
      t.timestamps null: false
    end
  end
end


text:
/**
 *
 */
package edu.rupp.rmi.students.shared;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;

import edu.rupp.rmi.students.shared.vo.StudentVO;

/**
 * @author sok.pongsametrey
 *
 */
public interface IRemoteStudent extends Remote {

	/** to insert student record to database */
	public void save (StudentVO studentVO) throws RemoteException;
	/** to update the existing record based on Id */
	public void update (StudentVO studentVO) throws RemoteException;
	/** to delete record based on Id */
	public void delete (int studentId) throws RemoteException;

	/** to get all the available students in the table */
	public List<StudentVO> findAll () throws RemoteException;
	/** get a student record based on Id given (only one record retrieved) */
	public StudentVO findById (int studentId) throws RemoteException;
	/** get a student record based on name given */
	public List<StudentVO> findByName (String name) throws RemoteException;
	/** get list of student records based on Course given (possibly many records retrieved) */
	public List<StudentVO> findByCourse (String course) throws RemoteException;

}


text:
<xml xmlns:o="urn:schemas-microsoft-com:office:office">
 <o:MainFile HRef="../BT%20Food%20Menu%201_4_16.htm"/>
 <o:File HRef="preview.wmf"/>
 <o:File HRef="themedata.thmx"/>
 <o:File HRef="colorschememapping.xml"/>
 <o:File HRef="filelist.xml"/>
</xml>


text:
// Pebble/src/framework/dr/transport/buffer_transport.h

#ifndef BUBBLEFS_UTILS_PEBBLE_DR_BUFFER_TRANSPORT_H_
#define BUBBLEFS_UTILS_PEBBLE_DR_BUFFER_TRANSPORT_H_

#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
#include "utils/pebble_dr_virtual_transport.h"

#ifdef __GNUC__
#define TDB_LIKELY(val) (__builtin_expect((val), 1))
#define TDB_UNLIKELY(val) (__builtin_expect((val), 0))
#else
#define TDB_LIKELY(val) (val)
#define TDB_UNLIKELY(val) (val)
#endif

namespace bubblefs {
namespace mypebble { namespace dr { namespace transport {

/**
 * Base class for all transports that use read/write buffers for performance.
 *
 * TBufferBase is designed to implement the fast-path "memcpy" style
 * operations that work in the common case.  It does so with small and
 * (eventually) nonvirtual, inlinable methods.  TBufferBase is an abstract
 * class.  Subclasses are expected to define the "slow path" operations
 * that have to be done when the buffers are full or empty.
 *
 */
class TBufferBase : public TVirtualTransport<TBufferBase> {
public:
    /**
     * Fast-path read.
     *
     * When we have enough data buffered to fulfill the read, we can satisfy it
     * with a single memcpy, then adjust our internal pointers.  If the buffer
     * is empty, we call out to our slow path, implemented by a subclass.
     * This method is meant to eventually be nonvirtual and inlinable.
     */
    uint32_t read(uint8_t* buf, uint32_t len) {
        uint8_t* new_rBase = rBase_ + len;
        if (TDB_LIKELY(new_rBase <= rBound_)) {
            std::memcpy(buf, rBase_, len);
            rBase_ = new_rBase;
            return len;
        }
        return readSlow(buf, len);
    }

    /**
     * Shortcutted version of readAll.
     */
    uint32_t readAll(uint8_t* buf, uint32_t len) {
        uint8_t* new_rBase = rBase_ + len;
        if (TDB_LIKELY(new_rBase <= rBound_)) {
            std::memcpy(buf, rBase_, len);
            rBase_ = new_rBase;
            return len;
        }
        return dr::transport::readAll(*this, buf, len);
    }

    /**
     * Fast-path write.
     *
     * When we have enough empty space in our buffer to accomodate the write, we
     * can satisfy it with a single memcpy, then adjust our internal pointers.
     * If the buffer is full, we call out to our slow path, implemented by a
     * subclass.  This method is meant to eventually be nonvirtual and
     * inlinable.
     */
    void write(const uint8_t* buf, uint32_t len) {
        uint8_t* new_wBase = wBase_ + len;
        if (TDB_LIKELY(new_wBase <= wBound_)) {
            std::memcpy(wBase_, buf, len);
            wBase_ = new_wBase;
            return;
        }
        writeSlow(buf, len);
    }

    /**
     * Fast-path borrow.  A lot like the fast-path read.
     */
    const uint8_t* borrow(uint8_t* buf, uint32_t* len) {
        if (TDB_LIKELY(static_cast<std::ptrdiff_t>(*len) <= rBound_ - rBase_)) {
            // With strict aliasing, writing to len shouldn't force us to
            // refetch rBase_ from memory.  TODO(dreiss): Verify this.
            *len = static_cast<uint32_t>(rBound_ - rBase_);
            return rBase_;
        }
        return borrowSlow(buf, len);
    }

    /**
     * Consume doesn't require a slow path.
     */
    void consume(uint32_t len) {
        if (TDB_LIKELY(static_cast<std::ptrdiff_t>(len) <= rBound_ - rBase_)) {
            rBase_ += len;
        } else {
            throw TTransportException(TTransportException::BAD_ARGS,
                                "consume did not follow a borrow.");
        }
    }

    /**
     * 支持块协议,以消息包为单位收发,接收到完整包后写入buff,供应用阻塞read
     * @return : 0-未收到包
     */
    virtual int recv() { return 0; }

protected:
    /// Slow path read.
    virtual uint32_t readSlow(uint8_t* buf, uint32_t len) = 0;

    /// Slow path write.
    virtual void writeSlow(const uint8_t* buf, uint32_t len) = 0;

    /**
     * Slow path borrow.
     *
     * POSTCONDITION: return == NULL || rBound_ - rBase_ >= *len
     */
    virtual const uint8_t* borrowSlow(uint8_t* buf, uint32_t* len) = 0;

    /**
     * Trivial constructor.
     *
     * Initialize pointers safely.  Constructing is not a very
     * performance-sensitive operation, so it is okay to just leave it to
     * the concrete class to set up pointers correctly.
     */
    TBufferBase()
        : rBase_(NULL)
        , rBound_(NULL)
        , wBase_(NULL)
        , wBound_(NULL)
    {}

    /// Convenience mutator for setting the read buffer.
    void setReadBuffer(uint8_t* buf, uint32_t len) {
        rBase_ = buf;
        rBound_ = buf+len;
    }

    /// Convenience mutator for setting the write buffer.
    void setWriteBuffer(uint8_t* buf, uint32_t len) {
        wBase_ = buf;
        wBound_ = buf+len;
    }

    virtual ~TBufferBase() {}

    /// Reads begin here.
    uint8_t* rBase_;
    /// Reads may extend to just before here.
    uint8_t* rBound_;

    /// Writes begin here.
    uint8_t* wBase_;
    /// Writes may extend to just before here.
    uint8_t* wBound_;
};

/**
 * A memory buffer is a tranpsort that simply reads from and writes to an
 * in memory buffer. Anytime you call write on it, the data is simply placed
 * into a buffer, and anytime you call read, data is read from that buffer.
 *
 * The buffers are allocated using C constructs malloc,realloc, and the size
 * doubles as necessary.  We've considered using scoped
 *
 */
class TMemoryBuffer : public TVirtualTransport<TMemoryBuffer, TBufferBase> {
private:
    // Common initialization done by all constructors.
    void initCommon(uint8_t* buf, uint32_t size, bool owner, uint32_t wPos) {
        if (buf == NULL && size != 0) {
            assert(owner);
            buf = reinterpret_cast<uint8_t*>(malloc(size));
            if (buf == NULL) {
                throw std::bad_alloc();
            }
        }

        buffer_ = buf;
        bufferSize_ = size;

        rBase_ = buffer_;
        rBound_ = buffer_ + wPos;
        // TODO Investigate NULL-ing this if !owner.
        // wBase_ = buffer_ + wPos; // 可写的模式
        wBase_ = buffer_;
        wBound_ = buffer_ + bufferSize_;

        owner_ = owner;

        // rBound_ is really an artifact.  In principle, it should always be
        // equal to wBase_.  We update it in a few places (computeRead, etc.).
    }

public:
    static const uint32_t defaultSize = 1024 * 1024 * 2; // 2M
    static const uint32_t maxSize     = 1024 * 1024 * 8; // 8M

    /**
     * This enum specifies how a TMemoryBuffer should treat
     * memory passed to it via constructors or resetBuffer.
     *
     * OBSERVE:
     *   TMemoryBuffer will simply store a pointer to the memory.
     *   It is the callers responsibility to ensure that the pointer
     *   remains valid for the lifetime of the TMemoryBuffer,
     *   and that it is properly cleaned up.
     *   Note that no data can be written to observed buffers.
     *
     * COPY:
     *   TMemoryBuffer will make an internal copy of the buffer.
     *   The caller has no responsibilities.
     *
     * TAKE_OWNERSHIP:
     *   TMemoryBuffer will become the "owner" of the buffer,
     *   and will be responsible for freeing it.
     *   The membory must have been allocated with malloc.
     */
    // TODO: OBSERVE改造
    enum MemoryPolicy
    { OBSERVE = 1
    , COPY = 2
    , TAKE_OWNERSHIP = 3
    };

    /**
     * Construct a TMemoryBuffer with a default-sized buffer,
     * owned by the TMemoryBuffer object.
     */
    TMemoryBuffer() {
        initCommon(NULL, defaultSize, true, 0);
    }

    /**
     * Construct a TMemoryBuffer with a buffer of a specified size,
     * owned by the TMemoryBuffer object.
     *
     * @param sz  The initial size of the buffer.
     */
    explicit TMemoryBuffer(uint32_t sz) {
        initCommon(NULL, sz, true, 0);
    }

    /**
     * Construct a TMemoryBuffer with buf as its initial contents.
     *
     * @param buf    The initial contents of the buffer.
     *               Note that, while buf is a non-const pointer,
     *               TMemoryBuffer will not write to it if policy == OBSERVE,
     *               so it is safe to const_cast<uint8_t*>(whatever).
     * @param sz     The size of @c buf.
     * @param policy See @link MemoryPolicy @endlink .
     */
    TMemoryBuffer(uint8_t* buf, uint32_t sz, MemoryPolicy policy = OBSERVE) {
        if (buf == NULL && sz != 0) {
            throw TTransportException(TTransportException::BAD_ARGS,
                                "TMemoryBuffer given null buffer with non-zero size.");
        }

        switch (policy) {
            case OBSERVE:
            case TAKE_OWNERSHIP:
                initCommon(buf, sz, policy == TAKE_OWNERSHIP, sz);
                break;
            case COPY:
                initCommon(NULL, sz, true, 0);
                this->write(buf, sz);
                break;
            default:
                throw TTransportException(TTransportException::BAD_ARGS,
                                    "Invalid MemoryPolicy for TMemoryBuffer");
        }
    }

    ~TMemoryBuffer() {
        if (owner_) {
            free(buffer_);
        }
    }

    bool isOpen() {
        return true;
    }

    bool peek() {
        return (rBase_ < wBase_);
    }

    void open() {}

    void close() {}

    // TODO: Make bufPtr const.
    void getBuffer(uint8_t** bufPtr, uint32_t* sz) {
        *bufPtr = rBase_;
        *sz = static_cast<uint32_t>(wBase_ - rBase_);
    }

    std::string getBufferAsString() {
        if (buffer_ == NULL) {
            return "";
        }
        uint8_t* buf;
        uint32_t sz;
        getBuffer(&buf, &sz);
        return std::string(reinterpret_cast<char*>(buf), (std::string::size_type)sz);
    }

    void appendBufferToString(std::string& str) { // NOLINT
        if (buffer_ == NULL) {
            return;
        }
        uint8_t* buf;
        uint32_t sz;
        getBuffer(&buf, &sz);
        str.append(reinterpret_cast<char*>(buf), sz);
    }

    void resetBuffer() {
        rBase_ = buffer_;
        rBound_ = buffer_;
        wBase_ = buffer_;
        // It isn't safe to write into a buffer we don't own.
        if (!owner_) {
            wBound_ = wBase_;
            bufferSize_ = 0;
        }
    }

    /// See constructor documentation.
    void resetBuffer(uint8_t* buf, uint32_t sz, MemoryPolicy policy = OBSERVE) {
        // Use a variant of the copy-and-swap trick for assignment operators.
        // This is sub-optimal in terms of performance for two reasons:
        //   1/ The constructing and swapping of the (small) values
        //      in the temporary object takes some time, and is not necessary.
        //   2/ If policy == COPY, we allocate the new buffer before
        //      freeing the old one, precluding the possibility of
        //      reusing that memory.
        // I doubt that either of these problems could be optimized away,
        // but the second is probably no a common case, and the first is minor.
        // I don't expect resetBuffer to be a common operation, so I'm willing to
        // bite the performance bullet to make the method this simple.

        // Construct the new buffer.
        TMemoryBuffer new_buffer(buf, sz, policy);
        // Move it into ourself.
        this->swap(new_buffer);
        // Our old self gets destroyed.
    }

    /// See constructor documentation.
    void resetBuffer(uint32_t sz) {
        // Construct the new buffer.
        TMemoryBuffer new_buffer(sz);
        // Move it into ourself.
        this->swap(new_buffer);
        // Our old self gets destroyed.
    }

    std::string readAsString(uint32_t len) {
        std::string str;
        (void)readAppendToString(str, len);
        return str;
    }

    uint32_t readAppendToString(std::string& str, uint32_t len); // NOLINT

    // return number of bytes read
    uint32_t readEnd() {
        // This cast should be safe, because buffer_'s size is a uint32_t
        uint32_t bytes = static_cast<uint32_t>(rBase_ - buffer_);
        if (rBase_ == wBase_) {
            resetBuffer();
        }
        return bytes;
    }

    // Return number of bytes written
    uint32_t writeEnd() {
        // This cast should be safe, because buffer_'s size is a uint32_t
        return static_cast<uint32_t>(wBase_ - buffer_);
    }

    uint32_t available_read() const {
        // Remember, wBase_ is the real rBound_.
        return static_cast<uint32_t>(wBase_ - rBase_);
    }

    uint32_t available_write() const {
        return static_cast<uint32_t>(wBound_ - wBase_);
    }

    // Returns a pointer to where the client can write data to append to
    // the TMemoryBuffer, and ensures the buffer is big enough to accomodate a
    // write of the provided length.  The returned pointer is very convenient for
    // passing to read(), recv(), or similar. You must call wroteBytes() as soon
    // as data is written or the buffer will not be aware that data has changed.
    uint8_t* getWritePtr(uint32_t len) {
        ensureCanWrite(len);
        return wBase_;
    }

    // Informs the buffer that the client has written 'len' bytes into storage
    // that had been provided by getWritePtr().
    void wroteBytes(uint32_t len);

    /*
     * TVirtualTransport provides a default implementation of readAll().
     * We want to use the TBufferBase version instead.
     */
    uint32_t readAll(uint8_t* buf, uint32_t len) {
        return TBufferBase::readAll(buf, len);
    }

protected:
    void swap(TMemoryBuffer& that) {
        using std::swap;
        swap(buffer_,     that.buffer_);
        swap(bufferSize_, that.bufferSize_);

        swap(rBase_,      that.rBase_);
        swap(rBound_,     that.rBound_);
        swap(wBase_,      that.wBase_);
        swap(wBound_,     that.wBound_);

        swap(owner_,      that.owner_);
    }

    // Make sure there's at least 'len' bytes available for writing.
    void ensureCanWrite(uint32_t len);

    // Compute the position and available data for reading.
    void computeRead(uint32_t len, uint8_t** out_start, uint32_t* out_give);

    uint32_t readSlow(uint8_t* buf, uint32_t len);

    void writeSlow(const uint8_t* buf, uint32_t len);

    const uint8_t* borrowSlow(uint8_t* buf, uint32_t* len);

    // Data buffer
    uint8_t* buffer_;

    // Allocated buffer size
    uint32_t bufferSize_;

    // Is this object the owner of the buffer?
    bool owner_;

    // Don't forget to update constrctors, initCommon, and swap if
    // you add new members.
};

} // namespace transport
} // namespace dr
} // namespace mypebble
} // namespace bubblefs

#endif // BUBBLEFS_UTILS_PEBBLE_DR_BUFFER_TRANSPORT_H_


text:
var proxyquire = require('proxyquire');

describe("DefaultMonthlyPlugin", function() {
    describe("#createColor()", function() {
        it("should return a color code for January", function() {
            var plugin = new (createMockedPlugin("01"))();
            expect(plugin.createColor()).to.equal("#FFD700");
        });
        it("should return a color code for February", function() {
            var plugin = new (createMockedPlugin("02"))();
            expect(plugin.createColor()).to.equal("#5E2D79");
        });
        it("should return a color code for March", function() {
            var plugin = new (createMockedPlugin("03"))();
            expect(plugin.createColor()).to.equal("#B22222");
        });
        it("should return a color code for April", function() {
            var plugin = new (createMockedPlugin("04"))();
            expect(plugin.createColor()).to.equal("#FFBBFF");
        });
        it("should return a color code for May", function() {
            var plugin = new (createMockedPlugin("05"))();
            expect(plugin.createColor()).to.equal("#278524");
        });
        it("should return a color code for June", function() {
            var plugin = new (createMockedPlugin("06"))();
            expect(plugin.createColor()).to.equal("#80461B");
        });
        it("should return a color code for July", function() {
            var plugin = new (createMockedPlugin("07"))();
            expect(plugin.createColor()).to.equal("#C87533");
        });
        it("should return a color code for August", function() {
            var plugin = new (createMockedPlugin("08"))();
            expect(plugin.createColor()).to.equal("#C0C0C0");
        });
        it("should return a color code for September", function() {
            var plugin = new (createMockedPlugin("09"))();
            expect(plugin.createColor()).to.equal("#FFFF00");
        });
        it("should return a color code for October", function() {
            var plugin = new (createMockedPlugin("10"))();
            expect(plugin.createColor()).to.equal("#FF7518");
        });
        it("should return a color code for November", function() {
            var plugin = new (createMockedPlugin("11"))();
            expect(plugin.createColor()).to.equal("#FFFFFF");
        });
        it("should return a color code for December", function() {
            var plugin = new (createMockedPlugin("12"))();
            expect(plugin.createColor()).to.equal("#0EBFE9");
        });
    });
});

var createMockedPlugin = function(response) {
    var moment = function() {
        return { format: function(fmtStr) { return response } };
    }
    return proxyquire('../../src/plugins/defaultMonthlyPlugin.js', { "moment": moment });
};


text:
> Readme in [Chinese 中文](https://github.com/monque/PHP-Migration/tree/master/README_ZH.md)

[![Build Status](https://travis-ci.org/monque/PHP-Migration.svg)](https://travis-ci.org/monque/PHP-Migration)
[![Total Downloads](https://poser.pugx.org/monque/PHP-Migration/d/total.svg)](https://packagist.org/packages/monque/PHP-Migration)
[![Latest Stable Version](https://poser.pugx.org/monque/PHP-Migration/v/stable.svg)](https://packagist.org/packages/monque/PHP-Migration)
[![License](https://poser.pugx.org/monque/PHP-Migration/license.svg)](https://packagist.org/packages/monque/PHP-Migration)

This is a static analyzer for PHP version migration and compatibility checking.

It can suppose your current code running under the new version of PHP then do
checking, and provide advice and treatment.

And it can simplify the process of upgrading PHP. Its goal is instead of manual
checking.

Features:
- Wide coverage, checks most of the changes which introduced in PHP 5.3 - 7.0.
- Strict, without missing any risk.
- Zero configuration, run directly after download.
- Simply add custom checks.

> Compare to the similar project [PHP Compatibility](https://github.com/wimg/PHPCompatibility)
> `PHP Compatibility` is a set of sniffs for `PHP_CodeSniffer`, therefore it
> lacks flexibility and can not checks more changes.
> *just objective comparison*

**Notice: this project is in beta stage, feel free to report any issues.**

## Install / Usage

1. You can download a executable [Phar](http://php.net/manual/en/book.phar.php) file
    ```
    wget https://github.com/monque/PHP-Migration/releases/download/v0.2.2/phpmig.phar
    ```

2. Use the following command to check PHP file
    ```
    php phpmig.phar sample.php
    ```

    Suppose these code stored in `sample.php`
    ``` php
    <?php
    // Fatal error: Only variables can be passed by reference
    array_shift(array(1, 2));
    sort(array(1, 2, 3));

    // __DIR__ is pre-defined
    define('__DIR__', dirname(__FILE__));

    // Fatal error: Cannot redeclare class_alias()
    function class_alias() {}

    // This is fine
    if (!function_exists('class_alias')) {
        function class_alias() {}
    }

    // Fatal error: Call-time pass-by-reference has been removed
    array_map('trim', &$_SERVER);

    // Fatal error: 'break' operator with non-constant operand is no longer supported
    while (true) {
        break $a;
    }

    // Fatal error: Cannot re-assign auto-global variable _GET
    function ohno($_GET) {}

    // Array keys won't be overwritten when defining an array as a property of a class via an array literal
    class C {
        const ONE = 1;
        public $array = [
            self::ONE => 'foo',
            'bar',
            'quux',
        ];
    }

    // set_exception_handler() is no longer guaranteed to receive Exception objects
    set_exception_handler(function (Exception $e) { });

    // Changes to the handling of indirect variables, properties, and methods
    echo $$foo['bar']['baz'];

    // foreach no longer changes the internal array pointer
    foreach ($list as &$row) {
        current($list);
    }
    ```

3. Output report
    Each columns means: Line Number, Level, Identified, Version, Message
    ```
    File: sample.php
    --------------------------------------------------------------------------------
	Found 11 spot(s), 10 identified
	--------------------------------------------------------------------------------
        3 | FATAL      | * | 5.3.0 | Only variables can be passed by reference
        4 | FATAL      | * | 5.3.0 | Only variables can be passed by reference
        7 | WARNING    | * | 5.3.0 | Constant "__DIR__" already defined
       10 | FATAL      | * | 5.3.0 | Cannot redeclare class_alias()
       18 | FATAL      | * | 5.4.0 | Call-time pass-by-reference has been removed
       22 | FATAL      | * | 5.4.0 | break operator with non-constant operand is no longer supported
       26 | FATAL      | * | 5.4.0 | Cannot re-assign auto-global variable
       31 | WARNING    |   | 5.6.0 | Array key may be overwritten when defining as a property and using constants
       39 | WARNING    | * | 7.0.0 | set_exception_handler() is no longer guaranteed to receive Exception objects
       42 | WARNING    | * | 7.0.0 | Different behavior between PHP 5/7
       46 | NOTICE     | * | 7.0.0 | foreach no longer changes the internal array pointer
    --------------------------------------------------------------------------------
    ```
    > The third field `Identified` will be explained at bottom.

### Set Selection

A Checking Set contains muiltiple Check Class, and the dependence of Set can be
specified.

List all sets through command `php phpmig.phar -l`.

```
classtree  => List contents of classes in a tree-like format
to53       => Migrating from ANY version to PHP 5.3.x
to54       => Migrating from ANY version to PHP 5.4.x
to55       => Migrating from ANY version to PHP 5.5.x
to56       => Migrating from ANY version to PHP 5.6.x
to70       => Migrating from ANY version to PHP 7.0.x
v53        => Migrating from PHP 5.2.x to PHP 5.3.x
v54        => Migrating from PHP 5.3.x to PHP 5.4.x
v55        => Migrating from PHP 5.4.x to PHP 5.5.x
v56        => Migrating from PHP 5.5.x to PHP 5.6.x
v70        => Migrating from PHP 5.6.x to PHP 7.0.x
```

And add param `-s` like `php phpmig.phar -s <setname>` to select a set to use.

### Utility, print class tree

Like the common linux command `tree`, the following command will scan files and
output all classes in a tree-like format.
```
php phpmig.phar -s classtree .
```

Output:
```
|-- PhpMigration\App
|-- PhpMigration\Changes\AbstractChange
|   |-- PhpMigration\Changes\AbstractIntroduced
|   |   |-- PhpMigration\Changes\v5dot3\Introduced
|   |   |-- PhpMigration\Changes\v5dot4\Introduced
|   |   |-- PhpMigration\Changes\v5dot5\Introduced
|   |   |-- PhpMigration\Changes\v5dot6\Introduced
|   |   `-- PhpMigration\Changes\v7dot0\Introduced
|   |-- PhpMigration\Changes\AbstractKeywordReserved
|   |   |-- PhpMigration\Changes\v5dot3\IncompReserved
|   |   `-- PhpMigration\Changes\v5dot4\IncompReserved
|   |-- PhpMigration\Changes\AbstractRemoved
|   |   |-- PhpMigration\Changes\v5dot3\Removed
|   |   |-- PhpMigration\Changes\v5dot4\Removed
|   |   |-- PhpMigration\Changes\v5dot5\Removed
|   |   |-- PhpMigration\Changes\v5dot6\Removed
|   |   `-- PhpMigration\Changes\v7dot0\Removed
|   |-- PhpMigration\Changes\ClassTree
|   |-- PhpMigration\Changes\Dev
|   |-- PhpMigration\Changes\v5dot3\Deprecated
|   |-- PhpMigration\Changes\v5dot3\IncompByReference
|   |-- PhpMigration\Changes\v5dot3\IncompCallFromGlobal
|   |-- PhpMigration\Changes\v5dot3\IncompMagic
|   |-- PhpMigration\Changes\v5dot3\IncompMagicInvoked
|   |-- PhpMigration\Changes\v5dot3\IncompMisc
|   |-- PhpMigration\Changes\v5dot4\Deprecated
|   |-- PhpMigration\Changes\v5dot4\IncompBreakContinue
|   |-- PhpMigration\Changes\v5dot4\IncompByReference
|   |-- PhpMigration\Changes\v5dot4\IncompHashAlgo
|   |-- PhpMigration\Changes\v5dot4\IncompMisc
|   |-- PhpMigration\Changes\v5dot4\IncompParamName
|   |-- PhpMigration\Changes\v5dot4\IncompRegister
|   |-- PhpMigration\Changes\v5dot5\Deprecated
|   |-- PhpMigration\Changes\v5dot5\IncompCaseInsensitive
|   |-- PhpMigration\Changes\v5dot5\IncompPack
|   |-- PhpMigration\Changes\v5dot6\Deprecated
|   |-- PhpMigration\Changes\v5dot6\IncompMisc
|   |-- PhpMigration\Changes\v5dot6\IncompPropertyArray
|   |-- PhpMigration\Changes\v7dot0\Deprecated
|   |-- PhpMigration\Changes\v7dot0\ExceptionHandle
|   |-- PhpMigration\Changes\v7dot0\ForeachLoop
|   |-- PhpMigration\Changes\v7dot0\FuncList
|   |-- PhpMigration\Changes\v7dot0\FuncParameters
|   |-- PhpMigration\Changes\v7dot0\IntegerOperation
|   |-- PhpMigration\Changes\v7dot0\KeywordReserved
|   |-- PhpMigration\Changes\v7dot0\ParseDifference
|   |-- PhpMigration\Changes\v7dot0\StringOperation
|   `-- PhpMigration\Changes\v7dot0\SwitchMultipleDefaults
|-- PhpMigration\CheckVisitor
|-- PhpMigration\Logger
|-- PhpMigration\ReduceVisitor
|-- PhpMigration\SymbolTable
|-- PhpMigration\Utils\FunctionListExporter
|-- PhpMigration\Utils\Logging
|-- PhpMigration\Utils\Packager
`-- PhpMigration\Utils\ParserHelper
```

### Manual Installation from Source

1. Clone this project to your local path
    ```
    git clone https://github.com/monque/PHP-Migration.git php-migration
    cd php-migration
    ```

2. Using [Composer](https://getcomposer.org/download/) to install dependencies
    ```
    curl -sS https://getcomposer.org/installer | php
    php composer.phar install
    ```

3. Verify it works
    ```
    php bin/phpmig
    ```

## Explaination

### Process Flow

![flow](http://p9.qhimg.com/t010392c0d7e3e01882.png)

### About the third field `Identified` in outputing

To be honest, not all code will be checked accurately as you expect.

Some changes will never be checked accurately, and it's has nothing to do with
someone's ability or technology.

For example, [`unpack()` changes in PHP
5.5](http://php.net/manual/en/migration55.incompatible.php#migration55.incompatible.pack),
it now keeps trailing NULL bytes when the "a" format code is used.

Code below:
``` php
<?php
unpack($obj->getFormat(), $data); // OMG, What is $obj? How getFormat() works?
unpack('b3', $data); // Works in new version
unpack('a3', $data); // Affected
```

But we can guess the value of variables, and make a level table:

| Level | Identified | Output |
| ---- | ---- | ---- |
| MUST affect | Yes | Yes |
| MUST NOT affect | Yes | No |
| MAY  affect | No | Yes |

So, finally output
```
--------------------------------------------------------------------------------
Found 2 spot(s), 1 identified
--------------------------------------------------------------------------------
   2 | WARNING    |   | 5.5.0 | Behavior of pack() with "a", "A" in format is changed
   4 | WARNING    | * | 5.5.0 | Behavior of pack() with "a", "A" in format is changed
--------------------------------------------------------------------------------
```

## License
This project is released under the [MIT license](http://opensource.org/licenses/MIT).


text:
<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/divider_content"
      android:layout_width="match_parent"
      android:layout_height="@dimen/divider_content_height"
      android:layout_marginLeft="@dimen/divider_margin_left"
      android:layout_marginRight="@dimen/divider_margin_right"
      android:background="@color/colorDD" />


text:
package org.kisoonlineapp.model;

import java.util.Calendar;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.kisoonlineapp.CalendarUtil;

/**
 *
 * @author berni
 */
public class AgeCalculatorTest {

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    private AgeCalculator instance;

    public AgeCalculatorTest() {
    }

    @Before
    public void setUp() {
        instance = new AgeCalculator();
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of calcAge method, of class AgeCalculator.
     */
    @Test
    public void testCalcAge() {
        Calendar now = null;
        Calendar dob = null;
        assertEquals(null, instance.calcAge(now, dob));
    }

    /**
     * Test of calcAge method, of class AgeCalculator.
     */
    @Test
    public void testCalcAge_NowMonthBefore() {
        Calendar now = CalendarUtil.createCalendarWith(2015, Calendar.JANUARY, 1, 0, 0, 0);
        Calendar dob = CalendarUtil.createCalendarWith(2010, Calendar.MAY, 1, 0, 0, 0);
        assertEquals(Integer.valueOf(4), instance.calcAge(now, dob));
    }

    /**
     * Test of calcAge method, of class AgeCalculator.
     */
    @Test
    public void testCalcAge_NowMonthAfter() {
        Calendar now = CalendarUtil.createCalendarWith(2015, Calendar.JUNE, 1, 0, 0, 0);
        Calendar dob = CalendarUtil.createCalendarWith(2010, Calendar.MAY, 1, 0, 0, 0);
        assertEquals(Integer.valueOf(5), instance.calcAge(now, dob));
    }

}


text:
layout: page
title: Omega International Award Ceremony
date: 2016-05-24
author: Robert Reyes
tags: weekly links, java
status: published
summary: Curabitur eget lacinia lectus, at elementum erat. Mauris lobortis lectus.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 04/10/2017
  endDate: 04/11/2017
  ctyhocn: PUBHSHX
  groupCode: OIAC
published: true
---
In tristique neque nibh, a tristique ante eleifend nec. Sed posuere efficitur est. Duis ac ipsum non nulla auctor rutrum quis sit amet massa. Cras non nunc ac neque condimentum consequat sed id lacus. Etiam auctor erat et magna pretium tincidunt eget pellentesque ante. Donec quis ipsum erat. Nam egestas auctor tincidunt.

* Pellentesque feugiat lorem at ante finibus, vel congue turpis accumsan.

Morbi mollis lorem diam, non dignissim mauris bibendum et. Fusce sed felis vel diam scelerisque vehicula. Phasellus quis ex convallis, molestie velit ut, cursus neque. Praesent mattis, elit et lacinia efficitur, arcu leo auctor erat, ut viverra lorem neque at justo. Nunc vitae dignissim elit, ac laoreet turpis. Phasellus risus erat, tincidunt a ipsum sit amet, vehicula cursus dui. Suspendisse vel magna vel dolor eleifend porta. Aliquam posuere est sed erat semper, eget sodales mauris tincidunt. Nam malesuada lacinia tellus lacinia interdum. Sed et nibh rhoncus, tristique dolor sed, porta nibh. Sed ut nisl at lacus luctus convallis. Duis vulputate nisl nec diam tempus lobortis. Proin euismod pulvinar ipsum ut tempor. Vestibulum in ante faucibus, tincidunt dolor in, laoreet est.


text:
package io.grpc.okhttp;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import com.squareup.okhttp.ConnectionSpec;
import io.grpc.NameResolver;
import io.grpc.internal.GrpcUtil;
import java.net.InetSocketAddress;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@link OkHttpChannelBuilder}.
 */
@RunWith(JUnit4.class)
public class OkHttpChannelBuilderTest {

  @Rule public final ExpectedException thrown = ExpectedException.none();

  @Test
  public void overrideAllowsInvalidAuthority() {
    OkHttpChannelBuilder builder = new OkHttpChannelBuilder("good", 1234) {
      @Override
      protected String checkAuthority(String authority) {
        return authority;
      }
    };

    builder.overrideAuthority("[invalidauthority")
        .negotiationType(NegotiationType.PLAINTEXT)
        .buildTransportFactory();
  }

  @Test
  public void failOverrideInvalidAuthority() {
    OkHttpChannelBuilder builder = new OkHttpChannelBuilder("good", 1234);

    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Invalid authority:");
    builder.overrideAuthority("[invalidauthority");
  }

  @Test
  public void failInvalidAuthority() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Invalid host or port");

    OkHttpChannelBuilder.forAddress("invalid_authority", 1234);
  }

  @Test
  public void failForUsingClearTextSpecDirectly() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("plaintext ConnectionSpec is not accepted");

    OkHttpChannelBuilder.forAddress("host", 1234).connectionSpec(ConnectionSpec.CLEARTEXT);
  }

  @Test
  public void allowUsingTlsConnectionSpec() {
    OkHttpChannelBuilder.forAddress("host", 1234).connectionSpec(ConnectionSpec.MODERN_TLS);
  }

  @Test
  public void usePlaintext_newClientTransportAllowed() {
    OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("host", 1234).usePlaintext(true);
    builder.buildTransportFactory().newClientTransport(new InetSocketAddress(5678),
        "dummy_authority", "dummy_userAgent");
  }

  @Test
  public void usePlaintextDefaultPort() {
    OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("host", 1234).usePlaintext(true);
    assertEquals(GrpcUtil.DEFAULT_PORT_PLAINTEXT,
        builder.getNameResolverParams().get(NameResolver.Factory.PARAMS_DEFAULT_PORT).intValue());
  }

  @Test
  public void usePlaintextCreatesNullSocketFactory() {
    OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("host", 1234);
    assertNotNull(builder.createSocketFactory());

    builder.usePlaintext(true);
    assertNull(builder.createSocketFactory());
  }
}


text:
<meta name="Copyright" content="1998-2014 The OpenSSL Project, http://www.openssl.org/">
<meta name="Author"    content="OpenSSL, openssl@openssl.org">
<meta name="Generator" content="WML 2.0.11 (19-Aug-2006)">
<meta name="Modified"  content="2014-07-03 05:00:13">
<title>OpenSSL: Documents, SSL_CTX_set_client_cert_cb(3)</title>

 Documents 	|
 openssl(1) 	|
 ssl(3) 	|
 crypto(3) 	|
 HOWTO 	|
 Wiki 	|
 FIPS140 	|
 misc

SSL_CTX_set_client_cert_cb(3)

NAME

SYNOPSIS

DESCRIPTION

NOTES

BUGS

SEE ALSO

NAME

SSL_CTX_set_client_cert_cb, SSL_CTX_get_client_cert_cb - handle client
certificate callback function

SYNOPSIS

 #include <openssl/ssl.h>

 void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, int (*client_cert_cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey));
 int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL *ssl, X509 **x509, EVP_PKEY **pkey);
 int (*client_cert_cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey);

DESCRIPTION

SSL_CTX_set_client_cert_cb() sets the client_cert_cb() callback, that is called when a client certificate is requested by a server
and no certificate was yet set for the SSL object.

When client_cert_cb() is NULL, no callback function is used.

SSL_CTX_get_client_cert_cb() returns a pointer to the
currently set callback function.

client_cert_cb() is the application defined callback. If it
wants to set a certificate, a certificate/private key combination must be
set using the x509 and pkey arguments and ``1'' must be returned. The certificate will be installed
into ssl, see the NOTES and BUGS sections. If no certificate should be set, ``0''
has to be returned and no certificate will be sent. A negative return value
will suspend the handshake and the handshake function will return
immediately. SSL_get_error(3)
will return SSL_ERROR_WANT_X509_LOOKUP to indicate, that the handshake was
suspended. The next call to the handshake function will again lead to the
call of client_cert_cb(). It is the job of the
client_cert_cb() to store information about the state of the
last call, if required to continue.

NOTES

During a handshake (or renegotiation) a server may request a certificate
from the client. A client certificate must only be sent, when the server
did send the request.

When a certificate was set using the
SSL_CTX_use_certificate(3) family of functions, it will be sent to the server. The TLS standard
requires that only a certificate is sent, if it matches the list of
acceptable CAs sent by the server. This constraint is violated by the
default behavior of the OpenSSL library. Using the callback function it is
possible to implement a proper selection routine or to allow a user
interaction to choose the certificate to be sent.

If a callback function is defined and no certificate was yet defined for
the SSL object, the callback function will be called. If the callback
function returns a certificate, the OpenSSL library will try to load the
private key and certificate data into the SSL object using the
SSL_use_certificate() and SSL_use_private_key()
functions. Thus it will permanently install the certificate and key for
this SSL object. It will not be reset by calling SSL_clear(3). If the callback returns no certificate, the OpenSSL library will not send
a certificate.

BUGS

The client_cert_cb() cannot return a complete certificate
chain, it can only return one client certificate. If the chain only has a
length of 2, the root CA certificate may be omitted according to the TLS
standard and thus a standard conforming answer can be sent to the server.
For a longer chain, the client must send the complete chain (with the
option to leave out the root CA certificate). This can only be accomplished
by either adding the intermediate CA certificates into the trusted
certificate store for the SSL_CTX object (resulting in having to add CA
certificates that otherwise maybe would not be trusted), or by adding the
chain certificates using the
SSL_CTX_add_extra_chain_cert(3)
function, which is only available for the SSL_CTX object as a whole and
that therefore probably can only apply for one client certificate, making
the concept of the callback function (to allow the choice from several
certificates) questionable.

Once the SSL object has been used in conjunction with the callback
function, the certificate will be set for the SSL object and will not be
cleared even when SSL_clear(3) is being called. It is therefore mandatory to destroy the SSL object using SSL_free(3)
and create a new one to return to the previous state.

SEE ALSO

ssl(3), SSL_CTX_use_certificate(3),
SSL_CTX_add_extra_chain_cert(3),
SSL_get_client_CA_list(3),
SSL_clear(3), SSL_free(3)


text:
package actions

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"fmt"
	"io"

	"github.com/go-openapi/runtime"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/c3sr/openwhisk-go/swagger_models"
)

// DeleteActionReader is a Reader for the DeleteAction structure.
type DeleteActionReader struct {
	formats strfmt.Registry
}

// ReadResponse reads a server response into the received o.
func (o *DeleteActionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 200:
		result := NewDeleteActionOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	case 401:
		result := NewDeleteActionUnauthorized()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 404:
		result := NewDeleteActionNotFound()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 500:
		result := NewDeleteActionInternalServerError()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	default:
		return nil, runtime.NewAPIError("unknown error", response, response.Code())
	}
}

// NewDeleteActionOK creates a DeleteActionOK with default headers values
func NewDeleteActionOK() *DeleteActionOK {
	return &DeleteActionOK{}
}

/*DeleteActionOK handles this case with default header values.

Deleted Item
*/
type DeleteActionOK struct {
}

func (o *DeleteActionOK) Error() string {
	return fmt.Sprintf("[DELETE /namespaces/{namespace}/actions/{actionName}][%d] deleteActionOK ", 200)
}

func (o *DeleteActionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	return nil
}

// NewDeleteActionUnauthorized creates a DeleteActionUnauthorized with default headers values
func NewDeleteActionUnauthorized() *DeleteActionUnauthorized {
	return &DeleteActionUnauthorized{}
}

/*DeleteActionUnauthorized handles this case with default header values.

Unauthorized request
*/
type DeleteActionUnauthorized struct {
	Payload *swagger_models.ErrorMessage
}

func (o *DeleteActionUnauthorized) Error() string {
	return fmt.Sprintf("[DELETE /namespaces/{namespace}/actions/{actionName}][%d] deleteActionUnauthorized  %+v", 401, o.Payload)
}

func (o *DeleteActionUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(swagger_models.ErrorMessage)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewDeleteActionNotFound creates a DeleteActionNotFound with default headers values
func NewDeleteActionNotFound() *DeleteActionNotFound {
	return &DeleteActionNotFound{}
}

/*DeleteActionNotFound handles this case with default header values.

Item not found
*/
type DeleteActionNotFound struct {
	Payload *swagger_models.ErrorMessage
}

func (o *DeleteActionNotFound) Error() string {
	return fmt.Sprintf("[DELETE /namespaces/{namespace}/actions/{actionName}][%d] deleteActionNotFound  %+v", 404, o.Payload)
}

func (o *DeleteActionNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(swagger_models.ErrorMessage)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewDeleteActionInternalServerError creates a DeleteActionInternalServerError with default headers values
func NewDeleteActionInternalServerError() *DeleteActionInternalServerError {
	return &DeleteActionInternalServerError{}
}

/*DeleteActionInternalServerError handles this case with default header values.

Server error
*/
type DeleteActionInternalServerError struct {
	Payload *swagger_models.ErrorMessage
}

func (o *DeleteActionInternalServerError) Error() string {
	return fmt.Sprintf("[DELETE /namespaces/{namespace}/actions/{actionName}][%d] deleteActionInternalServerError  %+v", 500, o.Payload)
}

func (o *DeleteActionInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(swagger_models.ErrorMessage)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}


text:
<?php

/**
 * Service definition for SiteVerification (v1).
 *
 *

 * Verifies ownership of websites or domains with Google.

 *
 *

 * For more information about this service, see the API
 * Documentation
 *

 *
 * @author Google, Inc.
 */
class Google_Service_SiteVerification extends Google_Service
{
  /** Manage the list of sites and domains you control. */
  const SITEVERIFICATION =
      "https://www.googleapis.com/auth/siteverification";
  /** Manage your new site verifications with Google. */
  const SITEVERIFICATION_VERIFY_ONLY =
      "https://www.googleapis.com/auth/siteverification.verify_only";

  public $webResource;

  /**
   * Constructs the internal representation of the SiteVerification service.
   *
   * @param Google_Client $client The client used to deliver requests.
   * @param string $rootUrl The root URL used for requests to the service.
   */
  public function __construct(Google_Client $client, $rootUrl = null)
  {
    parent::__construct($client);
    $this->rootUrl = $rootUrl ?: 'https://www.googleapis.com/';
    $this->servicePath = 'siteVerification/v1/';
    $this->batchPath = 'batch/siteVerification/v1';
    $this->version = 'v1';
    $this->serviceName = 'siteVerification';

    $this->webResource = new Google_Service_SiteVerification_Resource_WebResource(
        $this,
        $this->serviceName,
        'webResource',
        array(
          'methods' => array(
            'delete' => array(
              'path' => 'webResource/{id}',
              'httpMethod' => 'DELETE',
              'parameters' => array(
                'id' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),'get' => array(
              'path' => 'webResource/{id}',
              'httpMethod' => 'GET',
              'parameters' => array(
                'id' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),'getToken' => array(
              'path' => 'token',
              'httpMethod' => 'POST',
              'parameters' => array(),
            ),'insert' => array(
              'path' => 'webResource',
              'httpMethod' => 'POST',
              'parameters' => array(
                'verificationMethod' => array(
                  'location' => 'query',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),'list' => array(
              'path' => 'webResource',
              'httpMethod' => 'GET',
              'parameters' => array(),
            ),'patch' => array(
              'path' => 'webResource/{id}',
              'httpMethod' => 'PATCH',
              'parameters' => array(
                'id' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),'update' => array(
              'path' => 'webResource/{id}',
              'httpMethod' => 'PUT',
              'parameters' => array(
                'id' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),
          )
        )
    );
  }
}


text:
$(document).ready(function(){
	 var flag, i ,j;
	 var object_counter = 1;
	 var imgNameRand = [];
	 var optPosition = [];
	 var optOtherPos = [];
	 var imageObject = [];
	 var correctPosition;
	 var selectedOption;
	 var score = 0;
	 var wrong_selected = 0;  //wrong option selected so don't score up
	 var pos;
	 var t;
	 var current_image;

	 load_images();  //load the image numbers for random display
	 display_score();
	 game();     //let the game begin

	 function display_score(){
		 document.scoreDisplay.score.value = score;
		 if(object_counter > 6)
			 document.scoreDisplay.total.value = 6;
		 else
			 document.scoreDisplay.total.value = object_counter;
	 }

	 function checkDisplay(){   //Displays the correct and incorrect info
		 if(wrong_selected == 1){
			 $('.checkedOption').show();
			  document.getElementById("check").src = "assets/images/incorrect.png";
		       $('.checkedOption').fadeOut(1000);
		 }
		 else{
			 $('.checkedOption').hide();
			  document.getElementById("check").src = "assets/images/correct.png";
			  $('.checkedOption').fadeOut(2000);
			 //needs timer for holding on for abt a sec
		 }
	 }

	 $("#anchorPlayAgain").click(function(){
		 $('#gameOver').hide();
		 $('.optImg').show();
		 $('.imageBox').show();
		 load_images();
		 score = 0;
		 object_counter = 1;
		 wrong_selected = 0;
		 display_score();

		 game();

	 });
	 $("#anchorOpt0").click(function(){
		 selected_Option_Process('0');
	 });
	 $("#anchorOpt1").click(function(){
		 selected_Option_Process('1');
	 });
	 $("#anchorOpt2").click(function(){
		 selected_Option_Process('2');
	 });
	 $("#anchorOpt3").click(function(){
		 selected_Option_Process('3');
	 });

	 function generate_random_no(no_limit)	{                //generate random number
		var rand_no = Math.ceil(no_limit*Math.random());
		return rand_no;
	}

	function get_random_position(){           //generate random number between 0-3
		var rand_pos = Math.floor(Math.random()*4);
		return rand_pos;
	}

	function load_images(){

		imageObject[0] = generate_random_no("6");
			for(i=1; i<6; i++){
				do{
					flag = 0;
					imageObject[i] = generate_random_no("6");
					for(j=0; j<i; j++){
						if(imageObject[i]===imageObject[j]){
							flag++;
						}
					}
				}while(flag != 0 );  //end of do while loop
			}

	}
		function selected_Option_Process(selectedOption){

				if(selectedOption == correctPosition){
					object_counter++;
					if(wrong_selected == 0){
				   	  score++;
					}
					wrong_selected = 0;
				   display_score();
				   checkDisplay();
				   //t=setTimeout('game()',1000);
				   game();
				}
				else {
				 wrong_selected = 1;
			 	 checkDisplay();
				}

			}
	function game(){

		//clearTimeout(t);
		wrong_selected = 0;
		current_image = object_counter-1;
		document.getElementById("imgObject").src = "assets/images/"+imageObject[current_image]+".png";

		//find correct answer and apply it to the position
		currentImage = imageObject[current_image];
		imgNameRand[0] = currentImage;
		//generate choices

		for(i=1; i<4; i++){
			do{
				flag = 0;
				imgNameRand[i] = generate_random_no("6");
				for(j=0; j<i; j++){
					if(imgNameRand[i]===imgNameRand[j]){
						flag++;
					}
				}
			}while(flag != 0 );  //end of do while loop
		}

		correctPosition = get_random_position();

		optOtherPos[0] = correctPosition;

		for(i=1; i<4; i++){
			do{
				flag = 0;
				optOtherPos[i] = get_random_position();
					for(j=0; j<i; j++){   //chek repeat within optOtherPos array
						if(optOtherPos[i] === optOtherPos[j]){
							flag++;
						}
					}

			}while(flag != 0);

		}

		for(i=0; i<4; i++){
			pos = optOtherPos[i];
			optPosition[pos] = imgNameRand[i];
		}

		//random positions are stored in optOtherPos array. Great

		   for(i=0; i<4; i++){
			   document.getElementById("option"+i+"").src = "assets/images/image_name/"+optPosition[i]+".png";
			}

		//check for the correctness
		if(object_counter > 6){

			$('.optImg').hide();
			$('.imageBox').hide();
			$('#gameOver').show();

		}

		 //else
		    //no change
	} //end of game
});  //end of DOM