text:
CREATE TABLE v3_0_election_administrations (id INTEGER PRIMARY KEY,
                                            name TEXT,
                                            eo_id INT,
                                            ovc_id INT,
                                            physical_address_location_name TEXT,
                                            physical_address_line1 TEXT,
                                            physical_address_line2 TEXT,
                                            physical_address_line3 TEXT,
                                            physical_address_city TEXT,
                                            physical_address_state TEXT,
                                            physical_address_zip TEXT,
                                            mailing_address_location_name TEXT,
                                            mailing_address_line1 TEXT,
                                            mailing_address_line2 TEXT,
                                            mailing_address_line3 TEXT,
                                            mailing_address_city TEXT,
                                            mailing_address_state TEXT,
                                            mailing_address_zip TEXT,
                                            elections_url TEXT,
                                            registration_url TEXT,
                                            am_i_registered_url TEXT,
                                            absentee_url TEXT,
                                            where_do_i_vote_url TEXT,
                                            what_is_on_my_ballot_url TEXT,
                                            rules_url TEXT,
                                            voter_services TEXT,
                                            hours TEXT);


text:
package net.odmrp.informationBases;

import java.net.InetAddress;

public class PendingTuple {

	public MulticastSession multicastSession;
	public int sequenceNumber;
	public InetAddress nextHopAddress;
	public int transmissionCounter; // P_nth_time
	public long expirationTime;
	public boolean acknowledged;

	public PendingTuple(MulticastSession multicastSession,
			int sequenceNumber,
			InetAddress nextHopAddress,
			int retransmissionCounter,
			long expirationTime,
			boolean acknowledged) {
		super();
		this.multicastSession = multicastSession;
		this.sequenceNumber = sequenceNumber;
		this.nextHopAddress = nextHopAddress;
		this.transmissionCounter = retransmissionCounter;
		this.expirationTime = expirationTime;
		this.acknowledged = acknowledged;
	}

	public PendingTuple(MulticastSession multicastSession, int sequenceNumber,
			InetAddress nextHopAddress, int retransmissionCounter,
			long expirationTime) {
		super();
		this.multicastSession = multicastSession;
		this.sequenceNumber = sequenceNumber;
		this.nextHopAddress = nextHopAddress;
		this.transmissionCounter = retransmissionCounter;
		this.expirationTime = expirationTime;
		this.acknowledged = false;
	}

	public boolean isExpired() {
		return this.expirationTime < System.currentTimeMillis();
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace AntiMattr\GoogleBundle\Analytics;

/**
 * @link http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html
 */
class Event
{
    private $action;
    private $category;
    private $label;
    private $value;

    public function __contruct($category, $action, $label = null, $value = null)
    {
    	$this->action   = $action;
    	$this->category = $category;
    	$this->label    = $label;
    	$this->value    = $value;
    }

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

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

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

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


text:
require "spec_helper"

describe SessionsController do
  describe "routing" do

    it "routes to #index" do
      get("/sessions").should route_to("sessions#index")
    end

    it "routes to #new" do
      get("/sessions/new").should route_to("sessions#new")
    end

    it "routes to #show" do
      get("/sessions/1").should route_to("sessions#show", :id => "1")
    end

    it "routes to #edit" do
      get("/sessions/1/edit").should route_to("sessions#edit", :id => "1")
    end

    it "routes to #create" do
      post("/sessions").should route_to("sessions#create")
    end

    it "routes to #update" do
      put("/sessions/1").should route_to("sessions#update", :id => "1")
    end

    it "routes to #destroy" do
      delete("/sessions/1").should route_to("sessions#destroy", :id => "1")
    end

  end
end


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>pause</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

Module pause

Classes

    PauseLayer
    PauseScene

Functions

    __pause_scene_generator__
    default_pause_scene
    get_pause_scene
    set_pause_scene_generator

Variables

    __package__


text:
/*
	Package next calculates asynchronously combinations and permutations of a collection of values.

	Here is a sample usage of next:

		package main

		import (
			"fmt"
			"klaidliadon.dev/next"
		)

		func main() {
			for v := range next.Combination([]interface{1,2,3,4}, 2, true) {
				fmt.Println(v)
			}
		}
*/
package next


text:
import os
import unittest

from bpython import config

TEST_THEME_PATH = os.path.join(os.path.dirname(__file__), "test.theme")

class TestConfig(unittest.TestCase):
    def test_load_theme(self):
        struct = config.Struct()
        struct.color_scheme = dict()
        config.load_theme(struct, TEST_THEME_PATH, struct.color_scheme, dict())
        expected = {"keyword": "y"}
        self.assertEquals(struct.color_scheme, expected)

        defaults = {"name": "c"}
        expected.update(defaults)
        config.load_theme(struct, TEST_THEME_PATH, struct.color_scheme, defaults)
        self.assertEquals(struct.color_scheme, expected)

    def test_load_gtk_scheme(self):
        struct = config.Struct()
        struct.color_gtk_scheme = dict()
        config.load_theme(struct, TEST_THEME_PATH, struct.color_gtk_scheme, dict())
        expected = {"keyword": "y"}
        self.assertEquals(struct.color_gtk_scheme, expected)

        defaults = {"name": "c"}
        expected.update(defaults)
        config.load_theme(struct, TEST_THEME_PATH, struct.color_gtk_scheme, defaults)
        self.assertEquals(struct.color_gtk_scheme, expected)

if __name__ == '__main__':
    unittest.main()


text:
path: "/docs/flex"
title: "Flex Basis, Grow, and Shrink"
hasPlayground: true
---

## Flex Basis, Grow, and Shrink

**FLEX BASIS** is an axis-independent way of providing the default size of an item
along the main axis. Setting the flex basis of a child is similar to setting the `width` of that
child if its parent is a container with `flex direction: row` or setting the `height` of a child
if its parent is a container with `flex direction: column`. The flex basis of an item is the
default size of that item, the size of the item before any flex grow and flex shrink
calculations are performed.

<controls prop="flexBasis"></controls>

**FLEX GROW** describes how any space within a container should be distributed
among its children along the main axis. After laying out its children, a container will
distribute any remaining space according to the flex grow values specified by its children.

Flex grow accepts any floating point value >= 0, with 0 being the default value.
A container will distribute any remaining space among its children weighted by the child's flex grow value.

<controls prop="flexGrow"></controls>

**FLEX SHRINK** describes how to shrink children along the main axis in the
case that the total size of the children overflow the size of the container on the main axis.
flex shrink is very similar to flex grow and can be thought of in the same way if
any overflowing size is considered to be negative remaining space.
These two properties also work well together by allowing children to grow and shrink as needed.

Flex shrink accepts any floating point value >= 0, with 1 being the default value.
A container will shrink its children weighted by the child's flex shrink value.

<controls prop="flexShrink"></controls>


text:
from toee import *
import char_editor

def CheckPrereq(attachee, classLevelled, abilityScoreRaised):

	#BAB +2 checked by engine

	#Stunning Fist Check
	if not char_editor.has_feat(feat_stunning_fist):
		return 0

	return 1


text:
module ThoughtBot # :nodoc:
  module Shoulda # :nodoc:
    module ActiveRecord # :nodoc:
      DEFAULT_ERROR_MESSAGES =
        if Object.const_defined?(:I18n)
          I18n.translate('activerecord.errors.messages')
        else
          ::ActiveRecord::Errors.default_error_messages
        end

      # = Macro test helpers for your active record models
      #
      # These helpers will test most of the validations and associations for your ActiveRecord models.
      #
      #   class UserTest < Test::Unit::TestCase
      #     should_require_attributes :name, :phone_number
      #     should_not_allow_values_for :phone_number, "abcd", "1234"
      #     should_allow_values_for :phone_number, "(123) 456-7890"
      #
      #     should_protect_attributes :password
      #
      #     should_have_one :profile
      #     should_have_many :dogs
      #     should_have_many :messes, :through => :dogs
      #     should_belong_to :lover
      #   end
      #
      # For all of these helpers, the last parameter may be a hash of options.
      #
      module Macros
        # <b>DEPRECATED:</b> Use <tt>fixtures :all</tt> instead
        #
        # Loads all fixture files (<tt>test/fixtures/*.yml</tt>)
        def load_all_fixtures
          warn "[DEPRECATION] load_all_fixtures is deprecated.  Use `fixtures :all` instead."
          fixtures :all
        end

        # Ensures that the model cannot be saved if one of the attributes listed is not present.
        #
        # If an instance variable has been created in the setup named after the
        # model being tested, then this method will use that.  Otherwise, it will
        # create a new instance to test against.
        #
        # Options:
        # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
        #   Regexp or string.  Default = <tt>I18n.translate('activerecord.errors.messages')[:blank]</tt>
        #
        # Example:
        #   should_require_attributes :name, :phone_number
        #
        def should_require_attributes(*attributes)
          message = get_options!(attributes, :message)
          message ||= DEFAULT_ERROR_MESSAGES[:blank]
          klass = model_class

          attributes.each do |attribute|
            should "require #{attribute} to be set" do
              assert_bad_value(klass, attribute, nil, message)
            end
          end
        end

        # Ensures that the model cannot be saved if one of the attributes listed is not unique.
        # Requires an existing record
        #
        # Options:
        # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
        #   Regexp or string.  Default = <tt>I18n.translate('activerecord.errors.messages')[:taken]</tt>
        # * <tt>:scoped_to</tt> - field(s) to scope the uniqueness to.
        #
        # Examples:
        #   should_require_unique_attributes :keyword, :username
        #   should_require_unique_attributes :name, :message => "O NOES! SOMEONE STOELED YER NAME!"
        #   should_require_unique_attributes :email, :scoped_to => :name
        #   should_require_unique_attributes :address, :scoped_to => [:first_name, :last_name]
        #
        def should_require_unique_attributes(*attributes)
          message, scope = get_options!(attributes, :message, :scoped_to)
          scope = [*scope].compact
          message ||= DEFAULT_ERROR_MESSAGES[:taken]

          klass = model_class
          attributes.each do |attribute|
            attribute = attribute.to_sym
            should "require unique value for #{attribute}#{" scoped to #{scope.join(', ')}" unless scope.blank?}" do
              assert existing = klass.find(:first), "Can't find first #{klass}"
              object = klass.new
              existing_value = existing.send(attribute)

              if !scope.blank?
                scope.each do |s|
                  assert_respond_to object, :"#{s}=", "#{klass.name} doesn't seem to have a #{s} attribute."
                  object.send("#{s}=", existing.send(s))
                end
              end
              assert_bad_value(object, attribute, existing_value, message)

              # Now test that the object is valid when changing the scoped attribute
              # TODO:  There is a chance that we could change the scoped field
              # to a value that's already taken.  An alternative implementation
              # could actually find all values for scope and create a unique
              # one.
              if !scope.blank?
                scope.each do |s|
                  # Assume the scope is a foreign key if the field is nil
                  object.send("#{s}=", existing.send(s).nil? ? 1 : existing.send(s).next)
                  assert_good_value(object, attribute, existing_value, message)
                end
              end
            end
          end
        end

        # Ensures that the attribute cannot be set on mass update.
        #
        #   should_protect_attributes :password, :admin_flag
        #
        def should_protect_attributes(*attributes)
          get_options!(attributes)
          klass = model_class

          attributes.each do |attribute|
            attribute = attribute.to_sym
            should "protect #{attribute} from mass updates" do
              protected = klass.protected_attributes || []
              accessible = klass.accessible_attributes || []

              assert protected.include?(attribute.to_s) ||
                (!accessible.empty? && !accessible.include?(attribute.to_s)),
                     (accessible.empty? ?
                       "#{klass} is protecting #{protected.to_a.to_sentence}, but not #{attribute}." :
                       "#{klass} has made #{attribute} accessible")
            end
          end
        end

        # Ensures that the attribute cannot be changed once the record has been created.
        #
        #   should_have_readonly_attributes :password, :admin_flag
        #
        def should_have_readonly_attributes(*attributes)
          get_options!(attributes)
          klass = model_class

          attributes.each do |attribute|
            attribute = attribute.to_sym
            should "make #{attribute} read-only" do
              readonly = klass.readonly_attributes || []

              assert readonly.include?(attribute.to_s),
                     (readonly.empty? ?
                       "#{klass} attribute #{attribute} is not read-only" :
                       "#{klass} is making #{readonly.to_a.to_sentence} read-only, but not #{attribute}.")
            end
          end
        end

        # Ensures that the attribute cannot be set to the given values
        #
        # If an instance variable has been created in the setup named after the
        # model being tested, then this method will use that.  Otherwise, it will
        # create a new instance to test against.
        #
        # Options:
        # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
        #   Regexp or string.  Default = <tt>I18n.translate('activerecord.errors.messages')[:invalid]</tt>
        #
        # Example:
        #   should_not_allow_values_for :isbn, "bad 1", "bad 2"
        #
        def should_not_allow_values_for(attribute, *bad_values)
          message = get_options!(bad_values, :message)
          message ||= DEFAULT_ERROR_MESSAGES[:invalid]
          klass = model_class
          bad_values.each do |v|
            should "not allow #{attribute} to be set to #{v.inspect}" do
              assert_bad_value(klass, attribute, v, message)
            end
          end
        end

        # Ensures that the attribute can be set to the given values.
        #
        # If an instance variable has been created in the setup named after the
        # model being tested, then this method will use that.  Otherwise, it will
        # create a new instance to test against.
        #
        # Example:
        #   should_allow_values_for :isbn, "isbn 1 2345 6789 0", "ISBN 1-2345-6789-0"
        #
        def should_allow_values_for(attribute, *good_values)
          get_options!(good_values)
          klass = model_class
          good_values.each do |v|
            should "allow #{attribute} to be set to #{v.inspect}" do
              assert_good_value(klass, attribute, v)
            end
          end
        end

        # Ensures that the length of the attribute is in the given range
        #
        # If an instance variable has been created in the setup named after the
        # model being tested, then this method will use that.  Otherwise, it will
        # create a new instance to test against.
        #
        # Options:
        # * <tt>:short_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
        #   Regexp or string.  Default = <tt>I18n.translate('activerecord.errors.messages')[:too_short] % range.first</tt>
        # * <tt>:long_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
        #   Regexp or string.  Default = <tt>I18n.translate('activerecord.errors.messages')[:too_long] % range.last</tt>
        #
        # Example:
        #   should_ensure_length_in_range :password, (6..20)
        #
        def should_ensure_length_in_range(attribute, range, opts = {})
          short_message, long_message = get_options!([opts], :short_message, :long_message)
          short_message ||= DEFAULT_ERROR_MESSAGES[:too_short] % range.first
          long_message  ||= DEFAULT_ERROR_MESSAGES[:too_long] % range.last

          klass = model_class
          min_length = range.first
          max_length = range.last
          same_length = (min_length == max_length)

          if min_length > 0
            should "not allow #{attribute} to be less than #{min_length} chars long" do
              min_value = "x" * (min_length - 1)
              assert_bad_value(klass, attribute, min_value, short_message)
            end
          end

          if min_length > 0
            should "allow #{attribute} to be exactly #{min_length} chars long" do
              min_value = "x" * min_length
              assert_good_value(klass, attribute, min_value, short_message)
            end
          end

          should "not allow #{attribute} to be more than #{max_length} chars long" do
            max_value = "x" * (max_length + 1)
            assert_bad_value(klass, attribute, max_value, long_message)
          end

          unless same_length
            should "allow #{attribute} to be exactly #{max_length} chars long" do
              max_value = "x" * max_length
              assert_good_value(klass, attribute, max_value, long_message)
            end
          end
        end

        # Ensures that the length of the attribute is at least a certain length
        #
        # If an instance variable has been created in the setup named after the
        # model being tested, then this method will use that.  Otherwise, it will
        # create a new instance to test against.
        #
        # Options:
        # * <tt>:short_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
        #   Regexp or string.  Default = <tt>I18n.translate('activerecord.errors.messages')[:too_short] % min_length</tt>
        #
        # Example:
        #   should_ensure_length_at_least :name, 3
        #
        def should_ensure_length_at_least(attribute, min_length, opts = {})
          short_message = get_options!([opts], :short_message)
          short_message ||= DEFAULT_ERROR_MESSAGES[:too_short] % min_length

          klass = model_class

          if min_length > 0
            min_value = "x" * (min_length - 1)
            should "not allow #{attribute} to be less than #{min_length} chars long" do
              assert_bad_value(klass, attribute, min_value, short_message)
            end
          end
          should "allow #{attribute} to be at least #{min_length} chars long" do
            valid_value = "x" * (min_length)
            assert_good_value(klass, attribute, valid_value, short_message)
          end
        end

        # Ensures that the length of the attribute is exactly a certain length
        #
        # If an instance variable has been created in the setup named after the
        # model being tested, then this method will use that.  Otherwise, it will
        # create a new instance to test against.
        #
        # Options:
        # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
        #   Regexp or string.  Default = <tt>I18n.translate('activerecord.errors.messages')[:wrong_length] % length</tt>
        #
        # Example:
        #   should_ensure_length_is :ssn, 9
        #
        def should_ensure_length_is(attribute, length, opts = {})
          message = get_options!([opts], :message)
          message ||= DEFAULT_ERROR_MESSAGES[:wrong_length] % length

          klass = model_class

          should "not allow #{attribute} to be less than #{length} chars long" do
            min_value = "x" * (length - 1)
            assert_bad_value(klass, attribute, min_value, message)
          end

          should "not allow #{attribute} to be greater than #{length} chars long" do
            max_value = "x" * (length + 1)
            assert_bad_value(klass, attribute, max_value, message)
          end

          should "allow #{attribute} to be #{length} chars long" do
            valid_value = "x" * (length)
            assert_good_value(klass, attribute, valid_value, message)
          end
        end

        # Ensure that the attribute is in the range specified
        #
        # If an instance variable has been created in the setup named after the
        # model being tested, then this method will use that.  Otherwise, it will
        # create a new instance to test against.
        #
        # Options:
        # * <tt>:low_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
        #   Regexp or string.  Default = <tt>I18n.translate('activerecord.errors.messages')[:inclusion]</tt>
        # * <tt>:high_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
        #   Regexp or string.  Default = <tt>I18n.translate('activerecord.errors.messages')[:inclusion]</tt>
        #
        # Example:
        #   should_ensure_value_in_range :age, (0..100)
        #
        def should_ensure_value_in_range(attribute, range, opts = {})
          low_message, high_message = get_options!([opts], :low_message, :high_message)
          low_message  ||= DEFAULT_ERROR_MESSAGES[:inclusion]
          high_message ||= DEFAULT_ERROR_MESSAGES[:inclusion]

          klass = model_class
          min   = range.first
          max   = range.last

          should "not allow #{attribute} to be less than #{min}" do
            v = min - 1
            assert_bad_value(klass, attribute, v, low_message)
          end

          should "allow #{attribute} to be #{min}" do
            v = min
            assert_good_value(klass, attribute, v, low_message)
          end

          should "not allow #{attribute} to be more than #{max}" do
            v = max + 1
            assert_bad_value(klass, attribute, v, high_message)
          end

          should "allow #{attribute} to be #{max}" do
            v = max
            assert_good_value(klass, attribute, v, high_message)
          end
        end

        # Ensure that the attribute is numeric
        #
        # If an instance variable has been created in the setup named after the
        # model being tested, then this method will use that.  Otherwise, it will
        # create a new instance to test against.
        #
        # Options:
        # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
        #   Regexp or string.  Default = <tt>I18n.translate('activerecord.errors.messages')[:not_a_number]</tt>
        #
        # Example:
        #   should_only_allow_numeric_values_for :age
        #
        def should_only_allow_numeric_values_for(*attributes)
          message = get_options!(attributes, :message)
          message ||= DEFAULT_ERROR_MESSAGES[:not_a_number]
          klass = model_class
          attributes.each do |attribute|
            attribute = attribute.to_sym
            should "only allow numeric values for #{attribute}" do
              assert_bad_value(klass, attribute, "abcd", message)
            end
          end
        end

        # Ensures that the has_many relationship exists.  Will also test that the
        # associated table has the required columns.  Works with polymorphic
        # associations.
        #
        # Options:
        # * <tt>:through</tt> - association name for <tt>has_many :through</tt>
        # * <tt>:dependent</tt> - tests that the association makes use of the dependent option.
        #
        # Example:
        #   should_have_many :friends
        #   should_have_many :enemies, :through => :friends
        #   should_have_many :enemies, :dependent => :destroy
        #
        def should_have_many(*associations)
          through, dependent = get_options!(associations, :through, :dependent)
          klass = model_class
          associations.each do |association|
            name = "have many #{association}"
            name += " through #{through}" if through
            name += " dependent => #{dependent}" if dependent
            should name do
              reflection = klass.reflect_on_association(association)
              assert reflection, "#{klass.name} does not have any relationship to #{association}"
              assert_equal :has_many, reflection.macro

              if through
                through_reflection = klass.reflect_on_association(through)
                assert through_reflection, "#{klass.name} does not have any relationship to #{through}"
                assert_equal(through, reflection.options[:through])
              end

              if dependent
                assert_equal dependent.to_s,
                             reflection.options[:dependent].to_s,
                             "#{association} should have #{dependent} dependency"
              end

              # Check for the existence of the foreign key on the other table
              unless reflection.options[:through]
                if reflection.options[:foreign_key]
                  fk = reflection.options[:foreign_key]
                elsif reflection.options[:as]
                  fk = reflection.options[:as].to_s.foreign_key
                else
                  fk = reflection.primary_key_name
                end

                associated_klass_name = (reflection.options[:class_name] || association.to_s.classify)
                associated_klass = associated_klass_name.constantize

                assert associated_klass.column_names.include?(fk.to_s),
                       "#{associated_klass.name} does not have a #{fk} foreign key."
              end
            end
          end
        end

        # Ensure that the has_one relationship exists.  Will also test that the
        # associated table has the required columns.  Works with polymorphic
        # associations.
        #
        # Options:
        # * <tt>:dependent</tt> - tests that the association makes use of the dependent option.
        #
        # Example:
        #   should_have_one :god # unless hindu
        #
        def should_have_one(*associations)
          dependent = get_options!(associations, :dependent)
          klass = model_class
          associations.each do |association|
            name = "have one #{association}"
            name += " dependent => #{dependent}" if dependent
            should name do
              reflection = klass.reflect_on_association(association)
              assert reflection, "#{klass.name} does not have any relationship to #{association}"
              assert_equal :has_one, reflection.macro

              associated_klass = (reflection.options[:class_name] || association.to_s.camelize).constantize

              if reflection.options[:foreign_key]
                fk = reflection.options[:foreign_key]
              elsif reflection.options[:as]
                fk = reflection.options[:as].to_s.foreign_key
                fk_type = fk.gsub(/_id$/, '_type')
                assert associated_klass.column_names.include?(fk_type),
                       "#{associated_klass.name} does not have a #{fk_type} column."
              else
                fk = klass.name.foreign_key
              end
              assert associated_klass.column_names.include?(fk.to_s),
                     "#{associated_klass.name} does not have a #{fk} foreign key."

              if dependent
                assert_equal dependent.to_s,
                             reflection.options[:dependent].to_s,
                             "#{association} should have #{dependent} dependency"
              end
            end
          end
        end

        # Ensures that the has_and_belongs_to_many relationship exists, and that the join
        # table is in place.
        #
        #   should_have_and_belong_to_many :posts, :cars
        #
        def should_have_and_belong_to_many(*associations)
          get_options!(associations)
          klass = model_class

          associations.each do |association|
            should "should have and belong to many #{association}" do
              reflection = klass.reflect_on_association(association)
              assert reflection, "#{klass.name} does not have any relationship to #{association}"
              assert_equal :has_and_belongs_to_many, reflection.macro
              table = reflection.options[:join_table]
              assert ::ActiveRecord::Base.connection.tables.include?(table), "table #{table} doesn't exist"
            end
          end
        end

        # Ensure that the belongs_to relationship exists.
        #
        #   should_belong_to :parent
        #
        def should_belong_to(*associations)
          get_options!(associations)
          klass = model_class
          associations.each do |association|
            should "belong_to #{association}" do
              reflection = klass.reflect_on_association(association)
              assert reflection, "#{klass.name} does not have any relationship to #{association}"
              assert_equal :belongs_to, reflection.macro

              unless reflection.options[:polymorphic]
                associated_klass = (reflection.options[:class_name] || association.to_s.camelize).constantize
                fk = reflection.options[:foreign_key] || reflection.primary_key_name
                assert klass.column_names.include?(fk.to_s), "#{klass.name} does not have a #{fk} foreign key."
              end
            end
          end
        end

        # Ensure that the given class methods are defined on the model.
        #
        #   should_have_class_methods :find, :destroy
        #
        def should_have_class_methods(*methods)
          get_options!(methods)
          klass = model_class
          methods.each do |method|
            should "respond to class method ##{method}" do
              assert_respond_to klass, method, "#{klass.name} does not have class method #{method}"
            end
          end
        end

        # Ensure that the given instance methods are defined on the model.
        #
        #   should_have_instance_methods :email, :name, :name=
        #
        def should_have_instance_methods(*methods)
          get_options!(methods)
          klass = model_class
          methods.each do |method|
            should "respond to instance method ##{method}" do
              assert_respond_to klass.new, method, "#{klass.name} does not have instance method #{method}"
            end
          end
        end

        # Ensure that the given columns are defined on the models backing SQL table.
        #
        #   should_have_db_columns :id, :email, :name, :created_at
        #
        def should_have_db_columns(*columns)
          column_type = get_options!(columns, :type)
          klass = model_class
          columns.each do |name|
            test_name = "have column #{name}"
            test_name += " of type #{column_type}" if column_type
            should test_name do
              column = klass.columns.detect {|c| c.name == name.to_s }
              assert column, "#{klass.name} does not have column #{name}"
            end
          end
        end

        # Ensure that the given column is defined on the models backing SQL table.  The options are the same as
        # the instance variables defined on the column definition:  :precision, :limit, :default, :null,
        # :primary, :type, :scale, and :sql_type.
        #
        #   should_have_db_column :email, :type => "string", :default => nil,   :precision => nil, :limit    => 255,
        #                                 :null => true,     :primary => false, :scale     => nil, :sql_type => 'varchar(255)'
        #
        def should_have_db_column(name, opts = {})
          klass = model_class
          test_name = "have column named :#{name}"
          test_name += " with options " + opts.inspect unless opts.empty?
          should test_name do
            column = klass.columns.detect {|c| c.name == name.to_s }
            assert column, "#{klass.name} does not have column #{name}"
            opts.each do |k, v|
              assert_equal column.instance_variable_get("@#{k}").to_s, v.to_s, ":#{name} column on table for #{klass} does not match option :#{k}"
            end
          end
        end

        # Ensures that there are DB indices on the given columns or tuples of columns.
        # Also aliased to should_have_index for readability
        #
        #   should_have_indices :email, :name, [:commentable_type, :commentable_id]
        #   should_have_index :age
        #
        def should_have_indices(*columns)
          table = model_class.name.tableize
          indices = ::ActiveRecord::Base.connection.indexes(table).map(&:columns)

          columns.each do |column|
            should "have index on #{table} for #{column.inspect}" do
              columns = [column].flatten.map(&:to_s)
              assert_contains(indices, columns)
            end
          end
        end

        alias_method :should_have_index, :should_have_indices

        # Ensures that the model cannot be saved if one of the attributes listed is not accepted.
        #
        # If an instance variable has been created in the setup named after the
        # model being tested, then this method will use that.  Otherwise, it will
        # create a new instance to test against.
        #
        # Options:
        # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
        #   Regexp or string.  Default = <tt>I18n.translate('activerecord.errors.messages')[:accepted]</tt>
        #
        # Example:
        #   should_require_acceptance_of :eula
        #
        def should_require_acceptance_of(*attributes)
          message = get_options!(attributes, :message)
          message ||= DEFAULT_ERROR_MESSAGES[:accepted]
          klass = model_class

          attributes.each do |attribute|
            should "require #{attribute} to be accepted" do
              assert_bad_value(klass, attribute, false, message)
            end
          end
        end

        # Ensures that the model has a method named scope_name that returns a NamedScope object with the
        # proxy options set to the options you supply.  scope_name can be either a symbol, or a method
        # call which will be evaled against the model.  The eval'd method call has access to all the same
        # instance variables that a should statement would.
        #
        # Options: Any of the options that the named scope would pass on to find.
        #
        # Example:
        #
        #   should_have_named_scope :visible, :conditions => {:visible => true}
        #
        # Passes for
        #
        #   named_scope :visible, :conditions => {:visible => true}
        #
        # Or for
        #
        #   def self.visible
        #     scoped(:conditions => {:visible => true})
        #   end
        #
        # You can test lambdas or methods that return ActiveRecord#scoped calls:
        #
        #   should_have_named_scope 'recent(5)', :limit => 5
        #   should_have_named_scope 'recent(1)', :limit => 1
        #
        # Passes for
        #   named_scope :recent, lambda {|c| {:limit => c}}
        #
        # Or for
        #
        #   def self.recent(c)
        #     scoped(:limit => c)
        #   end
        #
        def should_have_named_scope(scope_call, *args)
          klass = model_class
          scope_opts = args.extract_options!
          scope_call = scope_call.to_s

          context scope_call do
            setup do
              @scope = eval("#{klass}.#{scope_call}")
            end

            should "return a scope object" do
              assert_equal ::ActiveRecord::NamedScope::Scope, @scope.class
            end

            unless scope_opts.empty?
              should "scope itself to #{scope_opts.inspect}" do
                assert_equal scope_opts, @scope.proxy_options
              end
            end
          end
        end

      end
    end
  end
end


text:
package com.ptoceti.osgi.modbus.impl.utils;

import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ModbusUtils {

	public static final int byteToHexWord(byte in ) {

		byte[] table = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
			0x41, 0x42, 0x43, 0x44, 0x45, 0x46 };
		int result = 0x0000;

		result = ( table[( in & 0xF0) >>> 4]) << 8;
		result = ( result & 0xFF00 ) | ( table[ in & 0x0F]);

		return result;
	}

	public static final byte hexWordToByte(int in ) {

		int highByte = ((in & 0xFF00) >>> 8 );
		int lowByte = (in & 0x00FF);

		if(( highByte >= 30 ) || ( highByte <= 39 )) highByte =- 0x30;
		else if(( highByte >= 0x41 ) || ( highByte <= 0x46 )) highByte =- ( 0x41 - 0x0A );
		else highByte = 0x00;

		if(( lowByte >= 30 ) || ( lowByte <= 39 )) lowByte =- 0x30;
		else if(( lowByte >= 0x41 ) || ( lowByte <= 0x46 )) lowByte =- ( 0x41 - 0x0A );
		else lowByte = 0x00;

		return (byte) (( highByte * 0x10 ) + lowByte );
	}

	public static final String writeHex(byte[] buff) throws IOException {

		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		writeHex( buff, 0, buff.length, bout );
		return bout.toString();
	}

	public static final void writeHex(byte[] buff, int off, int len,  OutputStream out) throws IOException {

		for(int i = off; i < ( off + len ); i++ ){
			writeHex( buff[i], out );
		}

	}

	public static final void writeHex(byte theByte, OutputStream out ) throws IOException {

		int theWord = byteToHexWord( theByte );
		out.write((theWord & 0xFF00) >>> 8 );
		out.write(theWord & 0x00FF);
	}

	public static final void readHex(byte[] buff, int off, int len, OutputStream out ) throws IOException {

		for(int i = off; i < (off + len); i = i + 2 ) {

			byte highByte = buff[i];
			byte lowByte = buff[i+1];
			int theWord = (((int) highByte ) << 8 ) | ((int) lowByte );

			readHex( theWord, out );
		}
	}

	public static final void readHex(int theWord, OutputStream out) throws IOException {

		byte thebyte = hexWordToByte( theWord );
		out.write( thebyte );
	}

	public static final byte calculateLRC(byte[] buff, int count) {

		byte lrc = 0x00;

		for( int i = 0; i < buff.length && i < count; i++ ) {
			lrc += buff[i];
		}

		return lrc;
	}

	public static final int calculateCRC( byte[] buff, int count) {

		int crc = 0xFFFF;
		boolean flag = false;

		for( int i = 0; i < buff.length && i < count ; i++) {
			// exclusive OR the first 8 bit byte of the message with the low order byte of the 16 bit crc register,
			// putting the result in the crc register.
			crc = ( crc & 0xFF00 ) | (( crc ^ buff[i] ) & 0x00FF );
			for (int shifts = 0; shifts < 8; shifts++) {
				// shift the crc register one bit to the right, zero-filling the msb. If the LSB was zero,
				// repeat another shift. If the LSB was 1, exclusive XOR the CRC with the value 0xA001;
				flag = (crc & 0x0001) == 0x0001;
				crc = crc >>> 1;
				if( flag ) crc = crc ^ 0xA001;
			// repeat till 8 shifts have been performed.
			};
		}
		// result is in crc. must swap low and high bytes.
		return (( 0x00FF & crc) << 8 ) | (( 0xFF00 & crc ) >>> 8 );
	}

}


text:
const path = require('path');
const webpack = require('webpack');

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const InlineManifestWebpackPlugin = require('inline-manifest-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');

const PATHS = {
  src: path.join(__dirname, '/docs/src'),
  dist: path.join(__dirname, '/docs/dist'),
  root: path.join(__dirname, '/docs'),
}

const getDevServer = (env) => {
  const devServer = {
    publicPath: '/',
    clientLogLevel: 'info',
    compress: true,
    contentBase: PATHS.dist,
    historyApiFallback: true,
    inline: true,
    hot: false,
  }

  return env.prod ? {} : devServer;
}

const getRules = (env) => {
  const commonRules = [
    {
      test: /\.tsx?$/,
      use: [
        {
          loader: 'awesome-typescript-loader',
          options: {
            configFileName: 'tsconfig.docs.json'
          }
        }
      ],
      exclude: /node_modules/
    },
    {
      test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
      use: [{
        loader: 'file-loader',
        options: {
          name: env.prod ? 'dist/[hash:8].[ext]' : '[name].[ext]?[hash:8]',
        },
      }],
    },
  ];

  const productionRules = [
    {
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              localIdentName: '[name]__[local]___[hash:base64:5]'
            }
          },
        ]
      })
    },
  ];

  const developmentRules = [
    {
      test: /\.css$/,
      use: [
        'style-loader',
        'css-loader?importLoaders=1&sourceMap&localIdentName=[name]__[local]___[hash:base64:5]',
      ],
    },
  ];

  const extraRules = env.prod ? productionRules : developmentRules;

  return commonRules.concat(extraRules);
};

const getPlugins = (env) => {
  const commonPlugins = [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module) {
        return module.context && module.context.indexOf('node_modules') !== -1;
      }
    }),
    new webpack.optimize.CommonsChunkPlugin('manifest'),
    new HtmlWebpackPlugin({
      template: `${PATHS.src}/index.html`,
      filename: 'index.html',
      inject: 'body',
      title: 'Bloomer | A set of React Stateless Components',
      chunksSortMode: 'dependency',
    }),
    new ScriptExtHtmlWebpackPlugin({
      defaultAttribute: 'defer',
    }),
  ];

  const productionPlugins = [
    new webpack.NamedModulesPlugin(),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      beautify: false,
      mangle: {
        screw_ie8: true,
        keep_fnames: true
      },
      compress: {
        warnings: false,
        screw_ie8: true,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true,
      },
      output: {
        comments: false,
      },
      comments: false
    }),
    new ExtractTextPlugin('dist/[name].[contenthash:8].css'),
    new CleanWebpackPlugin(['dist'], { root: PATHS.root }),
    new InlineManifestWebpackPlugin({ name: 'webpackManifest' }),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': '"production"',
      },
    }),
  ];

  const developmentPlugins = [
    new webpack.NamedModulesPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': '"development"',
      },
    }),
  ];

  const extraPlugins = env.prod ? productionPlugins : developmentPlugins;

  return commonPlugins.concat(extraPlugins);
}

const config = env => (
  {
    devtool: env.prod ? 'source-map' : 'inline-source-map',

    context: PATHS.src,

    entry: `${PATHS.src}/app.tsx`,

    output: {
      path: PATHS.root,
      filename: env.prod ? 'dist/[name].[hash:8].js' : 'dist/[name].js',
    },

    module: {
      rules: getRules(env)
    },

    resolve: {
      extensions: ['.ts', '.tsx', '.js']
    },

    plugins: getPlugins(env),

    devServer: getDevServer(env),

    externals: env.prod ? {
      "react": "React",
      "react-dom": "ReactDOM",
      "highlight.js": "hljs",
    } : {},
  }
);

module.exports = config;


text:
State Fair T-Shirt Bingo, updated for 2015!  Drawings by Andy Sturdevant; compiled by Tom Nehil.

You can see this project in action at *[Minnesota State Fair T-shirt bingo, 2015 edition](http://www.minnpost.com/stroll/2015/09/minnesota-state-fair-t-shirt-bingo-2015-edition)*.

The original version, from 2014, lives at *[Minnesota State Fair T-shirt bingo](http://www.minnpost.com/stroll/2014/08/minnesota-state-fair-t-shirt-bingo)*. And you can [check out the repo](https://github.com/MinnPost/minnpost-state-fair-bingo), which looks a lot like this one.

*Unless otherwise noted, MinnPost projects on [Github](https://github.com/minnpost) are story-driven and meant for transparency sake and not focused on re-use.  For a list of our more reusable projects, go to [code.minnpost.com](http://code.minnpost.com).*

## Development and running locally

### Prerequisites

All commands are assumed to be on the [command line](http://en.wikipedia.org/wiki/Command-line_interface), often called the Terminal, unless otherwise noted.  The following will install technologies needed for the other steps and will only needed to be run once on your computer so there is a good chance you already have these technologies on your computer.

1. Install [Git](http://git-scm.com/).
   * On a Mac, install [Homebrew](http://brew.sh/), then do: `brew install git`
1. Install [NodeJS](http://nodejs.org/).
   * On a Mac, do: `brew install node`
1. Optionally, for development, install [Grunt](http://gruntjs.com/): `npm install -g grunt-cli`
1. Install [Bower](http://bower.io/): `npm install -g bower`
1. Install [Sass](http://sass-lang.com/): `gem install sass`
   * On a Mac do: `sudo gem install sass`
1. Install [Compass](http://compass-style.org/): `gem install compass`
   * On a Mac do: `sudo gem install compass`

### Get code and install packages

Get the code for this project and install the necessary dependency libraries and packages.

1. Check out this code with [Git](http://git-scm.com/): `git clone https://github.com/MinnPost/minnpost-state-fair-bingo.git`
1. Go into the template directory: `cd minnpost-state-fair-bingo`
1. Install NodeJS packages: `npm install`
1. Install Bower components: `bower install`

### Running locally

1. Run: `grunt server`
    * This will run a local webserver for development and you can view the application in your web browser at [http://localhost:8802](http://localhost:8802).
1. By default, running a local server will show you the local development version.  But there are other builds that you can view by changing the query parameters.  Do note that you may have to run the build and deploy things for things to work normally.
    * Local build: http://localhost:8802/?mpDeployment=build
    * Build deployed on S3: http://localhost:8802/?mpDeployment=deploy
    * Embedded version with local build: http://localhost:8802/?mpDeployment=build&mpEmbed=true
    * Embedded version with S3 build: http://localhost:8802/?mpDeployment=deploy&mpEmbed=true

### Developing

Development will depend on what libraries are used.  But here are a few common parts.

* `js/app.js` is the main application and will contain the top logic.

Adding libraries is not difficult, but there are a few steps.

1. User bower to install the appropriate library: `bower install library --save`
1. Add the appropriate reference in `js/config.js` so that RequireJS knows about it.
1. Add an entry in the `dependencyMap` object in `bower.json`.  This is used to automatically collect resources in the build process.  It is possible, like with `minnpost-styles` that multiple entries will need to be made, one ber `.js` file.  Here is an example:

```
// Should be bower identifier.  Order matters for build, meaning that any dependencies should come first.
"library": {
  // Name used for reference in RequireJS (some modules expect dependencies with specific case, otherwise its arbitrary and you can just use the library name from above).
  // If this is not a JS library, do not include.
  "rname": "library",
  // (optional) Path to un-minified JS files within bower_components excluding .js suffix.
  "js": ["library/dist/library"],
  // (optional) Path to un-minified CSS files within bower_components excluding .css suffix.
  "css": ["library/dist/css/library"],
  // (optional) Path to un-minified IE-specific CSS files within bower_components excluding .css suffix.
  "ie": ["library/dist/css/library.ie"],
  // What is expected to be returned when using as a RequireJS dependency.  Some specific libraries, like jQuery use $, or backbone returns the Backbone class.
  // If this is not a JS library, do not include.
  "returns": "Library"
}
```

### Testing

Unfortunately there are no tests at the moment.

### Build

To build or compile all the assets together for easy and efficient deployment, do the following.  It will create all the files in the `dist/` folder.

1. Run: `grunt`

### Deploy

Deploying will push the relevant files up to Amazon's AWS S3 so that they can be easily referenced on the MinnPost site.  This is specific to MinnPost, and your deployment might be different.

1. Run: `grunt deploy`
    * This will output a bit of HTML to if you want to use the project as an embed.

There are to main ways to include the necessary HTML in a page in order to run the project.

1. Copy the relevant parts from `index.html`.
    * This has the benefit of showing messages to users that have older browsers or have Javascript turned off.  This also uses the build that separates out the third-party libraries that are used and are less likely to change; this gains a bit of performance for users.
1. Copy the embed output from `grunt deploy` (still in development).

## Hacks

*List any hacks used in this project, such as forked repos.  Link to pull request or repo and issue.*

## About Us

MinnData, the MinnPost data team, is Alan, Tom, and Kaeti and all the awesome contributors to open source projects we utilize.  See our work at [minnpost.com/data](http://minnpost.com/data).

```

                                                   .--.
                                                   `.  \
                                                     \  \
                                                      .  \
                                                      :   .
                                                      |    .
                                                      |    :
                                                      |    |
      ..._  ___                                       |    |
     `."".`''''""--..___                              |    |
     ,-\  \             ""-...__         _____________/    |
     / ` " '                    `""""""""                  .
     \                                                      L
     (>                                                      \
    /                                                         \
    \_    ___..---.                                            L
      `--'         '.                                           \
                     .                                           \_
                    _/`.                                           `.._
                 .'     -.                                             `.
                /     __.-Y     /''''''-...___,...--------.._            |
               /   _."    |    /                ' .      \   '---..._    |
              /   /      /    /                _,. '    ,/           |   |
              \_,'     _.'   /              /''     _,-'            _|   |
                      '     /               `-----''               /     |
                      `...-'                                       `...-'

```


text:
# Module `0x1::DiemSystem`

Maintains information about the set of validators used during consensus.
Provides functions to add, remove, and update validators in the
validator set.

> Note: When trying to understand this code, it's important to know that "config"
and "configuration" are used for several distinct concepts.

-  [Struct `ValidatorInfo`](#0x1_DiemSystem_ValidatorInfo)
-  [Resource `CapabilityHolder`](#0x1_DiemSystem_CapabilityHolder)
-  [Struct `DiemSystem`](#0x1_DiemSystem_DiemSystem)
-  [Constants](#@Constants_0)
-  [Function `initialize_validator_set`](#0x1_DiemSystem_initialize_validator_set)
-  [Function `set_diem_system_config`](#0x1_DiemSystem_set_diem_system_config)
-  [Function `add_validator`](#0x1_DiemSystem_add_validator)
-  [Function `remove_validator`](#0x1_DiemSystem_remove_validator)
-  [Function `update_config_and_reconfigure`](#0x1_DiemSystem_update_config_and_reconfigure)
-  [Function `get_diem_system_config`](#0x1_DiemSystem_get_diem_system_config)
-  [Function `is_validator`](#0x1_DiemSystem_is_validator)
-  [Function `get_validator_config`](#0x1_DiemSystem_get_validator_config)
-  [Function `validator_set_size`](#0x1_DiemSystem_validator_set_size)
-  [Function `get_ith_validator_address`](#0x1_DiemSystem_get_ith_validator_address)
-  [Function `get_validator_index_`](#0x1_DiemSystem_get_validator_index_)
-  [Function `update_ith_validator_info_`](#0x1_DiemSystem_update_ith_validator_info_)
-  [Function `is_validator_`](#0x1_DiemSystem_is_validator_)
-  [Module Specification](#@Module_Specification_1)
    -  [Initialization](#@Initialization_2)
    -  [Access Control](#@Access_Control_3)
    -  [Helper Functions](#@Helper_Functions_4)

use 0x1::CoreAddresses;
use 0x1::DiemConfig;
use 0x1::DiemTimestamp;
use 0x1::Errors;
use 0x1::Option;
use 0x1::Roles;
use 0x1::Signer;
use 0x1::ValidatorConfig;
use 0x1::Vector;

## Struct `ValidatorInfo`

Information about a Validator Owner.

struct ValidatorInfo

Fields

addr: address

 The address (account) of the Validator Owner

consensus_voting_power: u64

 The voting power of the Validator Owner (currently always 1).

config: ValidatorConfig::Config

 Configuration information about the Validator, such as the
 Validator Operator, human name, and info such as consensus key
 and network addresses.

last_config_update_time: u64

 The time of last reconfiguration invoked by this validator
 in microseconds

## Resource `CapabilityHolder`

Enables a scheme that restricts the DiemSystem config
in DiemConfig from being modified by any other module.  Only
code in this module can get a reference to the ModifyConfigCapability<DiemSystem>,
which is required by DiemConfig::set_with_capability_and_reconfigure to
modify the DiemSystem config. This is only needed by update_config_and_reconfigure.
Only Diem root can add or remove a validator from the validator set, so the
capability is not needed for access control in those functions.

resource struct CapabilityHolder

Fields

cap: DiemConfig::ModifyConfigCapability<DiemSystem::DiemSystem>

 Holds a capability returned by DiemConfig::publish_new_config_and_get_capability
 which is called in initialize_validator_set.

## Struct `DiemSystem`

The DiemSystem struct stores the validator set and crypto scheme in
DiemConfig. The DiemSystem struct is stored by DiemConfig, which publishes a
DiemConfig<DiemSystem> resource.

struct DiemSystem

Fields

scheme: u8

 The current consensus crypto scheme.

validators: vector<DiemSystem::ValidatorInfo>

 The current validator set.

Specification

Members of validators vector (the validator set) have unique addresses.

invariant
    forall i in 0..len(validators), j in 0..len(validators):
        validators[i].addr == validators[j].addr ==> i == j;

## Constants

The validator operator is not the operator for the specified validator

const EINVALID_TRANSACTION_SENDER: u64 = 4;

Tried to add a validator to the validator set that was already in it

const EALREADY_A_VALIDATOR: u64 = 2;

The CapabilityHolder resource was not in the required state

const ECAPABILITY_HOLDER: u64 = 0;

Rate limited when trying to update config

const ECONFIG_UPDATE_RATE_LIMITED: u64 = 6;

Tried to add a validator with an invalid state to the validator set

const EINVALID_PROSPECTIVE_VALIDATOR: u64 = 1;

Validator set already at maximum allowed size

const EMAX_VALIDATORS: u64 = 7;

An operation was attempted on an address not in the vaidator set

const ENOT_AN_ACTIVE_VALIDATOR: u64 = 3;

An out of bounds index for the validator set was encountered

const EVALIDATOR_INDEX: u64 = 5;

Number of microseconds in 5 minutes

const FIVE_MINUTES: u64 = 300000000;

The maximum number of allowed validators in the validator set

const MAX_VALIDATORS: u64 = 256;

## Function `initialize_validator_set`

Publishes the DiemConfig for the DiemSystem struct, which contains the current
validator set. Also publishes the CapabilityHolder with the
ModifyConfigCapability<DiemSystem> returned by the publish function, which allows
code in this module to change DiemSystem config (including the validator set).
Must be invoked by the Diem root a single time in Genesis.

public fun initialize_validator_set(dr_account: &signer)

Implementation

public fun initialize_validator_set(
    dr_account: &signer,
) {
    DiemTimestamp::assert_genesis();
    Roles::assert_diem_root(dr_account);

    let cap = DiemConfig::publish_new_config_and_get_capability<DiemSystem>(
        dr_account,
        DiemSystem {
            scheme: 0,
            validators: Vector::empty(),
        },
    );
    assert(
        !exists<CapabilityHolder>(CoreAddresses::DIEM_ROOT_ADDRESS()),
        Errors::already_published(ECAPABILITY_HOLDER)
    );
    move_to(dr_account, CapabilityHolder { cap })
}

Specification

modifies global<DiemConfig::DiemConfig<DiemSystem>>(CoreAddresses::DIEM_ROOT_ADDRESS());
include DiemTimestamp::AbortsIfNotGenesis;
include Roles::AbortsIfNotDiemRoot{account: dr_account};

let dr_addr = Signer::spec_address_of(dr_account);
aborts_if DiemConfig::spec_is_published<DiemSystem>() with Errors::ALREADY_PUBLISHED;
aborts_if exists<CapabilityHolder>(dr_addr) with Errors::ALREADY_PUBLISHED;
ensures exists<CapabilityHolder>(dr_addr);
ensures DiemConfig::spec_is_published<DiemSystem>();
ensures len(spec_get_validators()) == 0;

## Function `set_diem_system_config`

Copies a DiemSystem struct into the DiemConfig<DiemSystem> resource
Called by the add, remove, and update functions.

fun set_diem_system_config(value: DiemSystem::DiemSystem)

Implementation

fun set_diem_system_config(value: DiemSystem) acquires CapabilityHolder {
    DiemTimestamp::assert_operating();
    assert(
        exists<CapabilityHolder>(CoreAddresses::DIEM_ROOT_ADDRESS()),
        Errors::not_published(ECAPABILITY_HOLDER)
    );
    // Updates the DiemConfig<DiemSystem> and emits a reconfigure event.
    DiemConfig::set_with_capability_and_reconfigure<DiemSystem>(
        &borrow_global<CapabilityHolder>(CoreAddresses::DIEM_ROOT_ADDRESS()).cap,
        value
    )
}

Specification

pragma opaque;
modifies global<DiemConfig::DiemConfig<DiemSystem>>(CoreAddresses::DIEM_ROOT_ADDRESS());
modifies global<DiemConfig::Configuration>(CoreAddresses::DIEM_ROOT_ADDRESS());
include DiemTimestamp::AbortsIfNotOperating;
include DiemConfig::ReconfigureAbortsIf;

payload is the only field of DiemConfig, so next completely specifies it.

ensures global<DiemConfig::DiemConfig<DiemSystem>>(CoreAddresses::DIEM_ROOT_ADDRESS()).payload == value;
include DiemConfig::ReconfigureEmits;

## Function `add_validator`

Adds a new validator to the validator set.

public fun add_validator(dr_account: &signer, validator_addr: address)

Implementation

public fun add_validator(
    dr_account: &signer,
    validator_addr: address
) acquires CapabilityHolder {

    DiemTimestamp::assert_operating();
    Roles::assert_diem_root(dr_account);
    // A prospective validator must have a validator config resource
    assert(ValidatorConfig::is_valid(validator_addr), Errors::invalid_argument(EINVALID_PROSPECTIVE_VALIDATOR));

    // Bound the validator set size
    assert(
        validator_set_size() < MAX_VALIDATORS,
        Errors::limit_exceeded(EMAX_VALIDATORS)
    );

    let diem_system_config = get_diem_system_config();

    // Ensure that this address is not already a validator
    assert(
        !is_validator_(validator_addr, &diem_system_config.validators),
        Errors::invalid_argument(EALREADY_A_VALIDATOR)
    );

    // it is guaranteed that the config is non-empty
    let config = ValidatorConfig::get_config(validator_addr);
    Vector::push_back(&mut diem_system_config.validators, ValidatorInfo {
        addr: validator_addr,
        config, // copy the config over to ValidatorSet
        consensus_voting_power: 1,
        last_config_update_time: DiemTimestamp::now_microseconds(),
    });

    set_diem_system_config(diem_system_config);
}

Specification

modifies global<DiemConfig::DiemConfig<DiemSystem>>(CoreAddresses::DIEM_ROOT_ADDRESS());
include AddValidatorAbortsIf;
include AddValidatorEnsures;
include DiemConfig::ReconfigureEmits;

schema AddValidatorAbortsIf {
    dr_account: signer;
    validator_addr: address;
    aborts_if validator_set_size() >= MAX_VALIDATORS with Errors::LIMIT_EXCEEDED;
    include DiemTimestamp::AbortsIfNotOperating;
    include Roles::AbortsIfNotDiemRoot{account: dr_account};
    include DiemConfig::ReconfigureAbortsIf;
    aborts_if !ValidatorConfig::is_valid(validator_addr) with Errors::INVALID_ARGUMENT;
    aborts_if spec_is_validator(validator_addr) with Errors::INVALID_ARGUMENT;
}

schema AddValidatorEnsures {
    validator_addr: address;
}

DIP-6 property: validator has validator role. The code does not check this explicitly,
but it is implied by the assert ValidatorConfig::is_valid, since there
is an invariant (in ValidatorConfig) that a an address with a published ValidatorConfig has
a ValidatorRole

schema AddValidatorEnsures {
    ensures Roles::spec_has_validator_role_addr(validator_addr);
    ensures ValidatorConfig::is_valid(validator_addr);
    ensures spec_is_validator(validator_addr);

    let vs = spec_get_validators();
    ensures Vector::eq_push_back(vs,
                                 old(vs),
                                 ValidatorInfo {
                                     addr: validator_addr,
                                     config: ValidatorConfig::spec_get_config(validator_addr),
                                     consensus_voting_power: 1,
                                     last_config_update_time: DiemTimestamp::spec_now_microseconds(),
                                  }
                               );
}

## Function `remove_validator`

Removes a validator, aborts unless called by diem root account

public fun remove_validator(dr_account: &signer, validator_addr: address)

Implementation

public fun remove_validator(
    dr_account: &signer,
    validator_addr: address
) acquires CapabilityHolder {
    DiemTimestamp::assert_operating();
    Roles::assert_diem_root(dr_account);
    let diem_system_config = get_diem_system_config();
    // Ensure that this address is an active validator
    let to_remove_index_vec = get_validator_index_(&diem_system_config.validators, validator_addr);
    assert(Option::is_some(&to_remove_index_vec), Errors::invalid_argument(ENOT_AN_ACTIVE_VALIDATOR));
    let to_remove_index = *Option::borrow(&to_remove_index_vec);
    // Remove corresponding ValidatorInfo from the validator set
    _  = Vector::swap_remove(&mut diem_system_config.validators, to_remove_index);

    set_diem_system_config(diem_system_config);
}

Specification

modifies global<DiemConfig::DiemConfig<DiemSystem>>(CoreAddresses::DIEM_ROOT_ADDRESS());
include RemoveValidatorAbortsIf;
include RemoveValidatorEnsures;
include DiemConfig::ReconfigureEmits;

schema RemoveValidatorAbortsIf {
    dr_account: signer;
    validator_addr: address;
    include Roles::AbortsIfNotDiemRoot{account: dr_account};
    include DiemTimestamp::AbortsIfNotOperating;
    include DiemConfig::ReconfigureAbortsIf;
    aborts_if !spec_is_validator(validator_addr) with Errors::INVALID_ARGUMENT;
}

schema RemoveValidatorEnsures {
    validator_addr: address;

    let vs = spec_get_validators();
    ensures forall vi in vs where vi.addr != validator_addr: exists ovi in old(vs): vi == ovi;
}

Removed validator is no longer a validator.  Depends on no other entries for same address
in validator_set

schema RemoveValidatorEnsures {
    ensures !spec_is_validator(validator_addr);
}

## Function `update_config_and_reconfigure`

Copy the information from ValidatorConfig into the validator set.
This function makes no changes to the size or the members of the set.
If the config in the ValidatorSet changes, it stores the new DiemSystem
and emits a reconfigurationevent.

public fun update_config_and_reconfigure(validator_operator_account: &signer, validator_addr: address)

Implementation

public fun update_config_and_reconfigure(
    validator_operator_account: &signer,
    validator_addr: address,
) acquires CapabilityHolder {
    DiemTimestamp::assert_operating();
    Roles::assert_validator_operator(validator_operator_account);
    assert(
        ValidatorConfig::get_operator(validator_addr) == Signer::address_of(validator_operator_account),
        Errors::invalid_argument(EINVALID_TRANSACTION_SENDER)
    );
    let diem_system_config = get_diem_system_config();
    let to_update_index_vec = get_validator_index_(&diem_system_config.validators, validator_addr);
    assert(Option::is_some(&to_update_index_vec), Errors::invalid_argument(ENOT_AN_ACTIVE_VALIDATOR));
    let to_update_index = *Option::borrow(&to_update_index_vec);
    let is_validator_info_updated = update_ith_validator_info_(&mut diem_system_config.validators, to_update_index);
    if (is_validator_info_updated) {
        let validator_info = Vector::borrow_mut(&mut diem_system_config.validators, to_update_index);
        assert(DiemTimestamp::now_microseconds() >
               validator_info.last_config_update_time + FIVE_MINUTES,
               ECONFIG_UPDATE_RATE_LIMITED);
        validator_info.last_config_update_time = DiemTimestamp::now_microseconds();
        set_diem_system_config(diem_system_config);
    }
}

Specification

pragma opaque;
pragma verify = false;
modifies global<DiemConfig::Configuration>(CoreAddresses::DIEM_ROOT_ADDRESS());
modifies global<DiemConfig::DiemConfig<DiemSystem>>(CoreAddresses::DIEM_ROOT_ADDRESS());
include ValidatorConfig::AbortsIfGetOperator{addr: validator_addr};
include UpdateConfigAndReconfigureAbortsIf;
include UpdateConfigAndReconfigureEnsures;

let is_validator_info_updated =
    ValidatorConfig::is_valid(validator_addr) &&
    (exists v_info in spec_get_validators():
        v_info.addr == validator_addr
        && v_info.config != ValidatorConfig::spec_get_config(validator_addr));
include is_validator_info_updated ==> DiemConfig::ReconfigureAbortsIf;
include UpdateConfigAndReconfigureEmits;

schema UpdateConfigAndReconfigureAbortsIf {
    validator_addr: address;
    validator_operator_account: signer;

    let validator_operator_addr = Signer::address_of(validator_operator_account);
    include DiemTimestamp::AbortsIfNotOperating;
}

Must abort if the signer does not have the ValidatorOperator role [[H15]][PERMISSION].

schema UpdateConfigAndReconfigureAbortsIf {
    include Roles::AbortsIfNotValidatorOperator{validator_operator_addr: validator_operator_addr};
    include ValidatorConfig::AbortsIfNoValidatorConfig{addr: validator_addr};
    aborts_if ValidatorConfig::get_operator(validator_addr) != validator_operator_addr
        with Errors::INVALID_ARGUMENT;
    aborts_if !spec_is_validator(validator_addr) with Errors::INVALID_ARGUMENT;
}

Does not change the length of the validator set, only changes ValidatorInfo
for validator_addr, and doesn't change any addresses.

schema UpdateConfigAndReconfigureEnsures {
    validator_addr: address;

    let vs = spec_get_validators();
    ensures len(vs) == len(old(vs));
}

No addresses change in the validator set

schema UpdateConfigAndReconfigureEnsures {
    ensures forall i in 0..len(vs): vs[i].addr == old(vs)[i].addr;
}

If the ValidatorInfo address is not the one we're changing, the info does not change.

schema UpdateConfigAndReconfigureEnsures {
    ensures forall i in 0..len(vs) where old(vs)[i].addr != validator_addr:
                     vs[i] == old(vs)[i];
}

It updates the correct entry in the correct way

schema UpdateConfigAndReconfigureEnsures {
    ensures forall i in 0..len(vs): vs[i].config == old(vs[i].config) ||
                (old(vs)[i].addr == validator_addr &&
                vs[i].config == ValidatorConfig::get_config(validator_addr));
}

DIP-6 property

schema UpdateConfigAndReconfigureEnsures {
    ensures Roles::spec_has_validator_role_addr(validator_addr);
}

schema UpdateConfigAndReconfigureEmits {
    validator_addr: address;

    let is_validator_info_updated =
        ValidatorConfig::is_valid(validator_addr) &&
        (exists v_info in spec_get_validators():
            v_info.addr == validator_addr
            && v_info.config != ValidatorConfig::spec_get_config(validator_addr));
    include is_validator_info_updated ==> DiemConfig::ReconfigureEmits;
}

## Function `get_diem_system_config`

Get the DiemSystem configuration from DiemConfig

public fun get_diem_system_config(): DiemSystem::DiemSystem

Implementation

public fun get_diem_system_config(): DiemSystem {
    DiemConfig::get<DiemSystem>()
}

Specification

pragma opaque;
include DiemConfig::AbortsIfNotPublished<DiemSystem>;
ensures result == DiemConfig::get<DiemSystem>();

## Function `is_validator`

Return true if addr is in the current validator set

public fun is_validator(addr: address): bool

Implementation

public fun is_validator(addr: address): bool {
    is_validator_(addr, &get_diem_system_config().validators)
}

Specification

pragma opaque;
include DiemConfig::AbortsIfNotPublished<DiemSystem>;
ensures result == spec_is_validator(addr);

define spec_is_validator(addr: address): bool {
   exists v in spec_get_validators(): v.addr == addr
}

## Function `get_validator_config`

Returns validator config. Aborts if addr is not in the validator set.

public fun get_validator_config(addr: address): ValidatorConfig::Config

Implementation

public fun get_validator_config(addr: address): ValidatorConfig::Config {
    let diem_system_config = get_diem_system_config();
    let validator_index_vec = get_validator_index_(&diem_system_config.validators, addr);
    assert(Option::is_some(&validator_index_vec), Errors::invalid_argument(ENOT_AN_ACTIVE_VALIDATOR));
    *&(Vector::borrow(&diem_system_config.validators, *Option::borrow(&validator_index_vec))).config
}

Specification

pragma opaque;
include DiemConfig::AbortsIfNotPublished<DiemSystem>;
aborts_if !spec_is_validator(addr) with Errors::INVALID_ARGUMENT;
ensures
    exists info in DiemConfig::get<DiemSystem>().validators where info.addr == addr:
        result == info.config;

## Function `validator_set_size`

Return the size of the current validator set

public fun validator_set_size(): u64

Implementation

public fun validator_set_size(): u64 {
    Vector::length(&get_diem_system_config().validators)
}

Specification

pragma opaque;
include DiemConfig::AbortsIfNotPublished<DiemSystem>;
ensures result == len(spec_get_validators());

## Function `get_ith_validator_address`

Get the i'th validator address in the validator set.

public fun get_ith_validator_address(i: u64): address

Implementation

public fun get_ith_validator_address(i: u64): address {
    assert(i < validator_set_size(), Errors::invalid_argument(EVALIDATOR_INDEX));
    Vector::borrow(&get_diem_system_config().validators, i).addr
}

Specification

pragma opaque;
include DiemConfig::AbortsIfNotPublished<DiemSystem>;
aborts_if i >= len(spec_get_validators()) with Errors::INVALID_ARGUMENT;
ensures result == spec_get_validators()[i].addr;

## Function `get_validator_index_`

Get the index of the validator by address in the validators vector
It has a loop, so there are spec blocks in the code to assert loop invariants.

fun get_validator_index_(validators: &vector<DiemSystem::ValidatorInfo>, addr: address): Option::Option<u64>

Implementation

fun get_validator_index_(validators: &vector<ValidatorInfo>, addr: address): Option<u64> {
    let size = Vector::length(validators);
    let i = 0;
    while ({
        spec {
            assert i <= size;
            assert forall j in 0..i: validators[j].addr != addr;
        };
        (i < size)
    })
    {
        let validator_info_ref = Vector::borrow(validators, i);
        if (validator_info_ref.addr == addr) {
            spec {
                assert validators[i].addr == addr;
            };
            return Option::some(i)
        };
        i = i + 1;
    };
    spec {
        assert i == size;
        assert forall j in 0..size: validators[j].addr != addr;
    };
    return Option::none()
}

Specification

pragma opaque;
aborts_if false;

let size = len(validators);

If addr is not in validator set, returns none.

ensures (forall i in 0..size: validators[i].addr != addr) ==> Option::is_none(result);

If addr is in validator set, return the least index of an entry with that address.
The data invariant associated with the DiemSystem.validators that implies
that there is exactly one such address.

ensures
    (exists i in 0..size: validators[i].addr == addr) ==>
        Option::is_some(result)
        && {
                let at = Option::borrow(result);
                0 <= at && at < size && validators[at].addr == addr
            };

## Function `update_ith_validator_info_`

Updates *i*th validator info, if nothing changed, return false.
This function never aborts.

fun update_ith_validator_info_(validators: &mut vector<DiemSystem::ValidatorInfo>, i: u64): bool

Implementation

fun update_ith_validator_info_(validators: &mut vector<ValidatorInfo>, i: u64): bool {
    let size = Vector::length(validators);
    // This provably cannot happen, but left it here for safety.
    if (i >= size) {
        return false
    };
    let validator_info = Vector::borrow_mut(validators, i);
    // "is_valid" below should always hold based on a global invariant later
    // in the file (which proves if we comment out some other specifications),
    // but it is left here for safety.
    if (!ValidatorConfig::is_valid(validator_info.addr)) {
        return false
    };
    let new_validator_config = ValidatorConfig::get_config(validator_info.addr);
    // check if information is the same
    let config_ref = &mut validator_info.config;
    if (config_ref == &new_validator_config) {
        return false
    };
    *config_ref = new_validator_config;
    true
}

Specification

pragma opaque;
aborts_if false;

let new_validator_config = ValidatorConfig::spec_get_config(validators[i].addr);

Prover is able to prove this because get_validator_index_ ensures it
in calling context.

requires 0 <= i && i < len(validators);

Somewhat simplified from the code because of properties guaranteed
by the calling context.

ensures
    result ==
        (ValidatorConfig::is_valid(validators[i].addr) &&
         new_validator_config != old(validators[i].config));

It only updates validators at index i, and updates the
config field to new_validator_config.

ensures
    result ==>
        validators == update_vector(
            old(validators),
            i,
            update_field(old(validators[i]), config, new_validator_config)
        );

Does not change validators if result is false

ensures !result ==> validators == old(validators);

Updates the ith validator entry (and nothing else), as appropriate.

ensures validators == update_vector(old(validators), i, validators[i]);

Needed these assertions to make "consensus voting power is always 1" invariant
prove (not sure why).

requires forall i1 in 0..len(spec_get_validators()):
   spec_get_validators()[i1].consensus_voting_power == 1;
ensures forall i1 in 0..len(spec_get_validators()):
   spec_get_validators()[i1].consensus_voting_power == 1;

## Function `is_validator_`

Private function checks for membership of addr in validator set.

fun is_validator_(addr: address, validators_vec_ref: &vector<DiemSystem::ValidatorInfo>): bool

Implementation

fun is_validator_(addr: address, validators_vec_ref: &vector<ValidatorInfo>): bool {
    Option::is_some(&get_validator_index_(validators_vec_ref, addr))
}

Specification

pragma opaque;
aborts_if false;
ensures result == (exists v in validators_vec_ref: v.addr == addr);

## Module Specification

### Initialization

After genesis, the DiemSystem configuration is published, as well as the capability
which grants the right to modify it to certain functions in this module.

invariant [global] DiemTimestamp::is_operating() ==>
    DiemConfig::spec_is_published<DiemSystem>() &&
    exists<CapabilityHolder>(CoreAddresses::DIEM_ROOT_ADDRESS());

### Access Control

Access control requirements for validator set are a bit more complicated than
many parts of the framework because of update_config_and_reconfigure.
That function updates the validator info (e.g., the network address) for a
particular Validator Owner, but only if the signer is the Operator for that owner.
Therefore, we must ensure that the information for other validators in the
validator set are not changed, which is specified locally for
update_config_and_reconfigure.

The permission "{Add, Remove} Validator" is granted to DiemRoot [[H14]][PERMISSION].

apply Roles::AbortsIfNotDiemRoot{account: dr_account} to add_validator, remove_validator;

schema ValidatorSetConfigRemainsSame {
    ensures spec_get_validators() == old(spec_get_validators());
}

Only {add, remove} validator [[H14]][PERMISSION] and update_config_and_reconfigure
[[H15]][PERMISSION] may change the set of validators in the configuration.
set_diem_system_config is a private function which is only called by other
functions in the "except" list. initialize_validator_set is only called in
Genesis.

apply ValidatorSetConfigRemainsSame to *, *<T>
   except add_validator, remove_validator, update_config_and_reconfigure,
       initialize_validator_set, set_diem_system_config;

### Helper Functions

Fetches the currently published validator set from the published DiemConfig<DiemSystem>
resource.

define spec_get_validators(): vector<ValidatorInfo> {
   DiemConfig::get<DiemSystem>().validators
}

Every validator has a published ValidatorConfig whose config option is "some"
(meaning of ValidatorConfig::is_valid).
> Unfortunately, this times out for unknown reasons (it doesn't seem to be hard),
so it is deactivated.
The Prover can prove it if the uniqueness invariant for the DiemSystem resource
is commented out, along with aborts for update_config_and_reconfigure and everything
else that breaks (e.g., there is an ensures in remove_validator that has to be
commented out)

invariant [deactivated, global] forall i1 in 0..len(spec_get_validators()):
    ValidatorConfig::is_valid(spec_get_validators()[i1].addr);

Every validator in the validator set has a validator role.
> Note: Verification of DiemSystem seems to be very sensitive, and will
often time out after small changes.  Disabling this property
(with [deactivate, global]) is sometimes a quick temporary fix.

invariant [global] forall i1 in 0..len(spec_get_validators()):
    Roles::spec_has_validator_role_addr(spec_get_validators()[i1].addr);

Consensus_voting_power is always 1. In future implementations, this
field may have different values in which case this property will have to
change. It's here currently because and accidental or illicit change
to the voting power of a validator could defeat the Byzantine fault tolerance
of DiemBFT.

invariant [global] forall i1 in 0..len(spec_get_validators()):
    spec_get_validators()[i1].consensus_voting_power == 1;

[//]: # ("File containing references which can be used from documentation")
[ACCESS_CONTROL]: https://github.com/diem/dip/blob/main/dips/dip-2.md
[ROLE]: https://github.com/diem/dip/blob/main/dips/dip-2.md#roles
[PERMISSION]: https://github.com/diem/dip/blob/main/dips/dip-2.md#permissions


text:
Errors returned will contain only the properties that are set on the `ErrorObject` class. Custom fields can be added through `ErrorObject.Meta`.
You can create a custom error by throwing a `JsonApiException` (which accepts an `ErrorObject` instance), or returning an `ErrorObject` instance from an `ActionResult` in a controller.
Please keep in mind that JSON:API requires `Title` to be a generic message, while `Detail` should contain information about the specific problem occurence.

From a controller method:

```c#
return Conflict(new ErrorObject(HttpStatusCode.Conflict)
{
    Title = "Target resource was modified by another user.",
    Detail = $"User {userName} changed the {resourceField} field on {resourceName} resource."
});
```

From other code:

```c#
throw new JsonApiException(new ErrorObject(HttpStatusCode.Conflict)
{
    Title = "Target resource was modified by another user.",
    Detail = $"User {userName} changed the {resourceField} field on {resourceName} resource."
});
```

In both cases, the middleware will properly serialize it and return it as a JSON:API error.

# Exception handling

The translation of user-defined exceptions to error responses can be customized by registering your own handler.
This handler is also the place to choose the log level and message, based on the exception type.

```c#
public class ProductOutOfStockException : Exception
{
    public int ProductId { get; }

    public ProductOutOfStockException(int productId)
    {
        ProductId = productId;
    }
}

public class CustomExceptionHandler : ExceptionHandler
{
    public CustomExceptionHandler(ILoggerFactory loggerFactory, IJsonApiOptions options)
        : base(loggerFactory, options)
    {
    }

    protected override LogLevel GetLogLevel(Exception exception)
    {
        if (exception is ProductOutOfStockException)
        {
            return LogLevel.Information;
        }

        return base.GetLogLevel(exception);
    }

    protected override string GetLogMessage(Exception exception)
    {
        if (exception is ProductOutOfStockException productOutOfStock)
        {
            return $"Product {productOutOfStock.ProductId} is currently unavailable.";
        }

        return base.GetLogMessage(exception);
    }

    protected override IReadOnlyList<ErrorObject> CreateErrorResponse(Exception exception)
    {
        if (exception is ProductOutOfStockException productOutOfStock)
        {
            return new[]
            {
                new ErrorObject(HttpStatusCode.Conflict)
                {
                    Title = "Product is temporarily available.",
                    Detail = $"Product {productOutOfStock.ProductId} " +
                        "cannot be ordered at the moment."
                }
            };
        }

        return base.CreateErrorResponse(exception);
    }
}

// Program.cs
builder.Services.AddScoped<IExceptionHandler, CustomExceptionHandler>();
```


text:
package com.github.jsonzou.jmockdata.bean.enums;

public enum  ErrorEnum {

}


text:
/** @module reiter/repeatN */

import curry from "__curry__";

/**
 * Yields `value` repeated `n`-times.
 *
 * @since 0.0.1
 * @generator
 * @function repeatN
 * @param {number} n The number of repetitions.
 * @param {*} value The value.
 * @yields {*} `value` until `n` have been yielded.
 * @see [repeat]{@link module:reiter/repeat}
 * @example
 *
 * reiter.repeat(5, 1)
 * // => 1, 1, 1, 1, 1
 */
export default curry(function*(n, value) {
  for (let i = 0; i < n; i++) {
    yield value;
  }
});


text:
**To delete an Internet gateway**

This example deletes the specified Internet gateway. If the command succeeds, no output is returned.

Command::

  aws ec2 delete-internet-gateway --internet-gateway-id igw-c0a643a9


text:
package com.cisco.app.dbmigrator.migratorapp.utilities.oracle;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

public final class DbResourceUtils {
	private static Logger logger = Logger.getLogger(DbResourceUtils.class);
	private DbResourceUtils(){}
	public static void closeResources(ResultSet rset , Statement stmt, Connection connection){
		if(rset!=null){
			try {
				rset.close();
			} catch (SQLException e) {
				logger.error("Error in closing Resultset" , e);
			}
		}
		if(stmt!=null){
			try {
				stmt.close();
			} catch (SQLException e) {
				logger.error("Error in closing Statement" , e);
			}
		}
		if(connection!=null){
			try {
				connection.close();
			} catch (SQLException e) {
				logger.error("Error in closing Connection" , e);
			}
		}
	}

	public static boolean isValidConnection(Connection con){
		boolean isValid=true;
		try{
			if(con==null || con.isClosed()){
				logger.info("Connection is Null");
				isValid=false;
			}else{
				/*ValidConnection valCon= (ValidConnection) con;
				if(!valCon.isValid()){
					logger.info("Connection is invalid");
					isValid=false;
					valCon.setInvalid();
				}*/
			}
		}catch(SQLException e){
			isValid=false;
			logger.error("Error in validating connection ",e);
		}
		return isValid;
	}
}


text:
package org.apache.metron.management;

import static org.apache.metron.common.configuration.ConfigurationType.ENRICHMENT;
import static org.apache.metron.management.EnrichmentConfigFunctions.getConfig;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.jakewharton.fliptables.FlipTable;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig;
import org.apache.metron.common.configuration.enrichment.threatintel.RiskLevelRule;
import org.apache.metron.common.configuration.enrichment.threatintel.ThreatIntelConfig;
import org.apache.metron.common.configuration.enrichment.threatintel.ThreatTriageConfig;
import org.apache.metron.common.utils.JSONUtils;
import org.apache.metron.stellar.common.utils.ConversionUtils;
import org.apache.metron.stellar.dsl.Context;
import org.apache.metron.stellar.dsl.ParseException;
import org.apache.metron.stellar.dsl.Stellar;
import org.apache.metron.stellar.dsl.StellarFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThreatTriageFunctions {
  private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  @Stellar(
           namespace = "THREAT_TRIAGE"
          ,name = "PRINT"
          ,description = "Retrieve stellar enrichment transformations."
          ,params = {"sensorConfig - Sensor config to add transformation to."
                    }
          ,returns = "The String representation of the threat triage rules"
          )
  public static class GetStellarTransformation implements StellarFunction {

    @Override
    public Object apply(List<Object> args, Context context) throws ParseException {
      String config = (String) args.get(0);
      SensorEnrichmentConfig configObj;
      if(config == null || config.isEmpty()) {
        configObj = new SensorEnrichmentConfig();
      }
      else {
        configObj = (SensorEnrichmentConfig) ENRICHMENT.deserialize(config);
      }
      ThreatIntelConfig tiConfig = (ThreatIntelConfig) getConfig(configObj, EnrichmentConfigFunctions.Type.THREAT_INTEL);
      if(tiConfig == null) {
        return "";
      }
      ThreatTriageConfig triageConfig = tiConfig.getTriageConfig();
      if(triageConfig == null) {
        return "";
      }
      List<RiskLevelRule> triageRules = triageConfig.getRiskLevelRules();
      if(triageRules == null) {
        triageRules = new ArrayList<>();
      }
      String[] headers = new String[] {"Name", "Comment", "Triage Rule", "Score", "Reason"};
      String[][] data = new String[triageRules.size()][5];
      int i = 0;
      for(RiskLevelRule rule : triageRules) {
        double d = rule.getScore().doubleValue();
        String score = d == (long)d ? String.format("%d", (long)d) : String.format("%s", d);
        String name = Optional.ofNullable(rule.getName()).orElse("");
        String comment = Optional.ofNullable(rule.getComment()).orElse("");
        String reason = Optional.ofNullable(rule.getReason()).orElse("");
        data[i++]  = new String[] {name, comment, rule.getRule(), score, reason};
      }
      String ret = FlipTable.of(headers, data);
      if(!triageRules.isEmpty()) {
        ret += "\n\n";

        ret += "Aggregation: " + triageConfig.getAggregator().name();
      }
      return ret;
    }

    @Override
    public void initialize(Context context) {

    }

    @Override
    public boolean isInitialized() {
      return true;
    }
  }

  @Stellar(
           namespace = "THREAT_TRIAGE"
          ,name = "ADD"
          ,description = "Add a threat triage rule."
          ,params = {"sensorConfig - Sensor config to add transformation to."
                    ,"triageRules - A Map (or list of Maps) representing a triage rule.  It must contain 'rule' and 'score' keys, " +
                      "the stellar expression for the rule and triage score respectively.  " +
                      "It may contain 'name' and 'comment', the name of the rule and comment associated with the rule respectively."
                    }
          ,returns = "The String representation of the threat triage rules"
          )
  public static class AddStellarTransformation implements StellarFunction {

    @Override
    public Object apply(List<Object> args, Context context) throws ParseException {
      String config = (String) args.get(0);
      SensorEnrichmentConfig configObj;
      if(config == null || config.isEmpty()) {
        configObj = new SensorEnrichmentConfig();
      }
      else {
        configObj = (SensorEnrichmentConfig) ENRICHMENT.deserialize(config);
      }
      ThreatIntelConfig tiConfig = (ThreatIntelConfig) getConfig(configObj, EnrichmentConfigFunctions.Type.THREAT_INTEL);
      if(tiConfig == null) {
        tiConfig = new ThreatIntelConfig();
        configObj.setThreatIntel(tiConfig);
      }
      ThreatTriageConfig triageConfig = tiConfig.getTriageConfig();
      if(triageConfig == null) {
        triageConfig = new ThreatTriageConfig();
        tiConfig.setTriageConfig(triageConfig);
      }
      List<RiskLevelRule> triageRules = triageConfig.getRiskLevelRules();
      if(triageRules == null) {
        triageRules = new ArrayList<>();
      }
      Object newRuleObj = args.get(1);
      List<Map<String, Object>> newRules = new ArrayList<>();
      if(newRuleObj != null && newRuleObj instanceof List) {
        newRules = (List<Map<String, Object>>) newRuleObj;
      }
      else if(newRuleObj != null && newRuleObj instanceof Map) {
        newRules.add((Map<String, Object>) newRuleObj);
      }
      else if(newRuleObj != null) {
        throw new IllegalStateException("triageRule must be either a Map representing a single rule or a List of rules.");
      }
      for(Map<String, Object> newRule : newRules) {
        if(!(newRule == null || !newRule.containsKey("rule") || !newRule.containsKey("score"))) {
          RiskLevelRule ruleToAdd = new RiskLevelRule();
          ruleToAdd.setRule((String) newRule.get("rule"));
          ruleToAdd.setScore(ConversionUtils.convert(newRule.get("score"), Double.class));
          if (newRule.containsKey("name")) {
            ruleToAdd.setName((String) newRule.get("name"));
          }
          if (newRule.containsKey("comment")) {
            ruleToAdd.setComment((String) newRule.get("comment"));
          }
          if (newRule.containsKey("reason")) {
            ruleToAdd.setReason((String) newRule.get("reason"));
          }
          triageRules.add(ruleToAdd);
        }
      }
      triageConfig.setRiskLevelRules(triageRules);
      try {
        return JSONUtils.INSTANCE.toJSON(configObj, true);
      } catch (JsonProcessingException e) {
        LOG.error("Unable to convert object to JSON: {}", configObj, e);
        return config;
      }

    }

    @Override
    public void initialize(Context context) {

    }

    @Override
    public boolean isInitialized() {
      return true;
    }
  }

  @Stellar(
           namespace = "THREAT_TRIAGE"
          ,name = "REMOVE"
          ,description = "Remove stellar threat triage rule(s)."
          ,params = {"sensorConfig - Sensor config to add transformation to."
                    ,"rules - A list of stellar rules or rule names to remove"
                    }
          ,returns = "The String representation of the enrichment config"
          )
  public static class RemoveStellarTransformation implements StellarFunction {

    @Override
    public Object apply(List<Object> args, Context context) throws ParseException {
      String config = (String) args.get(0);
      SensorEnrichmentConfig configObj;
      if(config == null || config.isEmpty()) {
        configObj = new SensorEnrichmentConfig();
      }
      else {
        configObj = (SensorEnrichmentConfig) ENRICHMENT.deserialize(config);
      }
      ThreatIntelConfig tiConfig = (ThreatIntelConfig) getConfig(configObj, EnrichmentConfigFunctions.Type.THREAT_INTEL);
      if(tiConfig == null) {
        tiConfig = new ThreatIntelConfig();
        configObj.setThreatIntel(tiConfig);
      }
      ThreatTriageConfig triageConfig = tiConfig.getTriageConfig();
      if(triageConfig == null) {
        triageConfig = new ThreatTriageConfig();
        tiConfig.setTriageConfig(triageConfig);
      }
      List<RiskLevelRule> triageRules = triageConfig.getRiskLevelRules();
      if(triageRules == null) {
        triageRules = new ArrayList<>();
        triageConfig.setRiskLevelRules(triageRules);
      }

      Set<String> toRemove = new HashSet<>(Optional.ofNullable((List<String>) args.get(1)).orElse(new ArrayList<>()));
      for (Iterator<RiskLevelRule> it = triageRules.iterator();it.hasNext();){
        RiskLevelRule rule = it.next();
        boolean remove = toRemove.contains(rule.getRule());
        if(!remove && rule.getName() != null) {
          remove = toRemove.contains(rule.getName());
        }
        if(remove) {
          it.remove();
        }
      }
      try {
        return JSONUtils.INSTANCE.toJSON(configObj, true);
      } catch (JsonProcessingException e) {
        LOG.error("Unable to convert object to JSON: {}", configObj, e);
        return config;
      }

    }

    @Override
    public void initialize(Context context) {

    }

    @Override
    public boolean isInitialized() {
      return true;
    }
  }

  @Stellar(
           namespace = "THREAT_TRIAGE"
          ,name = "SET_AGGREGATOR"
          ,description = "Set the threat triage aggregator."
          ,params = {"sensorConfig - Sensor config to add transformation to."
                    ,"aggregator - Aggregator to use.  One of MIN, MAX, MEAN, SUM, POSITIVE_MEAN"
                    ,"aggregatorConfig - Optional config for aggregator"
                    }
          ,returns = "The String representation of the enrichment config"
          )
  public static class SetAggregator implements StellarFunction {

    @Override
    public Object apply(List<Object> args, Context context) throws ParseException {
      String config = (String) args.get(0);

      SensorEnrichmentConfig configObj;
      if(config == null || config.isEmpty()) {
        configObj = new SensorEnrichmentConfig();
      }
      else {
        configObj = (SensorEnrichmentConfig) ENRICHMENT.deserialize(config);
      }

      ThreatIntelConfig tiConfig = (ThreatIntelConfig) getConfig(configObj, EnrichmentConfigFunctions.Type.THREAT_INTEL);
      if(tiConfig == null) {
        tiConfig = new ThreatIntelConfig();
        configObj.setThreatIntel(tiConfig);
      }
      ThreatTriageConfig triageConfig = tiConfig.getTriageConfig();
      if(triageConfig == null) {
        triageConfig = new ThreatTriageConfig();
        tiConfig.setTriageConfig(triageConfig);
      }
      List<RiskLevelRule> triageRules = triageConfig.getRiskLevelRules();
      if(triageRules == null) {
        triageRules = new ArrayList<>();
        triageConfig.setRiskLevelRules(triageRules);
      }
      String aggregator = (String) args.get(1);
      triageConfig.setAggregator(aggregator);
      if(args.size() > 2) {
        Map<String, Object> aggConfig = (Map<String, Object>) args.get(2);
        triageConfig.setAggregationConfig(aggConfig);
      }
      try {
        return JSONUtils.INSTANCE.toJSON(configObj, true);
      } catch (JsonProcessingException e) {
        LOG.error("Unable to convert object to JSON: {}", configObj, e);
        return config;
      }

    }

    @Override
    public void initialize(Context context) {

    }

    @Override
    public boolean isInitialized() {
      return true;
    }
  }
}