text:
module BarkestCore
  ##
  # This module contains a number of utility functions to make generating forms even easier.
  module FormHelper

    ##
    # Creates a date picker selection field using a bootstrap input group.
    #
    # Valid options:
    # *   +input_group_size+
    #     Valid optional sizes are 'small' or 'large'.
    # *   +readonly+
    #     Set to true to make the input field read only.
    # *   +pre_calendar+
    #     Set to true to put a calendar icon before the input field.
    # *   +post_calendar+
    #     Set to true to put a calendar icon after the input field.  This is the default setting.
    # *   +pre_label+
    #     Set to a text value to put a label before the input field.  Replaces +pre_calendar+ if specified.
    # *   +post_label+
    #     Set to a text value to put a label after the input field.  Replaces +post_calendar+ if specified.
    def date_picker_field(f, method, options = {})
      options = {
          class:            'form-control',
          read_only:        false,
          pre_calendar:     false,
          pre_label:        nil,
          post_calendar:    true,
          post_label:       false,
          attrib_val:       { },
          style:            { },
          input_group_size: ''
      }.merge(options)

      style = ''
      options[:style].each { |k,v| style += "#{k}: #{v};" }

      attrib = options[:attrib_val]
      attrib[:class] = options[:class]
      attrib[:style] = style
      attrib[:readonly] = 'readonly' if options[:read_only]

      if options[:input_group_size] == 'sm' || options[:input_group_size] == 'small' || options[:input_group_size] == 'input-group-sm'
        options[:input_group_size] = 'input-group-sm'
      elsif options[:input_group_size] == 'lg' || options[:input_group_size] == 'large' || options[:input_group_size] == 'input-group-lg'
        options[:input_group_size] = 'input-group-lg'
      else
        options[:input_group_size] = ''
      end

      attrib[:value] = f.object.send(method).to_s(:date4) if f.object.send(method)
      fld = f.text_field(method, attrib)

      # must have at least one attachment, default to post-calendar.
      options[:post_calendar] = true unless options[:pre_calendar] || options[:pre_label] || options[:post_label]

      # labels override calendars.
      options[:pre_calendar] = false if options[:pre_label]
      options[:post_calendar] = false if options[:post_label]

      # construct the prefix
      if options[:pre_calendar]
        pre = ''
      elsif options[:pre_label]
        pre = "#{h options[:pre_label]}"
      else
        pre = ''
      end

      # construct the postfix
      if options[:post_calendar]
        post = ''
      elsif options[:post_label]
        post = "#{h options[:post_label]}"
      else
        post = ''
      end

      # and then the return value.
      "
#{pre}#{fld}#{post}
".html_safe
    end

    ##
    # Creates an input group containing multiple input fields.
    #
    # Valid options:
    # *   +input_group_size+
    #     Valid optional sizes are 'small' or 'large'.
    # *   +readonly+
    #     Set to true to make the input field read only.
    # *   +width+
    #     Set to any value to set the width of the overall field in percent.  Default is 100%.
    # *   +width_1+ ... +width_N+
    #     Set the width of the child field to a specific percent. Defaults to equal amount for all children.
    # *   +placeholder_1+ ... +placeholder_N+
    #     Set the placeholder of the child field.  Defaults to the method name.
    def multi_input_field(f, methods, options = {})
      raise ArgumentError.new('methods must respond to :count') unless methods.respond_to?(:count)

      options = {
          class:            'form-control',
          read_only:        false,
          attrib_val:       { },
          style:            { },
          input_group_size: ''
      }.merge(options)

      style = ''
      options[:style].each do |k,v|
        if k.to_s == 'width'
          options[:input_group_width] = "width: #{v};"
        else
          style += "#{k}: #{v};"
        end
      end

      options[:input_group_width] ||= 'width: 100%;'

      attrib = options[:attrib_val]
      attrib[:class] = options[:class]
      attrib[:readonly] = 'readonly' if options[:read_only]

      if options[:input_group_size] == 'sm' || options[:input_group_size] == 'small' || options[:input_group_size] == 'input-group-sm'
        options[:input_group_size] = 'input-group-sm'
      elsif options[:input_group_size] == 'lg' || options[:input_group_size] == 'large' || options[:input_group_size] == 'input-group-lg'
        options[:input_group_size] = 'input-group-lg'
      else
        options[:input_group_size] = ''
      end

      fld = []

      remaining_width = 100.0
      width = (100.0 / methods.count).round(2)

      builder = Proc.new do |method,label,index|
        num = index + 1
        # if user specified width, use it.
        width = options[:"width_#{num}"].to_s.to_f

        # otherwise compute the width.
        if width <= 0
          width = (remaining_width / (methods.count - index)).round(2)
          width = remaining_width if width > remaining_width || index == methods.count - 1
        end

        remaining_width -= width
        attrib[:style] = style + "width: #{width}%;"
        attrib[:value] = f.object.send(method)

        ph = options[:"placeholder_#{num}"] || (label.blank? ? method.to_s.humanize : label)
        attrib[:placeholder] = ph

        options.each do |opt_key, opt_val|
          attr_key,_,fld_num = opt_key.to_s.rpartition('_')
          if fld_num.to_i == num
            unless %w(value width placeholder).include?(attr_key)
              if %w(class style).include?(attr_key)
                attrib[:class] += ' ' + opt_val.to_s
              else
                attrib[attr_key.to_sym] = opt_val.to_s
              end
            end
          end
        end

        fld << f.text_field(method, attrib)
      end

      if methods.is_a?(Array)
        methods.each_with_index do |method, index|
          builder.call method, method.to_s.humanize, index
        end
      elsif methods.is_a?(Hash)
        methods.each_with_index do |(method,label), index|
          builder.call method, label.to_s, index
        end
      else
        raise ArgumentError.new('methods must either be an array or a hash')
      end

      "
#{fld.join}
".html_safe
    end

    ##
    # Creates a currency input field.
    #
    # Specify the +currency_symbol+ if you want it to be something other than '$'.
    # Additional options are passed on to the text field.
    def currency_field(f, method, options = {})
      # get the symbol for the field.
      sym = '$'
      if options[:currency_symbol]
        sym = options[:currency_symbol]
        options.except! :currency_symbol
      end

      # get the value
      if (val = f.object.send(method))
        options[:value] = number_with_precision val, precision: 2, delimiter: ','
      end

      # build the field
      fld = f.text_field(method, options)

      # return the value.
      "
#{h sym}#{fld}
".html_safe
    end

    ##
    # Creates a label followed by small text.
    #
    # Set the :small_text option to include small text.
    def label_with_small(f, method, text=nil, options = {}, &block)
      if text.is_a?(Hash)
        options = text
        text = nil
      end
      small_text = options.delete(:small_text)
      text = text || options.delete(:text) || method.to_s.humanize.capitalize
      lbl = f.label(method, text, options, &block) #do
      #  contents = text
      #  contents += "#{h small_text}" if small_text
      #  contents += yield if block_given?
      #  contents.html_safe
      #end
      lbl += " (#{h small_text})".html_safe if small_text
      lbl.html_safe
    end

    ##
    # Creates a form group including a label and a text field.
    #
    # To specify a label, set the +label_text+ option, otherwise the method name will be used.
    # Prefix field options with +field_+ and label options with +label_+.
    # Any additional options are passed to the form group.
    def text_form_group(f, method, options = {})
      gopt, lopt, fopt = split_form_group_options(options)
      lbl = f.label_with_small method, lopt.delete(:text), lopt
      fld = gopt[:wrap].call(f.text_field(method, fopt))
      form_group lbl, fld, gopt
    end

    ##
    # Creates a form group including a label and a text area.
    #
    # To specify a label, set the +label_text+ option, otherwise the method name will be used.
    # Prefix field options with +field_+ and label options with +label_+.
    # Any additional options are passed to the form group.
    def textarea_form_group(f, method, options = {})
      gopt, lopt, fopt = split_form_group_options(options)
      lbl = f.label_with_small method, lopt.delete(:text), lopt
      fld = gopt[:wrap].call(f.text_area(method, fopt))
      form_group lbl, fld, gopt
    end

    ##
    # Creates a form group including a label and a currency field.
    #
    # To specify a label, set the +label_text+ option, otherwise the method name will be used.
    # Prefix field options with +field_+ and label options with +label_+.
    # Any additional options are passed to the form group.
    def currency_form_group(f, method, options = {})
      gopt, lopt, fopt = split_form_group_options(options)
      lbl = f.label_with_small method, lopt.delete(:text), lopt
      fld = gopt[:wrap].call(currency_field(f, method, fopt))
      form_group lbl, fld, gopt
    end

    ##
    # Creates a form group including a label and a static field.
    # The static field is simple a readonly input field with no name.
    #
    # To specify a label, set the +label_text+ option, otherwise the method name will be used.
    # Prefix field options with +field_+ and label options with +label_+.
    # Any additional options are passed to the form group.
    def static_form_group(f, method, options = {})
      gopt, lopt, fopt = split_form_group_options(options)
      lbl = f.label_with_small method, lopt.delete(:text), lopt
      fld = gopt[:wrap].call("<input type=\"text\" class=\"form-control disabled\" readonly=\"readonly\" value=\"#{h(fopt[:value] || f.object.send(method))}\">")
      form_group lbl, fld, gopt
    end

    ##
    # Creates a form group including a label and a date picker field.
    #
    # To specify a label, set the +label_text+ option, otherwise the method name will be used.
    # Prefix field options with +field_+ and label options with +label_+.
    # Any additional options are passed to the form group.
    def date_picker_form_group(f, method, options = {})
      gopt, lopt, fopt = split_form_group_options(options)
      lbl = f.label_with_small method, lopt.delete(:text), lopt
      fld = gopt[:wrap].call(date_picker_field(f, method, fopt))
      form_group lbl, fld, gopt
    end

    ##
    # Creates a form group including a label and a multiple input field.
    #
    # To specify a label, set the +label_text+ option, otherwise the method name will be used.
    # Prefix field options with +field_+ and label options with +label_+.
    # Any additional options are passed to the form group.
    def multi_input_form_group(f, methods, options = {})
      gopt, lopt, fopt = split_form_group_options(options)
      lopt[:text] ||= gopt[:label]
      if lopt[:text].blank?
        lopt[:text] = methods.map {|k,_| k.to_s.humanize }.join(', ')
      end
      lbl = f.label_with_small methods.map{|k,_| k}.first, lopt[:text], lopt
      fld = gopt[:wrap].call(multi_input_field(f, methods, fopt))
      form_group lbl, fld, gopt
    end

    ##
    # Creates a form group including a label and a checkbox.
    #
    # To specify a label, set the +label_text+ option, otherwise the method name will be used.
    # Prefix field options with +field_+ and label options with +label_+.
    # Any additional options are passed to the form group.
    def checkbox_form_group(f, method, options = {})
      gopt, lopt, fopt = split_form_group_options({ class: 'checkbox', field_class: ''}.merge(options))

      if gopt[:h_align]
        gopt[:class] = gopt[:class].blank? ?
            "col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" :
            "#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}"
      end

      lbl = f.label method do
        f.check_box(method, fopt) +
            h(lopt[:text] || method.to_s.humanize) +
            if lopt[:small_text]
              "#{h lopt[:small_text]}"
            else
              ''
            end.html_safe
      end

      "

#{lbl}

".html_safe
    end

    ##
    # Creates a form group including a label and a collection select field.
    #
    # To specify a label, set the +label_text+ option, otherwise the method name will be used.
    # Prefix field options with +field_+ and label options with +label_+.
    # Any additional options are passed to the form group.
    def select_form_group(f, method, collection, value_method = nil, text_method = nil, options = {})
      gopt, lopt, fopt = split_form_group_options({ field_include_blank: true }.merge(options))
      lbl = f.label_with_small method, lopt.delete(:text), lopt
      value_method ||= :to_s
      text_method ||= :to_s
      opt = {}
      [:include_blank, :prompt, :include_hidden].each do |attr|
        if fopt[attr] != nil
          opt[attr] = fopt[attr]
          fopt.except! attr
        end
      end
      fld = gopt[:wrap].call(f.collection_select(method, collection, value_method, text_method, opt, fopt))
      form_group lbl, fld, gopt
    end

    private

    def form_group(lbl, fld, opt)
      ret = '
#{lbl}#{fld}
"
      ret.html_safe
    end

    def split_form_group_options(options)
      options = {class: 'form-group', field_class: 'form-control'}.merge(options || {})
      group = {}
      label = {}
      field = {}

      options.keys.each do |k|
        sk = k.to_s
        if sk.index('label_') == 0
          label[sk[6..-1].to_sym] = options[k]
        elsif sk.index('field_') == 0
          field[sk[6..-1].to_sym] = options[k]
        else
          group[k.to_sym] = options[k]
        end
      end

      group[:wrap] = Proc.new do |fld|
        fld
      end
      if group[:h_align]
        if group[:h_align].is_a?(TrueClass)
          l = 3
        else
          l = group[:h_align].to_i
        end
        l = 1 if l < 1
        l = 6 if l > 6
        f = 12 - l
        group[:h_align] = l
        label[:class] = label[:class].blank? ? "col-sm-#{l} control-label" : "#{label[:class]} col-sm-#{l} control-label"
        group[:wrap] = Proc.new do |fld|
          "
#{fld}
"
        end
      end

      [group, label, field]
    end

  end
end

# :enddoc:

ActionView::Helpers::FormBuilder.class_eval do

  def label_with_small(method, text = nil, options = {}, &block)
    @template.send(:label_with_small, self, method, text, options, &block)
  end

  def date_picker_field(method, options = {})
    @template.send(:date_picker_field, self, method, options)
  end

  def multi_input_field(methods, options = {})
    @template.send(:multi_input_field, self, methods, options)
  end

  def currency_field(method, options = {})
    @template.send(:currency_field, self, method, options)
  end

  def text_form_group(method, options = {})
    @template.send(:text_form_group, self, method, options)
  end

  def textarea_form_group(method, options = {})
    @template.send(:textarea_form_group, self, method, options)
  end

  def currency_form_group(method, options = {})
    @template.send(:currency_form_group, self, method, options)
  end

  def static_form_group(method, options = {})
    @template.send(:static_form_group, self, method, options)
  end

  def date_picker_form_group(method, options = {})
    @template.send(:date_picker_form_group, self, method, options)
  end

  def multi_input_form_group(method, options = {})
    @template.send(:multi_input_form_group, self, method, options)
  end

  def select_form_group(method, collection, value_method = nil, text_method = nil, options = {})
    @template.send(:select_form_group, self, method, collection, value_method, text_method, options)
  end

  def checkbox_form_group(method, options = {})
    @template.send(:checkbox_form_group, self, method, options)
  end
end


text:
package org.apache.geronimo.javaee6.jpa20.entities;

import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.JoinColumn;
import javax.persistence.FetchType;
import javax.persistence.CollectionTable;
import javax.persistence.OrderColumn;
import javax.persistence.Table;

@Entity
@Table(name = "Course")
public class Course implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    private Integer cid;

    private String cname;
    private String classroom;
    private String teacher;
    private String assistTeacher;

    @ElementCollection(fetch=FetchType.EAGER)
    //@CollectionTable(name="COURSE_COMMENTS")
    private List<String> evaluation;

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getClassroom() {
        return classroom;
    }

    public void setClassroom(String classroom) {
        this.classroom = classroom;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public String getTeacher() {
        return teacher;
    }

    public void setTeacher(String teacher) {
        this.teacher = teacher;
    }

    public String getAssistTeacher() {
        return assistTeacher;
    }

    public void setAssistTeacher(String assistTeacher) {
        this.assistTeacher = assistTeacher;
    }

/*        public Student getOwner() {
        return owner;
    }

    public void setOwner(Student owner) {
        this.owner = owner;
    }
*/
    public List<String> getEvaluation() {
        return evaluation;
    }

    public void setEvaluation(List<String> evaluation) {
        this.evaluation = evaluation;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (cid != null ? cid.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Course)) {
            return false;
        }
        Course other = (Course) object;
        if ((this.cid == null && other.cid != null) || (this.cid != null && !this.cid.equals(other.cid))) {
            System.out.println("This cid is" + this.cid + ",other cid is: " + ((Course) object).getCid());
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.apache.geronimo.sample.jpa20.Course[cid=" + cid + "]";
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.

namespace Client
{
    using System;
    using System.Linq;

    public class Demo
    {
        private readonly string _host;
        private readonly int _port;

        public Demo(string host, int port)
        {
            _host = host;
            _port = port;
        }

        public void Run()
        {
            var repo = new RemoteRepository(_host, _port);

            Console.WriteLine("\nGET ALL PRODUCTS:");
            foreach (var i in repo.Products)
            {
                Console.WriteLine($"  {i.Id} | {i.Name} | {i.Price:C}");
            }

            Console.WriteLine("\nCROSS JOIN:");
            Func<object, string> suffix = (x) => x + "ending";
            var crossJoinQuery =
                from c in repo.ProductCategories
                from p in repo.Products
                select new { Category = "#" + c.Name + suffix("-"), p.Name };
            var crossJoinResult = crossJoinQuery.ToList();
            foreach (var i in crossJoinResult)
            {
                Console.WriteLine($"  {i}");
            }

            Console.WriteLine("\nINNER JOIN:");
            var innerJoinQuery =
                from c in repo.ProductCategories
                join p in repo.Products on c.Id equals p.ProductCategoryId
                select new { c.Name, P = new { p.Price }, X = new { Y = string.Concat(c.Name, "-", p.Name) } };
            var innerJoinResult = innerJoinQuery.ToList();
            foreach (var i in innerJoinResult)
            {
                Console.WriteLine($"  {i}");
            }

            Console.WriteLine("\nSELECT IDs:");
            var productIdsQuery =
                from p in repo.Products
                orderby p.Price descending
                select p.Id;
            var productIds = productIdsQuery.ToList();
            foreach (var id in productIdsQuery)
            {
                Console.WriteLine($"  {id}");
            }

            Console.WriteLine("\nCOUNT:");
            var productsQuery =
                from p in repo.Products
                select p;
            Console.WriteLine($"  Count = {productsQuery.Count()}");

            Console.WriteLine("\nTOTAL AMOUNT BY CATEGORY:");
            var totalAmountByCategoryQuery =
                from c in repo.ProductCategories
                join p in repo.Products
                    on c.Id equals p.ProductCategoryId
                join i in repo.OrderItems
                    on p.Id equals i.ProductId
                group new { c, p, i } by c.Name into g
                select new
                {
                    Category = g.Key,
                    Amount = g.Sum(x => x.i.Quantity * x.p.Price),
                };

            var totalAmountByCategroyResult = totalAmountByCategoryQuery.ToDictionary(x => x.Category);
            foreach (var i in totalAmountByCategroyResult)
            {
                Console.WriteLine($"  {i}");
            }

            Console.WriteLine("\nINVALID OPERATION:");
            try
            {
                var first = totalAmountByCategoryQuery.First(x => false);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  {ex.Message}");
            }
        }
    }
}


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magento_Swatches" setup_version="2.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
            <module name="Magento_ConfigurableProduct"/>
            <module name="Magento_Eav"/>
            <module name="Magento_Customer"/>
            <module name="Magento_Store"/>
            <module name="Magento_Backend"/>
            <module name="Magento_MediaStorage"/>
            <module name="Magento_Config"/>
            <module name="Magento_LayeredNavigation"/>
            <module name="Magento_Theme"/>
        </sequence>
    </module>
</config>


text:
/*global describe, expect, it*/

'use strict';

var tableSql;

var PG_Client = require('../../../lib/dialects/postgres');
var client    = new PG_Client({});
var knex = require('../../../knex');

var equal  = require('assert').equal;

describe('PostgreSQL Config', function() {
  var knexInstance;
  var version;
  var config = {
    client: 'pg',
    connection: {
      user: 'postgres',
      password: '',
      host: '127.0.0.1',
      database: 'knex_test'
    }
  };
  describe('check version', function() {
    describe('check version < 9.2', function() {
      beforeEach(function () {
        version = '7.2';
        config.version = version;
        knexInstance = knex(config);
      });

      it('client.version', function(){
        expect(knexInstance.client.version).to.equal(version);
      });

      it('json', function() {
        tableSql = knexInstance.schema.table('public', function(t) {
          t.json('test_name');
        }).toSQL();
        equal(1, tableSql.length);
        expect(tableSql[0].sql).to.equal('alter table "public" add column "test_name" text');
      });

      it('jsonb', function() {
        tableSql = knexInstance.schema.table('public', function (t) {
          t.jsonb('test_name');
        }).toSQL();
        equal(1, tableSql.length);
        expect(tableSql[0].sql).to.equal('alter table "public" add column "test_name" text');
      });
    });

    describe('check version >= 9.2', function() {
      beforeEach(function() {
        version = '9.5';
        config.version = version;
        knexInstance = knex(config);
      });

      it('client.version', function(){
        expect(knexInstance.client.version).to.equal(version);
      });

      it('json', function() {
        tableSql = knexInstance.schema.table('public', function(t) {
          t.json('test_name');
        }).toSQL();
        equal(1, tableSql.length);
        expect(tableSql[0].sql).to.equal('alter table "public" add column "test_name" json');
      });

      it('jsonb', function() {
        tableSql = knexInstance.schema.table('public', function(t) {
          t.jsonb('test_name');
        }).toSQL();
        equal(1, tableSql.length);
        expect(tableSql[0].sql).to.equal('alter table "public" add column "test_name" jsonb');
      });
    });
  });
});

describe("PostgreSQL SchemaBuilder", function() {

  it("fixes memoization regression", function() {
    tableSql = client.schemaBuilder().createTable('users', function(table) {
      table.uuid('key');
      table.increments('id');
      table.string('email');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('create table "users" ("key" uuid, "id" serial primary key, "email" varchar(255))');
  });

  it("basic alter table", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.increments('id');
      table.string('email');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "id" serial primary key, add column "email" varchar(255)');
  });

  it('should alter columns with the alter flag', function() {
    tableSql = client.schemaBuilder().table('users', function() {
      this.string('foo').notNullable().default('foo').alter();
      this.integer('bar').alter();
    }).toSQL();

    equal(8, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" alter column "foo" drop default');
    expect(tableSql[1].sql).to.equal('alter table "users" alter column "foo" drop not null');
    expect(tableSql[2].sql).to.equal('alter table "users" alter column "foo" type varchar(255) using ("foo"::varchar(255))');
    expect(tableSql[3].sql).to.equal('alter table "users" alter column "foo" set default \'foo\'');
    expect(tableSql[4].sql).to.equal('alter table "users" alter column "foo" set not null');
    expect(tableSql[5].sql).to.equal('alter table "users" alter column "bar" drop default');
    expect(tableSql[6].sql).to.equal('alter table "users" alter column "bar" drop not null');
    expect(tableSql[7].sql).to.equal('alter table "users" alter column "bar" type integer using ("bar"::integer)');
  });

  it("alter table with schema", function() {
    tableSql = client.schemaBuilder().withSchema('myschema').table('users', function(table) {
      table.increments('id');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "myschema"."users" add column "id" serial primary key');
  });

  it("drop table", function() {
    tableSql = client.schemaBuilder().dropTable('users').toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('drop table "users"');
  });

  it("drop table with schema", function() {
    tableSql = client.schemaBuilder().withSchema('myschema').dropTable('users').toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('drop table "myschema"."users"');
  });

  it("drop table if exists", function() {
    tableSql = client.schemaBuilder().dropTableIfExists('users').toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('drop table if exists "users"');
  });

  it("drop table if exists with schema", function() {
    tableSql = client.schemaBuilder().withSchema('myschema').dropTableIfExists('users').toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('drop table if exists "myschema"."users"');
  });

  it("drop column", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dropColumn('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" drop column "foo"');
  });

  it("drop multiple columns", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dropColumn(['foo', 'bar']);
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" drop column "foo", drop column "bar"');
  });

  it("drop multiple columns with arguments", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dropColumn('foo', 'bar');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" drop column "foo", drop column "bar"');
  });

  it("drop primary", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dropPrimary();
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" drop constraint "users_pkey"');
  });

  it("drop unique", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dropUnique('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" drop constraint "users_foo_unique"');
  });

  it("drop unique, custom", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dropUnique(null, 'foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" drop constraint "foo"');
  });

  it("drop index", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dropIndex('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('drop index "users_foo_index"');
  });

  it("drop index, custom", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dropIndex(null, 'foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('drop index "foo"');
  });

  it("drop index, with schema", function() {
    tableSql = client.schemaBuilder().withSchema('mySchema').table('users', function(table) {
      table.dropIndex('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('drop index "mySchema"."users_foo_index"');
  });

  it("drop foreign", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dropForeign('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" drop constraint "users_foo_foreign"');
  });

  it("drop foreign", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dropForeign(null, 'foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" drop constraint "foo"');
  });

  it("drop timestamps", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dropTimestamps();
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" drop column "created_at", drop column "updated_at"');
  });

  it("rename table", function() {
    tableSql = client.schemaBuilder().renameTable('users', 'foo').toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" rename to "foo"');
  });

  it("rename column", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.renameColumn('foo', 'bar');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" rename "foo" to "bar"');
  });

  it("adding primary key", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.primary('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add constraint "users_pkey" primary key ("foo")');
  });

  it("adding primary key fluently", function() {
    tableSql = client.schemaBuilder().createTable('users', function(table) {
      table.string('name').primary();
    }).toSQL();
    equal(2, tableSql.length);
    expect(tableSql[0].sql).to.equal('create table "users" ("name" varchar(255))');
    expect(tableSql[1].sql).to.equal('alter table "users" add constraint "users_pkey" primary key ("name")');
  });

  it("adding foreign key", function() {
    tableSql = client.schemaBuilder().table('users', function() {
      this.foreign('foo_id').references('id').on('orders');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add constraint "users_foo_id_foreign" foreign key ("foo_id") references "orders" ("id")');

    tableSql = client.schemaBuilder().table('users', function() {
      this.integer('foo_id').references('id').on('orders');
    }).toSQL();
    equal(2, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo_id" integer');
    expect(tableSql[1].sql).to.equal('alter table "users" add constraint "users_foo_id_foreign" foreign key ("foo_id") references "orders" ("id")');
  });

  it('adding foreign key with specific identifier', function() {
    tableSql = client.schemaBuilder().table('users', function() {
      this.foreign('foo_id', 'fk_foo').references('id').on('orders');
    }).toSQL();

    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add constraint "fk_foo" foreign key ("foo_id") references "orders" ("id")');

    tableSql = client.schemaBuilder().table('users', function() {
      this.integer('foo_id').references('id').on('orders').withKeyName('fk_foo');
    }).toSQL();

    equal(2, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo_id" integer');
    expect(tableSql[1].sql).to.equal('alter table "users" add constraint "fk_foo" foreign key ("foo_id") references "orders" ("id")');
  });

  it("adds foreign key with onUpdate and onDelete", function() {
    tableSql = client.schemaBuilder().createTable('person', function(table) {
      table.integer('user_id').notNull().references('users.id').onDelete('SET NULL');
      table.integer('account_id').notNull().references('id').inTable('accounts').onUpdate('cascade');
    }).toSQL();
    equal(3, tableSql.length);
    expect(tableSql[1].sql).to.equal('alter table "person" add constraint "person_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete SET NULL');
    expect(tableSql[2].sql).to.equal('alter table "person" add constraint "person_account_id_foreign" foreign key ("account_id") references "accounts" ("id") on update cascade');
  });

  it("adding unique key", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.unique('foo', 'bar');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add constraint "bar" unique ("foo")');
  });

  it("adding unique key fluently", function() {
    tableSql = client.schemaBuilder().createTable('users', function(table) {
      table.string('email').unique();
    }).toSQL();
    equal(2, tableSql.length);
    expect(tableSql[0].sql).to.equal('create table "users" ("email" varchar(255))');
    expect(tableSql[1].sql).to.equal('alter table "users" add constraint "users_email_unique" unique ("email")');
  });

  it("adding index without value", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.index(['foo', 'bar']);
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('create index "users_foo_bar_index" on "users" ("foo", "bar")');
  });

  it("adding index", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.index(['foo', 'bar'], 'baz');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('create index "baz" on "users" ("foo", "bar")');
  });

  it("adding index fluently", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.string('name').index();
    }).toSQL();
    equal(2, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "name" varchar(255)');
    expect(tableSql[1].sql).to.equal('create index "users_name_index" on "users" ("name")');
  });

  it("adding index with an index type", function() {
     tableSql = client.schemaBuilder().table('users', function(table) {
      table.index(['foo', 'bar'], 'baz', 'gist');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('create index "baz" on "users" using gist ("foo", "bar")');
  });

  it("adding index with an index type fluently", function() {
     tableSql = client.schemaBuilder().table('users', function(table) {
      table.string('name').index('baz', 'gist');
    }).toSQL();
    equal(2, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "name" varchar(255)');
    expect(tableSql[1].sql).to.equal('create index "baz" on "users" using gist ("name")');
  });

  it("adding index with an index type and default name fluently", function() {
     tableSql = client.schemaBuilder().table('users', function(table) {
      table.string('name').index(null, 'gist');
    }).toSQL();
    equal(2, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "name" varchar(255)');
    expect(tableSql[1].sql).to.equal('create index "users_name_index" on "users" using gist ("name")');
  });

  it("adding incrementing id", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.increments('id');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "id" serial primary key');
  });

  it("adding big incrementing id", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.bigIncrements('id');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "id" bigserial primary key');
  });

  it("adding string", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.string('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" varchar(255)');
  });

  it("adding varchar with length", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.string('foo', 100);
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" varchar(100)');
  });

  it("adding a string with a default", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.string('foo', 100).defaultTo('bar');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" varchar(100) default \'bar\'');
  });

  it("adding text", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.text('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" text');
  });

  it("adding big integer", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.bigInteger('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" bigint');
  });

  it("tests a big integer as the primary autoincrement key", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.bigIncrements('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" bigserial primary key');
  });

  it("adding integer", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.integer('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" integer');
  });

  it("adding autoincrement integer", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.increments('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" serial primary key');
  });

  it("adding medium integer", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.mediumint('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" integer');
  });

  it("adding tiny integer", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.tinyint('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" smallint');
  });

  it("adding small integer", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.smallint('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" smallint');
  });

  it("adding float", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.float('foo', 5, 2);
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" real');
  });

  it("adding double", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.double('foo', 15, 8);
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" double precision');
  });

  it("adding decimal", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.decimal('foo', 5, 2);
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" decimal(5, 2)');
  });

  it("adding boolean", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.boolean('foo').defaultTo(false);
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" boolean default \'0\'');
  });

  it("adding enum", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.enum('foo', ['bar', 'baz']);
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" text check ("foo" in (\'bar\', \'baz\'))');
  });

  it("adding date", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.date('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" date');
  });

  it("adding date time", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.dateTime('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" timestamptz');
  });

  it("adding time", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.time('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" time');
  });

  it("adding timestamp", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.timestamp('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" timestamptz');
  });

  it("adding timestamps", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.timestamps();
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "created_at" timestamptz, add column "updated_at" timestamptz');
  });

  it("adding timestamps with defaults", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.timestamps(false, true);
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "created_at" timestamptz not null default CURRENT_TIMESTAMP, add column "updated_at" timestamptz not null default CURRENT_TIMESTAMP');
  });

  it("adding binary", function() {
    tableSql = client.schemaBuilder().table('users', function(table) {
      table.binary('foo');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('alter table "users" add column "foo" bytea');
  });

  it('adding jsonb', function() {
    tableSql = client.schemaBuilder().table('user', function(t) {
      t.jsonb('preferences');
    }).toSQL();
    expect(tableSql[0].sql).to.equal('alter table "user" add column "preferences" jsonb');
  });

  it('set comment', function() {
    tableSql = client.schemaBuilder().table('user', function(t) {
      t.comment('Custom comment');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('comment on table "user" is \'Custom comment\'');
  });

  it('set empty comment', function() {
    tableSql = client.schemaBuilder().table('user', function(t) {
      t.comment('');
    }).toSQL();
    equal(1, tableSql.length);
    expect(tableSql[0].sql).to.equal('comment on table "user" is \'\'');
  });

  it('allows adding default json objects when the column is json', function() {
    tableSql = client.schemaBuilder().table('user', function(t) {
      t.json('preferences').defaultTo({}).notNullable();
    }).toSQL();
    expect(tableSql[0].sql).to.equal('alter table "user" add column "preferences" json not null {}');
  });

  it('sets specificType correctly', function() {
    tableSql = client.schemaBuilder().table('user', function(t) {
      t.specificType('email', 'CITEXT').unique().notNullable();
    }).toSQL();
    expect(tableSql[0].sql).to.equal('alter table "user" add column "email" CITEXT not null');
  });

  it('allows creating an extension', function() {
    var sql = client.schemaBuilder().createExtension('test').toSQL();
    expect(sql[0].sql).to.equal('create extension "test"');
  });

  it('allows dropping an extension', function() {
    var sql = client.schemaBuilder().dropExtension('test').toSQL();
    expect(sql[0].sql).to.equal('drop extension "test"');
  });

  it('allows creating an extension only if it doesn\'t exist', function() {
    var sql = client.schemaBuilder().createExtensionIfNotExists('test').toSQL();
    expect(sql[0].sql).to.equal('create extension if not exists "test"');
  });

  it('allows dropping an extension only if it exists', function() {
    var sql = client.schemaBuilder().dropExtensionIfExists('test').toSQL();
    expect(sql[0].sql).to.equal('drop extension if exists "test"');
  });

  it('table inherits another table', function() {
    tableSql = client.schemaBuilder().createTable('inheriteeTable', function(t) {
      t.string('username');
      t.inherits('inheritedTable');
    }).toSQL();
    expect(tableSql[0].sql).to.equal('create table "inheriteeTable" ("username" varchar(255)) inherits ("inheritedTable")');
  });

  it('should warn on disallowed method', function() {
    tableSql = client.schemaBuilder().createTable('users', function(t) {
      t.string('username');
      t.engine('myISAM');
    }).toSQL();
    expect(tableSql[0].sql).to.equal('create table "users" ("username" varchar(255))');
  });

  it('#1430 - .primary & .dropPrimary takes columns and constraintName', function() {
    tableSql = client.schemaBuilder().table('users', function(t) {
      t.primary(['test1', 'test2'], 'testconstraintname');
    }).toSQL();
    expect(tableSql[0].sql).to.equal('alter table "users" add constraint "testconstraintname" primary key ("test1", "test2")');

    tableSql = client.schemaBuilder().createTable('users', function(t) {
      t.string('test').primary('testconstraintname');
    }).toSQL();

    expect(tableSql[1].sql).to.equal('alter table "users" add constraint "testconstraintname" primary key ("test")');
  });

});


text:
module MetalArchives
  ##
  # Represents a band (person or group)
  #
  class Band < Base
    ##
    # :attr_reader: id
    #
    # [Returns]
    # - +Integer+
    #
    attribute :id, type: :integer

    ##
    # :attr_reader: name
    #
    # [Returns]
    # - +String+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :name

    ##
    # :attr_reader: aliases
    #
    # [Returns]
    # - +Array+ of +String+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :aliases, multiple: true

    ##
    # :attr_reader: country
    #
    # [Returns]
    # - +ISO3166::Country+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :country, type: :country

    ##
    # :attr_reader: location
    #
    # [Returns]
    # - +String+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :location

    ##
    # :attr_reader: date_formed
    #
    # [Returns]
    # - +Date+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :date_formed, type: :date

    ##
    # :attr_reader: years_active
    #
    # [Returns]
    # - +Array+ of rdoc-ref:Range containing +Integer+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :years_active, type: :range, multiple: true

    ##
    # :attr_reader: genres
    #
    # [Returns]
    # - +Array+ of +String+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :genres, multiple: true

    ##
    # :attr_reader: lyrical_themes
    #
    # [Returns]
    # - +Array+ of +String+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :lyrical_themes, multiple: true

    ##
    # :attr_reader: label
    #
    # [Returns]
    # - rdoc-ref:Label
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :label, type: :label

    ##
    # :attr_reader: independent
    #
    # [Returns]
    # - +Boolean+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :independent, type: :boolean

    ##
    # :attr_reader: comment
    #
    # [Returns]
    # - raw HTML +String+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :comment

    ##
    # :attr_reader: status
    #
    # [Returns]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving a status code >= 400 (except 404)
    #
    attribute :status, type: :symbol, enum: [:active, :split_up, :on_hold, :unknown, :changed_name, :disputed]

    ##
    # :attr_reader: releases
    #
    # [Returns]
    # - +Array+ of rdoc-ref:Release
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :releases, type: :release, multiple: true

    ##
    # :attr_reader: members
    #
    # [Returns]
    # - +Array+ of +Hash+ containing the following keys
    #
    # [+members+]
    #   - +:artist+: rdoc-ref:Artist
    #   - +:current+: Boolean
    #   - +:years_active+: +Array+ of rdoc-ref:Range containing +Integer+
    #   - +:role+: +String+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :members, type: :hash, multiple: true

    ##
    # :attr_reader: similar
    #
    # [Returns]
    # - +Array+ of +Hash+ containing the following keys
    #
    # [+similar+]
    #   - +:band+: rdoc-ref:Band
    #   - +:score+: +Integer+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :similar, type: :hash, multiple: true

    ##
    # :attr_reader: logo
    #
    # [Returns]
    # - +URI+ (rewritten if config option was enabled)
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :logo, type: :uri

    ##
    # :attr_reader: photo
    #
    # [Returns]
    # - +URI+ (rewritten if config option was enabled)
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :photo, type: :uri

    ##
    # :attr_reader: links
    #
    # [Returns]
    # - +Array+ of +Hash+ containing the following keys
    #
    # [+links+]
    #   - +:url+: +String+
    #   - +:type+: +Symbol+, either +:official+ or +:merchandise+
    #   - +:title+: +String+
    #
    # [Raises]
    # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
    # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
    # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
    #
    attribute :links, type: :hash, multiple: true

    class << self
      ##
      # Find by attributes
      #
      # Refer to {MA's FAQ}[http://www.metal-archives.com/content/help?index=3#tab_db] for search tips.
      #
      # Returns rdoc-ref:Band or nil when no results
      #
      # [Raises]
      # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
      # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
      # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
      #
      # [+query+]
      #     Hash containing one or more of the following keys:
      #     - +:name+: +String+
      #     - +:exact+: +Boolean+
      #     - +:genre+: +String+
      #     - +:country+: +ISO3166::Country+
      #     - +:year_formation+: rdoc-ref:Range containing rdoc-ref:Date
      #     - +:comment+: +String+
      #     - +:status+: see rdoc-ref:Band.status
      #     - +:lyrical_themes+: +String+
      #     - +:location+: +String+
      #     - +:label+: rdoc-ref:Label
      #     - +:independent+: boolean
      #
      def find_by(query)
        params = map_params query

        response = MetalArchives.http.get "/search/ajax-advanced/searching/bands", params
        json = JSON.parse response.to_s

        return nil if json["aaData"].empty?

        data = json["aaData"].first
        id = Nokogiri::HTML(data.first).xpath("//a/@href").first.value.delete('\\').split("/").last.gsub(/\D/, "").to_i

        find id
      end

      ##
      # Find by attributes (no lazy loading)
      #
      # Refer to {MA's FAQ}[http://www.metal-archives.com/content/help?index=3#tab_db] for search tips.
      #
      # Returns rdoc-ref:Band or nil when no results
      #
      # [Raises]
      # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
      # - rdoc-ref:MetalArchives::Errors::NotFoundError when receiving status code 404
      # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
      #
      # [+query+]
      #     Hash containing one or more of the following keys:
      #     - +:name+: +String+
      #     - +:exact+: +Boolean+
      #     - +:genre+: +String+
      #     - +:country+: +ISO3166::Country+
      #     - +:year_formation+: rdoc-ref:Range containing rdoc-ref:Date
      #     - +:comment+: +String+
      #     - +:status+: see rdoc-ref:Band.status
      #     - +:lyrical_themes+: +String+
      #     - +:location+: +String+
      #     - +:label+: rdoc-ref:Label
      #     - +:independent+: boolean
      #
      def find_by!(query)
        obj = find_by query
        obj.load! if obj && !obj.loaded?

        obj
      end

      ##
      # Search by attributes
      #
      # Refer to {MA's FAQ}[http://www.metal-archives.com/content/help?index=3#tab_db] for search tips.
      #
      # Returns rdoc-ref:Collection of rdoc-ref:Band
      #
      # [Raises]
      # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
      # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
      #
      # [+query+]
      #     Hash containing one or more of the following keys:
      #     - +:name+: +String+
      #     - +:exact+: +Boolean+
      #     - +:genre+: +String+
      #     - +:country+: +ISO3166::Country+
      #     - +:year_formation+: rdoc-ref:Range containing rdoc-ref:Date
      #     - +:comment+: +String+
      #     - +:status+: see rdoc-ref:Band.status
      #     - +:lyrical_themes+: +String+
      #     - +:location+: +String+
      #     - +:label+: rdoc-ref:Label
      #     - +:independent+: boolean
      #
      def search_by(query)
        params = map_params query

        MetalArchives.Collection(Artist).new("/search/ajax-advanced/searching/bands", params)
      end

      ##
      # Search by name, resolves to rdoc-ref:Band.search_by <tt>(:name => name)</tt>
      #
      # Refer to {MA's FAQ}[http://www.metal-archives.com/content/help?index=3#tab_db] for search tips.
      #
      # Returns (possibly empty) +Array+ of rdoc-ref:Band
      #
      # [Raises]
      # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
      # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
      #
      # [+name+]
      #     +String+
      #
      def search(name)
        search_by(name: name.to_s)
      end

      ##
      # Get all bands
      #
      # Returns rdoc-ref:Collection of rdoc-ref:Band
      #
      # [Raises]
      # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
      # - rdoc-ref:MetalArchives::Errors::APIError when receiving status code >= 400
      #
      def all
        search_by({})
      end

      ##
      # Map attributes to MA attributes
      #
      # Returns +Hash+
      #
      # [+params+]
      #     +Hash+
      #
      def map_params(query)
        params = {
          bandName: query[:name] || "",
          exactBandMatch: (query[:exact] ? 1 : 0),
          genre: query[:genre] || "",
          yearCreationFrom: query[:year]&.begin || "",
          yearCreationTo: query[:year]&.end || "",
          bandNotes: query[:comment] || "",
          status: map_status(query[:status]),
          themes: query[:lyrical_themes] || "",
          location: query[:location] || "",
          bandLabelName: query[:label] || "",
          indieLabelBand: (query[:independent] ? 1 : 0),
        }

        params[:country] = []
        Array(query[:country]).each do |country|
          params[:country] << (country.is_a?(ISO3166::Country) ? country.alpha2 : (country || ""))
        end
        params[:country] = params[:country].first if params[:country].size == 1

        params
      end

      ##
      # Map MA band status
      #
      # Returns +Symbol+
      #
      # [Raises]
      # - rdoc-ref:MetalArchives::Errors::ParserError when parsing failed. Please report this error.
      #
      def map_status(status)
        s = {
          nil => "",
          :active => "Active",
          :split_up => "Split-up",
          :on_hold => "On hold",
          :unknown => "Unknown",
          :changed_name => "Changed name",
          :disputed => "Disputed",
        }

        raise Errors::ParserError, "Unknown status: #{status}" unless s[status]

        s[status]
      end
    end
  end
end


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Cadena.Api.Parameters;
using Cadena.Api.Rest;
using Cadena.Data;
using JetBrains.Annotations;

namespace Cadena.Engine.CyclicReceivers
{
    public class UserInfoReceiver : CyclicReceiverBase
    {
        private readonly IApiAccessor _accessor;
        private readonly Action<TwitterUser> _handler;
        private readonly UserParameter _target;

        public UserInfoReceiver(IApiAccessor accessor, [NotNull] Action<TwitterUser> handler,
            [CanBeNull] Action<Exception> exceptionHandler, [NotNull] UserParameter target)
            : base(exceptionHandler)
        {
            _accessor = accessor;
            _handler = handler ?? throw new ArgumentNullException(nameof(handler));
            _target = target ?? throw new ArgumentNullException(nameof(target));
        }

        protected override async Task<RateLimitDescription> Execute(CancellationToken token)
        {
            try
            {
                var result = await _accessor.ShowUserAsync(_target, token).ConfigureAwait(false);
                _handler(result.Result);
                return result.RateLimit;
            }
            catch (Exception ex)
            {
                CallExceptionHandler(ex);
                throw;
            }
        }
    }
}


text:
<?xml version="1.0"?>

    <meta name="generator" content="eZ Components; http://ezcomponents.org"/>
    <title>Line blocks</title>

      Line blocks

Lend us a couple of bob till Thursday.

I'm absolutely skint.

But I'm expecting a postal order and I can pay you back
as soon as it comes.

Love, Ewan.


text:
package sorcer.util;

import net.jini.config.Configuration;
import net.jini.config.EmptyConfiguration;
import net.jini.core.entry.Entry;
import net.jini.core.lookup.ServiceID;
import net.jini.core.lookup.ServiceItem;
import net.jini.core.lookup.ServiceMatches;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.lookup.ServiceItemFilter;
import net.jini.lookup.entry.Name;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sorcer.core.SorcerConstants;
import sorcer.core.provider.Cataloger;
import sorcer.core.provider.Provider;
import sorcer.core.provider.ServiceName;
import sorcer.core.signature.NetSignature;
import sorcer.jini.lookup.entry.SorcerServiceInfo;
import sorcer.river.Filters;
import sorcer.service.Accessor;
import sorcer.service.Signature;
import sorcer.service.SignatureException;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static sorcer.core.SorcerConstants.ANY;

/**
 * A utility class that provides access to SORCER services and some
 * infrastructure services. It extends the ServiceAccessor
 * functionality.
 *
 * The getService methods directly use ServiceAccessor calls while
 * the getService methods use a SORCER Cataloger's cached services
 * with round robin load balancing.
 *
 * The individual SORCER services should be accessed using this utility since it
 * uses local cached proxies for frequently used SORCER infrastructure services,
 * for example: Cataloger, JavaSpace, Jobber. ProviderAccessor normally uses
 * Cataloger if available, otherwise it uses Jini lookup services as implemented
 * by ServiceAccessor.
 *
 * @see ServiceAccessor
 */

public class ProviderAccessor extends ServiceAccessor {
	static Logger logger = LoggerFactory.getLogger(ProviderAccessor.class.getName());

    /**
	 * Used for local caching to speed up getting frequently needed service
	 * providers. Calls to discover JavaSpace takes a lot of time.
	 */
	protected static Cataloger cataloger;

    protected static ProviderNameUtil providerNameUtil = new SorcerProviderNameUtil();

    /* Zero-arg constructor for testing purposes, should not be used without a configuration */
    public ProviderAccessor() {
        this(EmptyConfiguration.INSTANCE);
    }

	public ProviderAccessor(Configuration configuration) {
		super(configuration);
	}

    /**
     * Returns a SORCER service provider with the specified signature,
     * Added for compatibility with AFRL SORCER
     *
     * @param signature
     *            the signature of service provider
     * @return a SORCER provider service
     */
    public Provider getProvider(Signature signature) throws SignatureException {
		if (signature.getProviderName() instanceof ServiceName) {
			// for handling dynamic groups in signature
			return ProviderLocator.getProvider(signature);
		} else {
			return (Provider) getService(signature);
		}
    }

    /**
     * Returns a SORCER service provider with the specified service type, using
     * a Cataloger if available, otherwise using Jini lookup services.
     *
     * @param serviceType
     *            a provider service type (interface)
     * @return a SORCER provider service
     */
    public Provider getProvider(Class serviceType) throws SignatureException {
		return getProvider(new NetSignature(serviceType));
	}

    /**
	 * Returns a SORCER service provider registered with the most significant
	 * and the least significant bits.
	 *
	 * @param mostSig
	 *            most significant bits
	 * @param leastSig
	 *            least significant bits
	 * @return a SORCER provider service
	 */
	public Object getService(long mostSig, long leastSig) {
		ServiceID serviceID = new ServiceID(mostSig, leastSig);
		return getService(serviceID, null, null);
	}

	/**
	 * Returns a SORCER service provider with the specified name and service
	 * type, using a Cataloger if available, otherwise using Jini lookup
	 * services.
	 *
	 * @param providerName
	 *            the name of service provider
	 * @param serviceType
	 *            a provider service type (interface)
	 * @return a SORCER provider service
	 */
    @SuppressWarnings("unchecked")
	public <T> T getProvider(String providerName, Class<T> serviceType) {
		Provider servicer = null;
		if (providerName != null) {
            if (providerName.equals(SorcerConstants.ANY))
                providerName = null;
            if(SorcerConstants.NAME_DEFAULT.equals(providerName)){
                providerName = providerNameUtil.getName(serviceType);
            }
        }

		try {
			//servicer = (Service)ProviderLookup.getService(providerName, serviceType);
			cataloger = getLocalCataloger();
			if (cataloger != null) {
                long t0 = System.currentTimeMillis();
                logger.info("Use Cataloger to discover {} {}", providerName, serviceType.getName());
				int tryNo = 0;
				while (tryNo < ServiceAccessor.LUS_REPEAT) {
					servicer = cataloger.lookup(providerName, serviceType);
					//servicer = (Service)cataloger.lookupItem(providerName, serviceType).service;
					if (servicer != null)
						break;

					Thread.sleep(ServiceAccessor.WAIT_FOR);
					tryNo++;
				}
                logger.info("Waited {} millis to discover {} {}", (System.currentTimeMillis()-t0), providerName, serviceType.getName());
			}
            // fall back on Jini LUS
            if (servicer == null) {
                if(cataloger!=null)
                    logger.info("Could not find {} {} in Cataloger, discover using Lookup service",
                                providerName, serviceType.getName());
                else
                    logger.info("No Cataloger, discover {} {} using Lookup service",
                                providerName, serviceType==null?"<null>" : serviceType.getName());
                servicer = (Provider) super.getService(providerName, serviceType);
            }
		} catch (Throwable ex) {
			logger.error("getService {} {}", providerName, serviceType==null?"<null>": serviceType.getName(), ex);
		}
		return (T) servicer;
	}

    /**
	 * Returns a SORCER service provider with the specified service ID using a
	 * Cataloger if available, otherwise using Jini lookup services.
	 *
	 * @param serviceID
	 *            serviceID of the desired service
	 * @return a SORCER provider service
	 */
	public Object getService(ServiceID serviceID) {
		try {
			cataloger = getLocalCataloger();
			if (cataloger != null)
				return cataloger.lookup(serviceID);
			else
				return super.getService(serviceID);
		} catch (Exception ex) {
			logger.error(ProviderAccessor.class.getName(), "getService", ex);
			return null;
		}
	}

    /**
	 * Returns a SORCER service provider matching a given attributes.
	 *
	 * @param attributes
	 *            attribute setValue to match
	 * @return a SORCER provider
	 */
	public Provider getProvider(Entry[] attributes) {
		return (Provider) getService(null, null, attributes);
	}

	/**
	 * Returns a SORCER service provider matching a given list of implemented
	 * service types (interfaces).
	 *
	 * @param serviceTypes
	 *            a setValue of service types to match
	 * @return a SORCER provider
	 */
	public Provider getProvider(Class[] serviceTypes) {
		return (Provider) getService(null, serviceTypes, null);
	}

	/**
	 * Returns a SORCER Cataloger Service.
	 *
	 * This method searches for either a JINI or a RMI Cataloger service.
	 *
	 * @return a Cataloger service proxy
     * @see sorcer.core.provider.Cataloger
	 */
	protected Cataloger getLocalCataloger() {
        return getCataloger(providerNameUtil.getName(Cataloger.class)) ;
	}

	/**
	 * Returns a SORCER Cataloger service provider using JINI discovery.
	 *
	 * @return a SORCER Cataloger
	 */
    protected Cataloger getCataloger(String serviceName) {
        boolean catIsOk;
		try {
            catIsOk = Accessor.isAlive((Provider) cataloger);
            if (catIsOk) {
				return cataloger;
			} else {
                ServiceItem[] serviceItems = getServiceItems(getServiceTemplate(null, serviceName, new Class[]{Cataloger.class}, null),
                                                             1,
                                                             1,
                                                             Filters.any());
                cataloger = serviceItems.length == 0 ? null : (Cataloger) serviceItems[0].service;
                if (Accessor.isAlive((Provider)cataloger))
                    return cataloger;
                else
                    return null;
            }
		} catch (Exception e) {
			logger.error("Problem getting Cataloger", e);
			return null;
		}
	}

    /**
	 * Returns a SORCER service using a cached Cataloger instance by this
	 * ProviderAccessor. However if it not possible uses a ServiceAccessor to
	 * get a requested service form Jini lookup services directly. This approach
	 * allows for SORCER requestors and providers to avoid continuous usage of
	 * lookup discovery for each needed service that is delegated to a SORCER
	 * Cataloger service.
	 *
	 * @param providerName
	 *            - a name of requested service
	 * @param primaryInterface
	 *            - service type of requested provider
	 * @return a requested service or null if a Cataloger is not available
	 */
	protected Provider lookup(String providerName, Class<Provider> primaryInterface) {
		try {
			// check if the cataloger is alive then return a requested service
			// provider
			if (Accessor.isAlive((Provider) cataloger))
				return cataloger.lookup(providerName, primaryInterface);
			else {
				// try to get a new cataloger and lookup again
				cataloger = getService(providerNameUtil.getName(Cataloger.class), Cataloger.class);
				if (cataloger != null) {
					logger.debug("Got service provider from Cataloger");
					return cataloger.lookup(providerName, primaryInterface);
				} else {
					// just get a provider without a Cataloger, use directly
					// LUSs
					logger.error("No SORCER cataloger available");
					return getService(providerName, primaryInterface);
				}
			}
		} catch (RemoteException ex) {
			logger.error(ProviderAccessor.class.getName(), "lookup", ex);
			return null;
		}
	}

    @Override
    public ServiceItem[] getServiceItems(ServiceTemplate template, int minMatches, int maxMatches, ServiceItemFilter filter) {
        assert template != null;

        // cataloger throws NPE if attributeSetTemplates is null
        assert template.attributeSetTemplates != null;
        assert filter != null;
        assert minMatches <= maxMatches;

        if(!Arrays.asList(template.serviceTypes).contains(Cataloger.class)){
			Cataloger cataloger = getLocalCataloger();
            if (cataloger != null) {
			    try {
                    ServiceMatches matches = cataloger.lookup(template, maxMatches);
                    logger.debug("Cataloger returned {} matches for {}", matches.totalMatches, formatServiceTemplate(template));
			        ServiceItem[] matching = Filters.matching(matches.items, filter);
                    if (matching.length > 0) {
                        return matching;
                    } else {
                        return super.getServiceItems(template, minMatches, maxMatches, filter);
                    }
                } catch (RemoteException e) {
                    logger.error( "Problem with Cataloger, falling back", e);
                }
            }
        }
		return super.getServiceItems(template, minMatches, maxMatches, filter);
    }

    ServiceTemplate getServiceTemplate(ServiceID serviceID,
                                       String providerName,
                                       Class[] serviceTypes,
                                       String[] publishedServiceTypes) {
        Class[] types;
        List<Entry> attributes = new ArrayList<>(2);

        if (providerName != null && !providerName.isEmpty() && !ANY.equals(providerName))
            attributes.add(new Name(providerName));

        if (publishedServiceTypes != null) {
            SorcerServiceInfo st = new SorcerServiceInfo();
            st.publishedServices = publishedServiceTypes;
            attributes.add(st);
        }

        if (serviceTypes == null) {
            types = new Class[] { Provider.class };
        } else {
            types = serviceTypes;
        }

        logger.debug("getServiceTemplate >> \n serviceID: {}\nproviderName: {}\nserviceTypes: {}\npublishedServiceTypes: {}",
                     serviceID, providerName, StringUtils.arrayToString(serviceTypes), StringUtils.arrayToString(publishedServiceTypes));

        return new ServiceTemplate(serviceID, types, attributes.toArray(new Entry[attributes.size()]));
    }
}


text:
"""Smart energy channels module for Zigbee Home Automation."""
from typing import Coroutine, Union

import zigpy.zcl.clusters.smartenergy as smartenergy

from homeassistant.const import (
    POWER_WATT,
    TIME_HOURS,
    TIME_SECONDS,
    VOLUME_FLOW_RATE_CUBIC_FEET_PER_MINUTE,
    VOLUME_FLOW_RATE_CUBIC_METERS_PER_HOUR,
)
from homeassistant.core import callback

from .. import registries, typing as zha_typing
from ..const import REPORT_CONFIG_DEFAULT
from .base import ZigbeeChannel

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Calendar.cluster_id)
class Calendar(ZigbeeChannel):
    """Calendar channel."""

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.DeviceManagement.cluster_id)
class DeviceManagement(ZigbeeChannel):
    """Device Management channel."""

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Drlc.cluster_id)
class Drlc(ZigbeeChannel):
    """Demand Response and Load Control channel."""

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.EnergyManagement.cluster_id)
class EnergyManagement(ZigbeeChannel):
    """Energy Management channel."""

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Events.cluster_id)
class Events(ZigbeeChannel):
    """Event channel."""

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.KeyEstablishment.cluster_id)
class KeyEstablishment(ZigbeeChannel):
    """Key Establishment channel."""

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.MduPairing.cluster_id)
class MduPairing(ZigbeeChannel):
    """Pairing channel."""

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Messaging.cluster_id)
class Messaging(ZigbeeChannel):
    """Messaging channel."""

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Metering.cluster_id)
class Metering(ZigbeeChannel):
    """Metering channel."""

    REPORT_CONFIG = [{"attr": "instantaneous_demand", "config": REPORT_CONFIG_DEFAULT}]

    unit_of_measure_map = {
        0x00: POWER_WATT,
        0x01: VOLUME_FLOW_RATE_CUBIC_METERS_PER_HOUR,
        0x02: VOLUME_FLOW_RATE_CUBIC_FEET_PER_MINUTE,
        0x03: f"ccf/{TIME_HOURS}",
        0x04: f"US gal/{TIME_HOURS}",
        0x05: f"IMP gal/{TIME_HOURS}",
        0x06: f"BTU/{TIME_HOURS}",
        0x07: f"l/{TIME_HOURS}",
        0x08: "kPa",
        0x09: "kPa",
        0x0A: f"mcf/{TIME_HOURS}",
        0x0B: "unitless",
        0x0C: f"MJ/{TIME_SECONDS}",
    }

    def __init__(
        self, cluster: zha_typing.ZigpyClusterType, ch_pool: zha_typing.ChannelPoolType
    ) -> None:
        """Initialize Metering."""
        super().__init__(cluster, ch_pool)
        self._format_spec = None

    @property
    def divisor(self) -> int:
        """Return divisor for the value."""
        return self.cluster.get("divisor") or 1

    @property
    def multiplier(self) -> int:
        """Return multiplier for the value."""
        return self.cluster.get("multiplier") or 1

    def async_configure_channel_specific(self) -> Coroutine:
        """Configure channel."""
        return self.fetch_config(False)

    def async_initialize_channel_specific(self, from_cache: bool) -> Coroutine:
        """Initialize channel."""
        return self.fetch_config(True)

    @callback
    def attribute_updated(self, attrid: int, value: int) -> None:
        """Handle attribute update from Metering cluster."""
        if None in (self.multiplier, self.divisor, self._format_spec):
            return
        super().attribute_updated(attrid, value)

    @property
    def unit_of_measurement(self) -> str:
        """Return unit of measurement."""
        uom = self.cluster.get("unit_of_measure", 0x7F)
        return self.unit_of_measure_map.get(uom & 0x7F, "unknown")

    async def fetch_config(self, from_cache: bool) -> None:
        """Fetch config from device and updates format specifier."""
        results = await self.get_attributes(
            ["divisor", "multiplier", "unit_of_measure", "demand_formatting"],
            from_cache=from_cache,
        )

        fmting = results.get(
            "demand_formatting", 0xF9
        )  # 1 digit to the right, 15 digits to the left

        r_digits = int(fmting & 0x07)  # digits to the right of decimal point
        l_digits = (fmting >> 3) & 0x0F  # digits to the left of decimal point
        if l_digits == 0:
            l_digits = 15
        width = r_digits + l_digits + (1 if r_digits > 0 else 0)

        if fmting & 0x80:
            self._format_spec = "{:" + str(width) + "." + str(r_digits) + "f}"
        else:
            self._format_spec = "{:0" + str(width) + "." + str(r_digits) + "f}"

    def formatter_function(self, value: int) -> Union[int, float]:
        """Return formatted value for display."""
        value = value * self.multiplier / self.divisor
        if self.unit_of_measurement == POWER_WATT:
            # Zigbee spec power unit is kW, but we show the value in W
            value_watt = value * 1000
            if value_watt < 100:
                return round(value_watt, 1)
            return round(value_watt)
        return self._format_spec.format(value).lstrip()

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Prepayment.cluster_id)
class Prepayment(ZigbeeChannel):
    """Prepayment channel."""

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Price.cluster_id)
class Price(ZigbeeChannel):
    """Price channel."""

@registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Tunneling.cluster_id)
class Tunneling(ZigbeeChannel):
    """Tunneling channel."""


text:
<?xml version="1.0"?>
<document>

  <properties>
    <author email="bayard@generationjava.com">Henri Yandell</author>
    <title>Manual</title>
  </properties>

Why use Simple-JNDI?

Downloading

Configuring

Configuring with Maven2

Simple-JNDI design

Creating your data files

Using Converters

Using as a Configuration system

Using the JNDI Memory implementation separately

Using the JNDI loader system separately

DataSources + Pooling

Index of supported properties for jndi.properties

List of future ideas

Submitting bugs

Compiling the source

Submitting patches

</document>


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\customer\EmailRecord */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'purpose')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'address')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
//
//  GTLCalendarEvents.h
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Calendar API (calendar/v3)
// Description:
//   Lets you manipulate events and other calendar data.
// Documentation:
//   https://developers.google.com/google-apps/calendar/firstapp
// Classes:
//   GTLCalendarEvents (0 custom class methods, 10 custom properties)

#if GTL_BUILT_AS_FRAMEWORK
  #import "GTL/GTLObject.h"
#else
  #import "GTLObject.h"
#endif

@class GTLCalendarEvent;
@class GTLCalendarEventReminder;

// ----------------------------------------------------------------------------
//
//   GTLCalendarEvents
//

// This class supports NSFastEnumeration over its "items" property. It also
// supports -itemAtIndex: to retrieve individual objects from "items".

@interface GTLCalendarEvents : GTLCollectionObject

// The user's access role for this calendar. Read-only. Possible values are:
// - "none" - The user has no access.
// - "freeBusyReader" - The user has read access to free/busy information.
// - "reader" - The user has read access to the calendar. Private events will
// appear to users with reader access, but event details will be hidden.
// - "writer" - The user has read and write access to the calendar. Private
// events will appear to users with writer access, and event details will be
// visible.
// - "owner" - The user has ownership of the calendar. This role has all of the
// permissions of the writer role with the additional ability to see and
// manipulate ACLs.
@property (copy) NSString *accessRole;

// The default reminders on the calendar for the authenticated user. These
// reminders apply to all events on this calendar that do not explicitly
// override them (i.e. do not have 'reminders.useDefault' set to 'true').
@property (retain) NSArray *defaultReminders;  // of GTLCalendarEventReminder

// Description of the calendar. Read-only.
// Remapped to 'descriptionProperty' to avoid NSObject's 'description'.
@property (copy) NSString *descriptionProperty;

// ETag of the collection.
@property (copy) NSString *ETag;

// List of events on the calendar.
@property (retain) NSArray *items;  // of GTLCalendarEvent

// Type of the collection ("calendar#events").
@property (copy) NSString *kind;

// Token used to access the next page of this result. Omitted if no further
// results are available.
@property (copy) NSString *nextPageToken;

// Title of the calendar. Read-only.
@property (copy) NSString *summary;

// The time zone of the calendar. Read-only.
@property (copy) NSString *timeZone;

// Last modification time of the calendar (as a RFC 3339 timestamp). Read-only.
@property (retain) GTLDateTime *updated;

@end


text:
<?php
namespace Df\Framework\Upgrade;
use Magento\Framework\Setup\ModuleContextInterface as IModuleContext;
use Magento\Framework\Setup\SchemaSetupInterface as ISchemaSetup;
use Magento\Framework\Setup\UpgradeSchemaInterface as IUpgradeSchema;
/**
 * 2016-08-14
 * @see \Df\API\Setup\UpgradeSchema
 * @see \Df\Customer\Setup\UpgradeSchema
 * @see \Df\OAuth\Setup\UpgradeSchema
 * @see \Df\Sales\Setup\Schema
 * @see \Df\Sales\Setup\UpgradeSchema
 * @see \Df\Sso\Upgrade\Schema
 * @see \Dfe\Color\Setup\UpgradeSchema
 * @see \Dfe\Markdown\Setup\UpgradeSchema
 * @see \Inkifi\Pwinty\Setup\UpgradeSchema
 * @see \Inkifi\Pwinty\Setup\UpgradeSchema
 * @see \Justuno\M2\Setup\UpgradeSchema
 * @see \KingPalm\B2B\Setup\UpgradeSchema
 * @see \Verdepieno\Core\Setup\UpgradeSchema
 */
abstract class Schema extends \Df\Framework\Upgrade implements IUpgradeSchema {
	/**
	 * 2016-08-14
	 * @override
	 * @see IUpgradeSchema::upgrade()
	 * @used-by \Magento\Setup\Model\Installer::handleDBSchemaData():
	 *		if ($currentVersion !== '') {
	 *			$status = version_compare($configVer, $currentVersion);
	 *			if ($status == \Magento\Framework\Setup\ModuleDataSetupInterface::VERSION_COMPARE_GREATER) {
	 *				$upgrader = $this->getSchemaDataHandler($moduleName, $upgradeType);
	 *				if ($upgrader) {
	 *					$this->log->logInline("Upgrading $type.. ");
	 *					$upgrader->upgrade($setup, $moduleContextList[$moduleName]);
	 *				}
	 *				if ($type === 'schema') {
 	 *					$resource->setDbVersion($moduleName, $configVer);
	 *				}
	 *				elseif ($type === 'data') {
	 *					$resource->setDataVersion($moduleName, $configVer);
	 *				}
	 *			}
	 *		}
	 *		elseif ($configVer) {
	 *			$installer = $this->getSchemaDataHandler($moduleName, $installType);
	 *			if ($installer) {
	 *				$this->log->logInline("Installing $type... ");
	 *				$installer->install($setup, $moduleContextList[$moduleName]);
	 *			}
	 *			$upgrader = $this->getSchemaDataHandler($moduleName, $upgradeType);
	 *			if ($upgrader) {
	 *				$this->log->logInline("Upgrading $type... ");
	 *				$upgrader->upgrade($setup, $moduleContextList[$moduleName]);
	 *			}
	 *			if ($type === 'schema') {
	 *				$resource->setDbVersion($moduleName, $configVer);
	 *			}
	 *			elseif ($type === 'data') {
	 *				$resource->setDataVersion($moduleName, $configVer);
	 *			}
	 *		}
	 * https://github.com/magento/magento2/blob/2.2.0-RC1.6/setup/src/Magento/Setup/Model/Installer.php#L844-L881
	 */
	function upgrade(ISchemaSetup $setup, IModuleContext $context):void {$this->process($setup, $context);}
}


text:
package jadx.tests.integration.trycatch;

import org.junit.jupiter.api.Test;

import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.IntegrationTest;

import static jadx.tests.api.utils.JadxMatchers.containsOne;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;

public class TestTryCatchInIf extends IntegrationTest {

	public static class TestCls {

		private String test(String name, String value) {
			if (value != null) {
				try {
					int key;
					if (value.startsWith("0x")) {
						value = value.substring(2);
						key = Integer.parseInt(value, 16);
					} else {
						key = Integer.parseInt(value);
					}
					return name + '=' + key;
				} catch (NumberFormatException e) {
					return "Failed to parse number";
				}
			}
			System.out.println("?");
			return null;
		}

		public void check() {
			assertNull(test("n", null));
			assertEquals("n=7", test("n", "7"));
			assertEquals("n=77", test("n", "0x" + Integer.toHexString(77)));
			assertEquals("Failed to parse number", test("n", "abc"));
			assertEquals("Failed to parse number", test("n", "0xabX"));
		}
	}

	@Test
	public void test() {
		ClassNode cls = getClassNode(TestCls.class);
		String code = cls.getCode().toString();

		assertThat(code, containsOne("try {"));
		assertThat(code, containsOne("} catch (NumberFormatException e) {"));
	}
}


text:
steal.then(function() {
	var ignoreCheck = /\@documentjs-ignore/,
		commentReg = /\r?\n(\s*\*+)?/g,
		spaceReg = /\S/g;

	/**
	 * Represents a file.
	 * Breaks up file into comment and code parts.
	 * Creates new [DocumentJS.Pair | Doc.Pairs].
	 * @hide
	 */
	DocumentJS.Script = {

		// returns the min intented amount for these lines.
		minSpace : function(lines){
			var removeSpace = Infinity,
				noSpace = spaceReg,
				match;

			for ( l = 0; l < lines.length; l++ ) {
				match = noSpace.exec(lines[l]);
				if ( match && lines[l] && noSpace.lastIndex < removeSpace ) {
					removeSpace = noSpace.lastIndex;
				}
				noSpace.lastIndex = 0;
			}
			return removeSpace - 1;
		},
		// removes Indent inline
		removeIndent : function(lines){
			var removeSpace = this.minSpace(lines);

			if ( isFinite(removeSpace) ) {
				for ( l = 0; l < lines.length; l++ ) {

					lines[l] = lines[l].substr(removeSpace)
				}
			}
			return lines;
		},
		getCommentCodePairs : function(){

		},
		group: new RegExp("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/\[^\\w\\{\\(\\[/]*[^\\n]*)", "g"),

		// (?:/\*+((?:[^*]|(?:\*+[^*/]))*)\*+/[^\w\{\(\[\"'\$]*([^\r\n]*))
		splitter: new RegExp("(?:/\\*+((?:[^*]|(?:\\*+[^*/]))*)\\*+/\[^\\w\\{\\(\\[\"'\$]*([^\\r\\n]*))"),

		/**
		 * Generates docs for a file.
		 * @param {Object} docScript an object that has src and text attributes.  It can also just be
		 * the path of a file.
		 */
		process: function( docScript, objects ) {
			if(typeof docScript == 'string'){
				docScript = {src: docScript}
			}

			var source = docScript.text || readFile(docScript.src);

			//check if the source has @documentjs-ignore
			if (ignoreCheck.test(source) ) {
				return;
			}
			var script = {
					type: "script",
					name: docScript.src
				},
				scope = script,
				comments,
				type;

			print("  " + script.name);
			objects[script.name] = script;

			// handle markdown docs
			if(/\.md$/.test(docScript.src)){
				type = DocumentJS.Type.create(source, "", scope, objects, 'page', docScript.src.match(/([^\/]+)\.md$/)[1]  );
				if ( type ) {

					objects[type.name] = type;
					//get the new scope if you need it
					// if we don't have a type, assume we can have children
					scope = !type.type || DocumentJS.types[type.type].hasChildren ? type : scope;
					type.src = docScript.src;
				}
				return;
			}

			comments = this.getComments(source);

			//clean comments
			for(var i =0 ; i < comments.length; i++){
				var comment = comments[i];

				type = DocumentJS.Type.create(comment.comment,
							comment.code, scope, objects);
				if ( type ) {
					objects[type.name] = type;
					//get the new scope if you need it
					// if we don't have a type, assume we can have children
					scope = !type.type || DocumentJS.types[type.type].hasChildren ? type : scope;

					type.src = docScript.src;
				}
			}

		},
		//
		getComments : function(source){
			var pairs = source.match(this.group) || [],
				comments = [],
				len = pairs.length;
			//clean comments
			for ( var i = 0; i < len; i++ ) {
				var splits = pairs[i].match(this.splitter),
					comment = splits[1].replace(commentReg, '\n');

				//print(splits[1].replace(/^[^\w@]*/,''))
				var code = splits[2],
					lines = comment.split("\n");

				this.removeIndent(lines);
				comment = lines.join("\n");

				// probably want line numbers and such
				comments.push({
					comment: comment,
					code: code
				})
			}
			return comments;
		}
	};

	DocumentJS.Type("script", {
		useName: false,
		hasChildren: true
	})
})


text:
package parser

import "fmt"

func (*AlterTable) statement() {}
func (*AlterView) statement()  {}

// AlterTable represents a ALTER TABLE statement.
type AlterTable struct {
	Name string
}

func (node *AlterTable) String() string {
	return fmt.Sprintf("ALTER TABLE %s", node.Name)
}

// AlterView represents a ALTER VIEW statement.
type AlterView struct {
	Name string
}

func (node *AlterView) String() string {
	return fmt.Sprintf("ALTER VIEW %s", node.Name)
}