text:
require 'spec_helper'

describe "Connection" do

  before(:all) do
    @raw_conn = get_connection
    @conn = PLSQL::Connection.create( @raw_conn )
  end

  after(:all) do
    unless defined?(JRuby)
      @raw_conn.logoff rescue nil
    else
      @raw_conn.close rescue nil
    end
  end

  describe "create and destroy" do
    before(:all) do
      @raw_conn1 = get_connection
    end

    before(:each) do
      @conn1 = PLSQL::Connection.create( @raw_conn1 )
    end

    it "should create connection" do
      expect(@conn1.raw_connection).to eq @raw_conn1
    end

    unless defined?(JRuby)
      it "should be oci connection" do
        expect(@conn1).to be_oci
        expect(@conn1.raw_driver).to eq :oci
      end
    else
      it "should be jdbc connection" do
        expect(@conn1).to be_jdbc
        expect(@conn1.raw_driver).to eq :jdbc
      end
    end

    it "should logoff connection" do
      expect(@conn1.logoff).to be true
    end

  end

  # Ruby 1.8 and 1.9
  unless defined?(JRuby)
    describe "OCI data type conversions" do
      it "should translate PL/SQL VARCHAR to Ruby String" do
        expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR", :data_length => 100)).to eq [String, 100]
        expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR", :data_length => nil)).to eq [String, 32767]
      end

      it "should translate PL/SQL VARCHAR2 to Ruby String" do
        expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR2", :data_length => 100)).to eq [String, 100]
        expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR2", :data_length => nil)).to eq [String, 32767]
      end

      it "should translate PL/SQL CLOB to Ruby String" do
        expect(@conn.plsql_to_ruby_data_type(:data_type => "CLOB", :data_length => 100_000)).to eq [OCI8::CLOB, nil]
        expect(@conn.plsql_to_ruby_data_type(:data_type => "CLOB", :data_length => nil)).to eq [OCI8::CLOB, nil]
      end

      it "should translate PL/SQL NUMBER to Ruby OraNumber" do
        expect(@conn.plsql_to_ruby_data_type(:data_type => "NUMBER", :data_length => 15)).to eq [OraNumber, nil]
      end

      it "should translate PL/SQL DATE to Ruby DateTime" do
        expect(@conn.plsql_to_ruby_data_type(:data_type => "DATE", :data_length => nil)).to eq [DateTime, nil]
      end

      it "should translate PL/SQL TIMESTAMP to Ruby Time" do
        expect(@conn.plsql_to_ruby_data_type(:data_type => "TIMESTAMP", :data_length => nil)).to eq [Time, nil]
      end

      it "should not translate Ruby Fixnum when OraNumber type specified" do
        expect(@conn.ruby_value_to_ora_value(100, OraNumber)).to eql(100)
      end

      it "should translate Ruby Bignum value to OraNumber when OraNumber type specified" do
        ora_number = @conn.ruby_value_to_ora_value(12345678901234567890, OraNumber)
        expect(ora_number.class).to eq OraNumber
        expect(ora_number.to_s).to eq "12345678901234567890"
        # OraNumber has more numeric comparison methods in ruby-oci8 2.0
        expect(ora_number).to eq OraNumber.new("12345678901234567890") if OCI8::VERSION >= '2.0.0'
      end

      it "should translate Ruby String value to OCI8::CLOB when OCI8::CLOB type specified" do
        large_text = "x" * 100_000
        ora_value = @conn.ruby_value_to_ora_value(large_text, OCI8::CLOB)
        expect(ora_value.class).to eq OCI8::CLOB
        expect(ora_value.size).to eq 100_000
        ora_value.rewind
        expect(ora_value.read).to eq large_text
      end

      it "should translate Oracle OraNumber integer value to Fixnum" do
        expect(@conn.ora_value_to_ruby_value(OraNumber.new(100))).to eql(100)
      end

      it "should translate Oracle OraNumber float value to BigDecimal" do
        expect(@conn.ora_value_to_ruby_value(OraNumber.new(100.11))).to eql(BigDecimal("100.11"))
      end

      # ruby-oci8 2.0 returns DATE as Time or DateTime
      if OCI8::VERSION < '2.0.0'
        it "should translate Oracle OraDate value to Time" do
          now = OraDate.now
          expect(@conn.ora_value_to_ruby_value(now)).to eql(now.to_time)
        end
      end

      it "should translate Oracle CLOB value to String" do
        large_text = "x" * 100_000
        clob = OCI8::CLOB.new(@raw_conn, large_text)
        expect(@conn.ora_value_to_ruby_value(clob)).to eq large_text
      end

    end

  # JRuby
  else

    describe "JDBC data type conversions" do
      it "should translate PL/SQL VARCHAR to Ruby String" do
        expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR", :data_length => 100)).to eq [String, 100]
        expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR", :data_length => nil)).to eq [String, 32767]
      end
      it "should translate PL/SQL VARCHAR2 to Ruby String" do
        expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR2", :data_length => 100)).to eq [String, 100]
        expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR2", :data_length => nil)).to eq [String, 32767]
      end

      it "should translate PL/SQL NUMBER to Ruby BigDecimal" do
        expect(@conn.plsql_to_ruby_data_type(:data_type => "NUMBER", :data_length => 15)).to eq [BigDecimal, nil]
      end

      it "should translate PL/SQL DATE to Ruby DateTime" do
        expect(@conn.plsql_to_ruby_data_type(:data_type => "DATE", :data_length => nil)).to eq [DateTime, nil]
      end

      it "should translate PL/SQL TIMESTAMP to Ruby Time" do
        expect(@conn.plsql_to_ruby_data_type(:data_type => "TIMESTAMP", :data_length => nil)).to eq [Time, nil]
      end

      it "should not translate Ruby Fixnum when BigDecimal type specified" do
        expect(@conn.ruby_value_to_ora_value(100, BigDecimal)).to eq java.math.BigDecimal.new(100)
      end

      it "should translate Ruby String to string value" do
        expect(@conn.ruby_value_to_ora_value(1.1, String)).to eq '1.1'
      end

      it "should translate Ruby Bignum value to BigDecimal when BigDecimal type specified" do
        big_decimal = @conn.ruby_value_to_ora_value(12345678901234567890, BigDecimal)
        expect(big_decimal).to eq java.math.BigDecimal.new("12345678901234567890")
      end

      it "should translate Ruby String value to Java::OracleSql::CLOB when Java::OracleSql::CLOB type specified" do
        large_text = "x" * 100_000
        ora_value = @conn.ruby_value_to_ora_value(large_text, Java::OracleSql::CLOB)
        expect(ora_value.class).to eq Java::OracleSql::CLOB
        expect(ora_value.length).to eq 100_000
        expect(ora_value.getSubString(1, ora_value.length)).to eq large_text
        ora_value.freeTemporary
      end

      it "should translate Ruby nil value to nil when Java::OracleSql::CLOB type specified" do
        ora_value = @conn.ruby_value_to_ora_value(nil, Java::OracleSql::CLOB)
        expect(ora_value).to be_nil
      end

      it "should translate Oracle BigDecimal integer value to Fixnum" do
        expect(@conn.ora_value_to_ruby_value(BigDecimal("100"))).to eql(100)
      end

      it "should translate Oracle BigDecimal float value to BigDecimal" do
        expect(@conn.ora_value_to_ruby_value(BigDecimal("100.11"))).to eql(BigDecimal("100.11"))
      end

      it "should translate Oracle CLOB value to String" do
        large_text = "āčē" * 100_000
        clob = @conn.ruby_value_to_ora_value(large_text, Java::OracleSql::CLOB)
        expect(@conn.ora_value_to_ruby_value(clob)).to eq large_text
        clob.freeTemporary
      end

      it "should translate empty Oracle CLOB value to nil" do
        clob = @conn.ruby_value_to_ora_value(nil, Java::OracleSql::CLOB)
        expect(@conn.ora_value_to_ruby_value(clob)).to be_nil
      end

    end

  end

  describe "SQL SELECT statements" do

    it "should execute SQL statement and return first result" do
      @now = Time.local(2008,05,31,23,22,11)
      expect(@conn.select_first("SELECT 'abc',123,123.456,
        TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
        FROM dual")).to eq ["abc",123,123.456,@now]
    end

    it "should execute SQL statement and return first result as hash" do
      @now = Time.local(2008,05,31,23,22,11)
      expect(@conn.select_hash_first("SELECT 'abc' a, 123 b, 123.456 c,
        TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}', 'YYYY-MM-DD HH24:MI:SS') d
        FROM dual")).to eq({:a => "abc", :b => 123, :c => 123.456, :d => @now})
    end

    it "should execute SQL statement with bind parameters and return first result" do
      @today = Date.parse("2008-05-31")
      @now = Time.local(2008,05,31,23,22,11)
      expect(@conn.select_first("SELECT :1,:2,:3,:4,:5 FROM dual",
        'abc',123,123.456,@now,@today)).to eq ["abc",123,123.456,@now,Time.parse(@today.to_s)]
    end

    it "should execute SQL statement with NULL values and return first result" do
      @now = Time.local(2008,05,31,23,22,11)
      expect(@conn.select_first("SELECT NULL,123,123.456,
        TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
        FROM dual")).to eq [nil,123,123.456,@now]
    end

    if defined?(JRuby)

      it "should execute SQL statement with NULL values as bind parameters and return first result" do
        @today = Date.parse("2008-05-31")
        @now = Time.local(2008,05,31,23,22,11)
        expect(@conn.select_first("SELECT :1,:2,:3,:4,:5 FROM dual",
          nil,123,123.456,@now,@today)).to eq [nil,123,123.456,@now,Time.parse(@today.to_s)]
      end

    end

    it "should execute SQL statement and return all results" do
      @now = Time.local(2008,05,31,23,22,11)
      expect(@conn.select_all("SELECT 'abc',123,123.456,
          TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
          FROM dual
          UNION ALL SELECT 'abc',123,123.456,
          TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
          FROM dual")).to eq [["abc",123,123.456,@now],["abc",123,123.456,@now]]
    end

    it "should execute SQL statement and return all results as hash" do
      @now = Time.local(2008,05,31,23,22,11)
      expect(@conn.select_hash_all("SELECT 'abc' a, 123 b, 123.456 c,
          TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') d
          FROM dual
          UNION ALL SELECT 'def' a, 123 b, 123.456 c,
          TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') d
          FROM dual")).to eq [{:a=>"abc",:b=>123,:c=>123.456,:d=>@now},{:a=>"def",:b=>123,:c=>123.456,:d=>@now}]
    end

    it "should execute SQL statement with bind parameters and return all results" do
      @now = Time.local(2008,05,31,23,22,11)
      expect(@conn.select_all("SELECT :1,:2,:3,:4 FROM dual UNION ALL SELECT :1,:2,:3,:4 FROM dual",
        'abc',123,123.456,@now,'abc',123,123.456,@now)).to eq [["abc",123,123.456,@now],["abc",123,123.456,@now]]
    end

    it "should execute SQL statement and yield all results in block" do
      @now = Time.local(2008,05,31,23,22,11)
      expect(@conn.select_all("SELECT 'abc',123,123.456,
          TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
          FROM dual
          UNION ALL SELECT 'abc',123,123.456,
          TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
          FROM dual") do |r|
        expect(r).to eq ["abc",123,123.456,@now]
      end).to eq 2
    end

    it "should execute SQL statement with bind parameters and yield all results in block" do
      @now = Time.local(2008,05,31,23,22,11)
      expect(@conn.select_all("SELECT :1,:2,:3,:4 FROM dual UNION ALL SELECT :1,:2,:3,:4 FROM dual",
        'abc',123,123.456,@now,'abc',123,123.456,@now) do |r|
        expect(r).to eq ["abc",123,123.456,@now]
      end).to eq 2
    end

  end

  describe "PL/SQL procedures" do
    before(:all) do
      @random = rand(1000)
      @now = Time.local(2008,05,31,23,22,11)
      sql = <<-SQL
        CREATE OR REPLACE FUNCTION test_add_random (p_number NUMBER, p_varchar IN OUT VARCHAR2, p_date IN OUT DATE)
          RETURN NUMBER
        IS
        BEGIN
          RETURN p_number + #{@random};
        END test_add_random;
      SQL
      expect(@conn.exec(sql)).to be true
    end

    after(:all) do
      @conn.exec "DROP FUNCTION test_add_random"
    end

    it "should parse PL/SQL procedure call and bind parameters and exec and get bind parameter value" do
      sql = <<-SQL
        BEGIN
          :result := test_add_random (:p_number, :p_varchar, :p_date);
        END;
      SQL
      cursor = @conn.parse(sql)
      cursor.bind_param(":result", nil, :data_type => 'NUMBER', :in_out => 'OUT')
      cursor.bind_param(":p_number", 100, :data_type => 'NUMBER', :in_out => 'IN')
      cursor.bind_param(":p_varchar", "abc", :data_type => 'VARCHAR2', :in_out => 'IN/OUT')
      cursor.bind_param(":p_date", @now, :data_type => 'DATE', :in_out => 'IN/OUT')
      cursor.exec
      expect(cursor[":result"]).to eq @random + 100
      expect(cursor[":p_varchar"]).to eq "abc"
      expect(cursor[":p_date"]).to eq @now
      expect(cursor.close).to be_nil
    end

  end

  describe "commit and rollback" do
    before(:all) do
      expect(@conn.exec("CREATE TABLE test_commit (dummy VARCHAR2(100))")).to be true
      @conn.autocommit = false
      expect(@conn).not_to be_autocommit
    end

    after(:all) do
      @conn.exec "DROP TABLE test_commit"
    end

    after(:each) do
      @conn.exec "DELETE FROM test_commit"
      @conn.commit
    end

    it "should do commit" do
      @conn.exec("INSERT INTO test_commit VALUES ('test')")
      @conn.commit
      expect(@conn.select_first("SELECT COUNT(*) FROM test_commit")[0]).to eq 1
    end

    it "should do rollback" do
      @conn.exec("INSERT INTO test_commit VALUES ('test')")
      @conn.rollback
      expect(@conn.select_first("SELECT COUNT(*) FROM test_commit")[0]).to eq 0
    end

    it "should do commit and rollback should not undo commited transaction" do
      @conn.exec("INSERT INTO test_commit VALUES ('test')")
      @conn.commit
      @conn.rollback
      expect(@conn.select_first("SELECT COUNT(*) FROM test_commit")[0]).to eq 1
    end

  end

  describe "prefetch rows" do
    after(:each) do
      @conn.prefetch_rows = 1 # set back to default
    end

    it "should set prefetch rows for connection" do
      sql = "SELECT 1 FROM dual UNION ALL SELECT 1/0 FROM dual"
      @conn.prefetch_rows = 2
      expect {
        @conn.cursor_from_query(sql)
      }.to raise_error(/divisor is equal to zero/)
      @conn.prefetch_rows = 1
      expect {
        @conn.cursor_from_query(sql)
      }.not_to raise_error
    end

    it "should fetch just one row when using select_first" do
      sql = "SELECT 1 FROM dual UNION ALL SELECT 1/0 FROM dual"
      @conn.prefetch_rows = 2
      expect {
        @conn.select_first(sql)
      }.not_to raise_error
    end

  end

  describe "describe synonym" do
    before(:all) do
      @conn.exec "CREATE SYNONYM hr.synonym_for_dual FOR sys.dual"
    end

    after(:all) do
      @conn.exec "DROP SYNONYM hr.synonym_for_dual"
    end

    it "should describe local synonym" do
      expect(@conn.describe_synonym('HR','SYNONYM_FOR_DUAL')).to eq ['SYS', 'DUAL']
      expect(@conn.describe_synonym('hr','synonym_for_dual')).to eq ['SYS', 'DUAL']
      expect(@conn.describe_synonym(:hr,:synonym_for_dual)).to eq ['SYS', 'DUAL']
    end

    it "should return nil on non-existing synonym" do
      expect(@conn.describe_synonym('HR','SYNONYM_FOR_XXX')).to be_nil
      expect(@conn.describe_synonym('hr','synonym_for_xxx')).to be_nil
      expect(@conn.describe_synonym(:hr,:synonym_for_xxx)).to be_nil
    end

    it "should describe public synonym" do
      expect(@conn.describe_synonym('PUBLIC','DUAL')).to eq ['SYS', 'DUAL']
      expect(@conn.describe_synonym('PUBLIC','dual')).to eq ['SYS', 'DUAL']
      expect(@conn.describe_synonym('PUBLIC',:dual)).to eq ['SYS', 'DUAL']
    end

  end

  describe "session information" do
    it "should get database version" do
      # using Oracle version 10.2.0.4 for unit tests
      expect(@conn.database_version).to eq DATABASE_VERSION.split('.').map{|n| n.to_i}
    end

    it "should get session ID" do
      expect(@conn.session_id).to eq @conn.select_first("SELECT USERENV('SESSIONID') FROM dual")[0].to_i
    end
  end

  describe "drop ruby temporary tables" do
    after(:all) do
      @conn.drop_all_ruby_temporary_tables
    end

    it "should drop all ruby temporary tables" do
      tmp_table = "ruby_111_222_333"
      @conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))"
      expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error
      @conn.drop_all_ruby_temporary_tables
      expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.to raise_error(/table or view does not exist/)
    end

    it "should drop current session ruby temporary tables" do
      tmp_table = "ruby_#{@conn.session_id}_222_333"
      @conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))"
      expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error
      @conn.drop_session_ruby_temporary_tables
      expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.to raise_error(/table or view does not exist/)
    end

    it "should not drop other session ruby temporary tables" do
      tmp_table = "ruby_#{@conn.session_id+1}_222_333"
      @conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))"
      expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error
      @conn.drop_session_ruby_temporary_tables
      expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error
    end

  end

  describe "logoff" do
    before(:each) do
      # restore connection before each test
      reconnect_connection
    end

    after(:all) do
      @conn.exec "DROP TABLE test_dummy_table" rescue nil
    end

    def reconnect_connection
      @raw_conn = get_connection
      @conn = PLSQL::Connection.create( @raw_conn )
    end

    it "should drop current session ruby temporary tables" do
      tmp_table = "ruby_#{@conn.session_id}_222_333"
      @conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))"
      expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error
      @conn.logoff
      reconnect_connection
      expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.to raise_error(/table or view does not exist/)
    end

    it "should rollback any uncommited transactions" do
      tmp_table = "ruby_#{@conn.session_id}_222_333"
      old_autocommit = @conn.autocommit?
      @conn.autocommit = false
      @conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))"
      @conn.exec "CREATE TABLE test_dummy_table (dummy CHAR(1))"
      @conn.exec "INSERT INTO test_dummy_table VALUES ('1')"
      # logoff will drop ruby temporary tables, it should do rollback before drop table
      @conn.logoff
      reconnect_connection
      expect(@conn.select_first("SELECT * FROM test_dummy_table")).to eq nil
      @conn.autocommit = old_autocommit
    end

  end

end


text:
import { QueryBuilderOptions, Block, cls } from 'squel'
import CriteriaBlock from './blocks/CriteriaBlock'
import { Queries } from '../manager/parts'
import { UpdateQuery as $UpdateQuery, OkPacket } from '../types'

export class UpdateQuery extends cls.QueryBuilder {
  private _manager: Queries<any, any> //eslint-disable-line @typescript-eslint/no-explicit-any
  constructor(
    manager: Queries<any, any>, //eslint-disable-line @typescript-eslint/no-explicit-any
    options: QueryBuilderOptions,
    blocks: Block[] | undefined,
  ) {
    const newBlocks = blocks || [
      new cls.StringBlock(options, 'UPDATE'),
      new cls.UpdateTableBlock(options),
      new cls.SetFieldBlock(options),
      new CriteriaBlock(options),
      new cls.OrderByBlock(options),
      new cls.LimitBlock(options),
    ]

    super(options, newBlocks)

    this._manager = manager
  }

  execute(): Promise<OkPacket> {
    // @ts-ignore
    return this._manager.execute(this).then(([result]) => result)
  }
}

export default function update(
  manager: Queries<any, any>, //eslint-disable-line @typescript-eslint/no-explicit-any
  options: QueryBuilderOptions | null = {},
): $UpdateQuery {
  // @ts-ignore
  return new UpdateQuery(manager, options)
}

redpajama_set_name: RedPajamaGithub


text:
from django.apps import AppConfig

class AppConfig(AppConfig):
    name = '.'.join(__name__.split('.')[:-1])
    label = "layout_page"
    verbose_name = 'Page'


text:
class AddBandcampUrlToProject < ActiveRecord::Migration[5.0]
  def change
    add_column :projects, :bandcamp_url, :string
  end
end


text:
layout: post
title: Use of relative pronouns
categories:
- Learning
---

Relative pronouns are: that, who, whom, whose, which, where, when, and why. This [table (OWL Purdue)](http://owl.english.purdue.edu/owl/resource/645/01/) summarises the usage of these pronouns...

![](/img/relative_pronoun_usage.jpg "relative_pronoun_usage")


text:
package org.apache.accumulo.test.functional;

import static org.apache.accumulo.fate.util.UtilWaitThread.sleepUninterruptibly;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;

import java.util.Collections;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;

import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.BatchScanner;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.RootTable;
import org.apache.accumulo.core.metadata.schema.MetadataSchema;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.apache.accumulo.miniclusterImpl.MiniAccumuloConfigImpl;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.junit.Test;

import com.google.common.collect.Iterators;

public class MetadataIT extends AccumuloClusterHarness {

  @Override
  public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
    cfg.setNumTservers(1);
  }

  @Override
  public int defaultTimeoutSeconds() {
    return 2 * 60;
  }

  @Test
  public void testFlushAndCompact() throws Exception {
    try (AccumuloClient c = Accumulo.newClient().from(getClientProps()).build()) {
      String[] tableNames = getUniqueNames(2);

      // create a table to write some data to metadata table
      c.tableOperations().create(tableNames[0]);

      try (Scanner rootScanner = c.createScanner(RootTable.NAME, Authorizations.EMPTY)) {
        rootScanner.setRange(MetadataSchema.TabletsSection.getRange());
        rootScanner.fetchColumnFamily(MetadataSchema.TabletsSection.DataFileColumnFamily.NAME);

        Set<String> files1 = new HashSet<>();
        for (Entry<Key,Value> entry : rootScanner)
          files1.add(entry.getKey().getColumnQualifier().toString());

        c.tableOperations().create(tableNames[1]);
        c.tableOperations().flush(MetadataTable.NAME, null, null, true);

        Set<String> files2 = new HashSet<>();
        for (Entry<Key,Value> entry : rootScanner)
          files2.add(entry.getKey().getColumnQualifier().toString());

        // flush of metadata table should change file set in root table
        assertTrue(files2.size() > 0);
        assertNotEquals(files1, files2);

        c.tableOperations().compact(MetadataTable.NAME, null, null, false, true);

        Set<String> files3 = new HashSet<>();
        for (Entry<Key,Value> entry : rootScanner)
          files3.add(entry.getKey().getColumnQualifier().toString());

        // compaction of metadata table should change file set in root table
        assertNotEquals(files2, files3);
      }
    }
  }

  @Test
  public void mergeMeta() throws Exception {
    try (AccumuloClient c = Accumulo.newClient().from(getClientProps()).build()) {
      String[] names = getUniqueNames(5);
      SortedSet<Text> splits = new TreeSet<>();
      for (String id : "1 2 3 4 5".split(" ")) {
        splits.add(new Text(id));
      }
      c.tableOperations().addSplits(MetadataTable.NAME, splits);
      for (String tableName : names) {
        c.tableOperations().create(tableName);
      }
      c.tableOperations().merge(MetadataTable.NAME, null, null);
      try (Scanner s = c.createScanner(RootTable.NAME, Authorizations.EMPTY)) {
        s.setRange(MetadataSchema.DeletesSection.getRange());
        while (Iterators.size(s.iterator()) == 0) {
          sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
        }
        assertEquals(0, c.tableOperations().listSplits(MetadataTable.NAME).size());
      }
    }
  }

  @Test
  public void batchScanTest() throws Exception {
    try (AccumuloClient c = Accumulo.newClient().from(getClientProps()).build()) {
      String tableName = getUniqueNames(1)[0];
      c.tableOperations().create(tableName);

      // batch scan regular metadata table
      int count = 0;
      try (BatchScanner s = c.createBatchScanner(MetadataTable.NAME)) {
        s.setRanges(Collections.singleton(new Range()));
        for (Entry<Key,Value> e : s) {
          if (e != null)
            count++;
        }
      }

      assertTrue(count > 0);

      // batch scan root metadata table
      try (BatchScanner s = c.createBatchScanner(RootTable.NAME)) {
        s.setRanges(Collections.singleton(new Range()));
        count = 0;
        for (Entry<Key,Value> e : s) {
          if (e != null)
            count++;
        }
        assertTrue(count > 0);
      }
    }
  }
}


text:
//
//  UIDevice+Hardware.h
//

@import UIKit;

/*!
 * Category displays detailed information about current device hardware
 */
@interface UIDevice (Hardware)

/**
 *  Returns current battery level of the device
 *
 *  @return battery level
 */
- (float)hay_batteryLevel;

//
// CPU Related
//

/*!
 * Number of CPU cores
 */
- (NSUInteger)hay_cpuCount;

/*!
 * Number of active CPU cores
 */
- (NSUInteger)hay_cpuActiveCount;

- (NSUInteger)hay_cpuPhysicalCount;

- (NSUInteger)hay_cpuPhysicalMaximumCount;

- (NSUInteger)hay_cpuLogicalCount;

- (NSUInteger)hay_cpuLogicalMaximumCount;

- (NSUInteger)hay_cpuFrequency;

- (NSUInteger)hay_cpuMaximumFrequency;

- (NSUInteger)hay_cpuMinimumFrequency;

- (NSString *)hay_cpuType;

- (NSString *)hay_cpuSubType;

- (NSString *)hay_cpuArchitectures;

//
// Memory Related
//

- (unsigned long long)hay_memoryMarketingSize;

/**
 *  Total RAM size
 *
 *  @return Total RAM size
 */
- (unsigned long long)hay_memoryPhysicalSize;

//
// Disk Space Related
//

- (unsigned long long)hay_diskMarketingSpace;

- (unsigned long long)hay_diskTotalSpace;

- (unsigned long long)hay_diskFreeSpace;

@end


text:
package kafka.api;

import com.google.common.collect.Lists;
import kafka.cluster.Broker;
import kafka.cluster.Brokers;
import kafka.utils.*;

import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class TopicMetadataResponse extends RequestOrResponse {
    public static TopicMetadataResponse readFrom(final ByteBuffer buffer) {
        int correlationId = buffer.getInt();
        int brokerCount = buffer.getInt();
        List<Broker> brokers = Utils.flatList(0, brokerCount, new Function1<Integer, Broker>() {
            @Override
            public Broker apply(Integer index) {
                return Brokers.readFrom(buffer);
            }
        });

        final Map<Integer, Broker> brokerMap = Utils.map(brokers, new Function1<Broker, Tuple2<Integer, Broker>>() {
            @Override
            public Tuple2<Integer, Broker> apply(Broker broker) {
                return Tuple2.make(broker.id, broker);
            }
        });
        int topicCount = buffer.getInt();
        List<TopicMetadata> topicsMetadata = Utils.flatList(0, topicCount, new Function1<Integer, TopicMetadata>() {
            @Override
            public TopicMetadata apply(Integer arg) {
                return TopicMetadata.readFrom(buffer, brokerMap);
            }
        });

        return new TopicMetadataResponse(topicsMetadata, correlationId);
    }

    public List<TopicMetadata> topicsMetadata;

    public TopicMetadataResponse(List<TopicMetadata> topicsMetadata, int correlationId) {
        super(correlationId);

        this.topicsMetadata = topicsMetadata;
    }

    @Override
    public int sizeInBytes() {
        Collection<Broker> brokers = extractBrokers(topicsMetadata).values();

        return 4 + 4 + Utils.foldLeft(brokers, 0, new Function2<Integer, Broker, Integer>() {
            @Override
            public Integer apply(Integer arg1, Broker _) {
                return arg1 + _.sizeInBytes();
            }
        }) + 4 + Utils.foldLeft(topicsMetadata, 0, new Function2<Integer, TopicMetadata, Integer>() {
            @Override
            public Integer apply(Integer arg1, TopicMetadata _) {
                return arg1 + _.sizeInBytes();
            }
        });
    }

    @Override
    public void writeTo(final ByteBuffer buffer) {
        buffer.putInt(correlationId);
        /* brokers */
        Collection<Broker> brokers = extractBrokers(topicsMetadata).values();
        buffer.putInt(brokers.size());
        Utils.foreach(brokers, new Callable1<Broker>() {
            @Override
            public void apply(Broker _) {
                _.writeTo(buffer);
            }
        });
        /* topic metadata */
        buffer.putInt(topicsMetadata.size());

        Utils.foreach(topicsMetadata, new Callable1<TopicMetadata>() {
            @Override
            public void apply(TopicMetadata _) {
                _.writeTo(buffer);
            }
        });
    }

    private Map<Integer, Broker> extractBrokers(List<TopicMetadata> topicMetadatas) {
        List<PartitionMetadata> parts = Utils.mapLists(topicsMetadata, new Function1<TopicMetadata, Collection<PartitionMetadata>>() {
            @Override
            public Collection<PartitionMetadata> apply(TopicMetadata arg) {
                return arg.partitionsMetadata;
            }
        });

        List<Broker> brokers = Utils.mapLists(parts, new Function1<PartitionMetadata, Collection<Broker>>() {
            @Override
            public Collection<Broker> apply(PartitionMetadata _) {
                List<Broker> lst = Lists.newArrayList();
                lst.addAll(_.replicas);

                if (_.leader != null)
                    lst.add(_.leader);

                return lst;
            }
        });

        return Utils.map(brokers, new Function1<Broker, Tuple2<Integer, Broker>>() {
            @Override
            public Tuple2<Integer, Broker> apply(Broker b) {
                return Tuple2.make(b.id, b);
            }
        });
    }
}


text:
<?php
include("database/db_conection2.php"); //Connects to DB.
$mysql_table = "events";

if (isset($_POST['event_id'])) {
	$event_id = $_POST['event_id'];

	$query =
		"SELECT poster_url FROM ".$mysql_table." WHERE event_id=".mysqli_real_escape_string($dbcon, $event_id);

	echo $query."
";

	if ($query_exec = mysqli_query($dbcon, $query)) {
		if ($query_row = mysqli_fetch_array($query_exec)){
			echo "fetching poster url: ";
			$event_poster_url 	= $query_row['poster_url'];
		}
	}

	if ((!empty($event_poster_url))&&(!unlink($event_poster_url)))
  	{
  		echo ("Error deleting $event_poster_url");
  	} else {
  		echo ("Deleted $event_poster_url");
  	}

	$query = "DELETE FROM `".$mysql_table."` WHERE `".$mysql_table."`.`event_id` = ".mysqli_real_escape_string($dbcon, $event_id);
	echo $query."

";

	if ($query_exec = mysqli_query($dbcon, $query)) {
			echo 'Event successfully deleted.
';
		} else {
			echo 'Unable to delete event from DB table.';
		}

} else {
	echo exit("Couldn't fetch query. Check that event ID is valid.");
}

	header("refresh:0; url=./eventsmanager.php");

?>


text:
// .NAME vtkVolumePicker - ray-cast picker enhanced for volumes
// .SECTION Description
// vtkVolumePicker is a subclass of vtkCellPicker.  It has one
// advantage over vtkCellPicker for volumes: it will be able to
// correctly perform picking when CroppingPlanes are present.  This
// isn't possible for vtkCellPicker since it doesn't link to
// the VolumeRendering classes and hence cannot access information
// about the CroppingPlanes.
//
// .SECTION See Also
// vtkPicker vtkPointPicker vtkCellPicker
//
// .SECTION Thanks
// This class was contributed to VTK by David Gobbi on behalf of Atamai Inc.

#ifndef vtkVolumePicker_h
#define vtkVolumePicker_h

#include "vtkRenderingVolumeModule.h" // For export macro
#include "vtkCellPicker.h"

class VTKRENDERINGVOLUME_EXPORT vtkVolumePicker : public vtkCellPicker
{
public:
  static vtkVolumePicker *New();
  vtkTypeMacro(vtkVolumePicker, vtkCellPicker);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Set whether to pick the cropping planes of props that have them.
  // If this is set, then the pick will be done on the cropping planes
  // rather than on the data. The GetCroppingPlaneId() method will return
  // the index of the cropping plane of the volume that was picked.  This
  // setting is only relevant to the picking of volumes.
  vtkSetMacro(PickCroppingPlanes, int);
  vtkBooleanMacro(PickCroppingPlanes, int);
  vtkGetMacro(PickCroppingPlanes, int);

  // Description:
  // Get the index of the cropping plane that the pick ray passed
  // through on its way to the prop. This will be set regardless
  // of whether PickCroppingPlanes is on.  The crop planes are ordered
  // as follows: xmin, xmax, ymin, ymax, zmin, zmax.  If the volume is
  // not cropped, the value will bet set to -1.
  vtkGetMacro(CroppingPlaneId, int);

protected:
  vtkVolumePicker();
  ~vtkVolumePicker();

  virtual void ResetPickInfo();

  virtual double IntersectVolumeWithLine(const double p1[3],
                                         const double p2[3],
                                         double t1, double t2,
                                         vtkProp3D *prop,
                                         vtkAbstractVolumeMapper *mapper);

  static int ClipLineWithCroppingRegion(const double bounds[6],
                                        const int extent[6], int flags,
                                        const double x1[3], const double x2[3],
                                        double t1, double t2,
                                        int &extentPlaneId, int &numSegments,
                                        double *t1List, double *t2List,
                                        double *s1List, int *planeIdList);

  int PickCroppingPlanes;
  int CroppingPlaneId;

private:
  vtkVolumePicker(const vtkVolumePicker&);  // Not implemented.
  void operator=(const vtkVolumePicker&);  // Not implemented.
};

#endif


text:
package org.apache.wicket.markup;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;

/**
 */
public class MarkupInheritanceBase_2 extends WebPage
{
	private static final long serialVersionUID = 1L;

	/**
	 * Construct.
	 *
	 */
	public MarkupInheritanceBase_2()
	{
		add(new Label("label1", "base label 1"));
		add(new Label("label2", "base label 2"));
	}
}


text:
from .base import Info
from .postproc import SplineFilter
from .dti import DTIRecon, DTITracker
from .odf import HARDIMat, ODFRecon, ODFTracker


text:
layout: page
title: Kelley Research Award Ceremony
date: 2016-05-24
author: Larry Gutierrez
tags: weekly links, java
status: published
summary: Proin dignissim eu est vitae laoreet.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 11/07/2017
  endDate: 11/08/2017
  ctyhocn: ACYVIHX
  groupCode: KRAC
published: true
---
Cras sed augue in lectus luctus ultrices. Cras facilisis viverra purus eget scelerisque. Vestibulum suscipit eros vitae sodales scelerisque. Quisque volutpat tincidunt placerat. Integer efficitur ante et neque tempor fringilla. Phasellus sollicitudin ipsum ac orci suscipit, non pellentesque velit consequat. In quis lacus ultricies, viverra metus vitae, lacinia ex.
Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec ullamcorper faucibus nibh, at pellentesque orci mattis id. Suspendisse potenti. Suspendisse volutpat nec nunc eu interdum. Phasellus vitae pharetra erat, ut posuere nibh. Phasellus fermentum aliquet magna, faucibus facilisis tellus ultricies eget. Mauris molestie mi turpis, nec vestibulum dui hendrerit id. Aenean blandit mi metus, sit amet porttitor velit gravida non. Suspendisse congue, erat nec pulvinar posuere, ipsum nisi porttitor sapien, non mollis mauris erat eget sem.

1 Pellentesque sit amet nisi elementum, vehicula nulla scelerisque, pulvinar purus
1 Duis feugiat tortor eget lectus consequat sagittis et a nulla
1 Vestibulum sed mi et metus vehicula luctus in quis orci
1 Mauris id velit vel lacus faucibus commodo et non lectus.

Nullam convallis laoreet mi, sit amet mollis quam hendrerit nec. Proin pharetra ipsum et urna tincidunt hendrerit. Aliquam ut ullamcorper ipsum. Sed vehicula dolor felis, eu blandit dui condimentum et. Integer et pharetra est. In ullamcorper metus erat, et interdum mauris lobortis eu. Nam vulputate pretium molestie. Praesent ac nunc vel orci varius dictum. Phasellus consectetur rutrum augue, nec scelerisque dolor mattis sit amet. Duis fermentum turpis in lectus ultrices finibus. Nam posuere nulla nec sem dignissim ullamcorper. Fusce sagittis malesuada massa sit amet scelerisque. Vivamus fringilla massa leo, in auctor mauris venenatis in. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin mattis tristique placerat.


text:
const Server   = require('./server/Server');
const instance = new Server();

instance
    .build()
    .then(() => instance.listen())
    .then(() => instance.open())
    .catch(console.log);


text:
"""
Controller that manages the interface between the driver and the messaging
service.

This module defines a Controller class that is responsible for performing
messaging-related operations (Tasks) requested by the driver, and for managing
the connection to the messaging service.  The Controller creates a background
thread which performs all messaging operations and socket I/O.  The
Controller's messaging logic is executed in the background thread via lambda
functions scheduled by the Controller.
"""

import abc
import logging
import threading
import uuid

from oslo_config import cfg
import proton
import pyngus
from six import moves

from oslo_messaging._drivers.protocols.amqp import eventloop
from oslo_messaging._drivers.protocols.amqp import opts
from oslo_messaging._i18n import _LE, _LI, _LW
from oslo_messaging import exceptions
from oslo_messaging import transport

LOG = logging.getLogger(__name__)

class Task(object):
    """Perform a messaging operation via the Controller."""
    @abc.abstractmethod
    def execute(self, controller):
        """This method will be run on the eventloop thread."""

class Replies(pyngus.ReceiverEventHandler):
    """This is the receiving link for all reply messages.  Messages are routed
    to the proper Listener's incoming queue using the correlation-id header in
    the message.
    """
    def __init__(self, connection, on_ready):
        self._correlation = {}  # map of correlation-id to response queue
        self._ready = False
        self._on_ready = on_ready
        rname = "Consumer-%s:src=[dynamic]:tgt=replies" % uuid.uuid4().hex
        self._receiver = connection.create_receiver("replies",
                                                    event_handler=self,
                                                    name=rname)

        # capacity determines the maximum number of reply messages this link
        # can receive. As messages are received and credit is consumed, this
        # driver will 'top up' the credit back to max capacity.  This number
        # should be large enough to avoid needlessly flow-controlling the
        # replies.
        self.capacity = 100  # TODO(kgiusti) guesstimate - make configurable
        self._credit = 0
        self._receiver.open()

    def destroy(self):
        self._correlation = None
        self._receiver = None

    def ready(self):
        return self._ready

    def prepare_for_response(self, request, reply_queue):
        """Apply a unique message identifier to this request message. This will
        be used to identify messages sent in reply.  The identifier is placed
        in the 'id' field of the request message.  It is expected that the
        identifier will appear in the 'correlation-id' field of the
        corresponding response message.
        """
        request.id = uuid.uuid4().hex
        # reply is placed on reply_queue
        self._correlation[request.id] = reply_queue
        request.reply_to = self._receiver.source_address
        LOG.debug("Reply for msg id=%(id)s expected on link %(reply_to)s",
                  {'id': request.id, 'reply_to': request.reply_to})
        return request.id

    def cancel_response(self, msg_id):
        """Abort waiting for a response message.  This can be used if the
        request fails and no reply is expected.
        """
        if msg_id in self._correlation:
            del self._correlation[msg_id]

    # Pyngus ReceiverLink event callbacks:

    def receiver_active(self, receiver_link):
        """This is a Pyngus callback, invoked by Pyngus when the receiver_link
        has transitioned to the open state and is able to receive incoming
        messages.
        """
        self._ready = True
        self._update_credit()
        self._on_ready()
        LOG.debug("Replies expected on link %s",
                  self._receiver.source_address)

    def receiver_remote_closed(self, receiver, pn_condition):
        """This is a Pyngus callback, invoked by Pyngus when the peer of this
        receiver link has initiated closing the connection.
        """
        # TODO(kgiusti) Unclear if this error will ever occur (as opposed to
        # the Connection failing instead).  Log for now, possibly implement a
        # recovery strategy if necessary.
        LOG.error(_LE("Reply subscription closed by peer: %s"),
                  (pn_condition or "no error given"))

    def message_received(self, receiver, message, handle):
        """This is a Pyngus callback, invoked by Pyngus when a new message
        arrives on this receiver link from the peer.
        """
        self._credit = self._credit - 1
        self._update_credit()

        key = message.correlation_id
        if key in self._correlation:
            LOG.debug("Received response for msg id=%s", key)
            result = {"status": "OK",
                      "response": message}
            self._correlation[key].put(result)
            # cleanup (only need one response per request)
            del self._correlation[key]
            receiver.message_accepted(handle)
        else:
            LOG.warning(_LW("Can't find receiver for response msg id=%s, "
                            "dropping!"), key)
            receiver.message_modified(handle, True, True, None)

    def _update_credit(self):
        # ensure we have enough credit
        if self._credit < self.capacity / 2:
            self._receiver.add_capacity(self.capacity - self._credit)
            self._credit = self.capacity

class Server(pyngus.ReceiverEventHandler):
    """A group of links that receive messages from a set of addresses derived
    from a given target.  Messages arriving on the links are placed on the
    'incoming' queue.
    """
    def __init__(self, addresses, incoming):
        self._incoming = incoming
        self._addresses = addresses
        self._capacity = 500   # credit per link
        self._receivers = None

    def attach(self, connection):
        """Create receiver links over the given connection for all the
        configured addresses.
        """
        self._receivers = []
        for a in self._addresses:
            props = {"snd-settle-mode": "settled"}
            rname = "Consumer-%s:src=%s:tgt=%s" % (uuid.uuid4().hex, a, a)
            r = connection.create_receiver(source_address=a,
                                           target_address=a,
                                           event_handler=self,
                                           name=rname,
                                           properties=props)

            # TODO(kgiusti) Hardcoding credit here is sub-optimal.  A better
            # approach would monitor for a back-up of inbound messages to be
            # processed by the consuming application and backpressure the
            # sender based on configured thresholds.
            r.add_capacity(self._capacity)
            r.open()
            self._receivers.append(r)

    def destroy(self):
        self._receivers = None

    # Pyngus ReceiverLink event callbacks:

    def receiver_remote_closed(self, receiver, pn_condition):
        """This is a Pyngus callback, invoked by Pyngus when the peer of this
        receiver link has initiated closing the connection.
        """
        vals = {
            "addr": receiver.source_address or receiver.target_address,
            "err_msg": pn_condition or "no error given"
        }
        LOG.error(_LE("Server subscription %(addr)s closed "
                      "by peer: %(err_msg)s"), vals)

    def message_received(self, receiver, message, handle):
        """This is a Pyngus callback, invoked by Pyngus when a new message
        arrives on this receiver link from the peer.
        """
        if receiver.capacity < self._capacity / 2:
            receiver.add_capacity(self._capacity - receiver.capacity)
        self._incoming.put(message)
        LOG.debug("message received: %s", message)
        receiver.message_accepted(handle)

class Hosts(object):
    """An order list of TransportHost addresses. Connection failover
    progresses from one host to the next.  username and password come from the
    configuration and are used only if no username/password was given in the
    URL.
    """
    def __init__(self, entries=None, default_username=None,
                 default_password=None):
        if entries:
            self._entries = entries[:]
        else:
            self._entries = [transport.TransportHost(hostname="localhost",
                                                     port=5672)]
        for entry in self._entries:
            entry.port = entry.port or 5672
            entry.username = entry.username or default_username
            entry.password = entry.password or default_password
        self._current = 0

    @property
    def current(self):
        return self._entries[self._current]

    def next(self):
        if len(self._entries) > 1:
            self._current = (self._current + 1) % len(self._entries)
        return self.current

    def __repr__(self):
        return '<Hosts ' + str(self) + '>'

    def __str__(self):
        return ", ".join(["%r" % th for th in self._entries])

class Controller(pyngus.ConnectionEventHandler):
    """Controls the connection to the AMQP messaging service.  This object is
    the 'brains' of the driver.  It maintains the logic for addressing, sending
    and receiving messages, and managing the connection.  All messaging and I/O
    work is done on the Eventloop thread, allowing the driver to run
    asynchronously from the messaging clients.
    """
    def __init__(self, hosts, default_exchange, config):
        self.processor = None
        self._socket_connection = None
        # queue of Task() objects to execute on the eventloop once the
        # connection is ready:
        self._tasks = moves.queue.Queue(maxsize=500)
        # limit the number of Task()'s to execute per call to _process_tasks().
        # This allows the eventloop main thread to return to servicing socket
        # I/O in a timely manner
        self._max_task_batch = 50
        # cache of sending links indexed by address:
        self._senders = {}
        # Servers (set of receiving links), indexed by target:
        self._servers = {}

        opt_group = cfg.OptGroup(name='oslo_messaging_amqp',
                                 title='AMQP 1.0 driver options')
        config.register_group(opt_group)
        config.register_opts(opts.amqp1_opts, group=opt_group)

        self.server_request_prefix = \
            config.oslo_messaging_amqp.server_request_prefix
        self.broadcast_prefix = config.oslo_messaging_amqp.broadcast_prefix
        self.group_request_prefix = \
            config.oslo_messaging_amqp.group_request_prefix
        self._container_name = config.oslo_messaging_amqp.container_name
        self.idle_timeout = config.oslo_messaging_amqp.idle_timeout
        self.trace_protocol = config.oslo_messaging_amqp.trace
        self.ssl_ca_file = config.oslo_messaging_amqp.ssl_ca_file
        self.ssl_cert_file = config.oslo_messaging_amqp.ssl_cert_file
        self.ssl_key_file = config.oslo_messaging_amqp.ssl_key_file
        self.ssl_key_password = config.oslo_messaging_amqp.ssl_key_password
        self.ssl_allow_insecure = \
            config.oslo_messaging_amqp.allow_insecure_clients
        self.sasl_mechanisms = config.oslo_messaging_amqp.sasl_mechanisms
        self.sasl_config_dir = config.oslo_messaging_amqp.sasl_config_dir
        self.sasl_config_name = config.oslo_messaging_amqp.sasl_config_name
        self.hosts = Hosts(hosts, config.oslo_messaging_amqp.username,
                           config.oslo_messaging_amqp.password)
        self.separator = "."
        self.fanout_qualifier = "all"
        self.default_exchange = default_exchange

        # can't handle a request until the replies link is active, as
        # we need the peer assigned address, so need to delay any
        # processing of task queue until this is done
        self._replies = None
        # Set True when the driver is shutting down
        self._closing = False
        # only schedule one outstanding reconnect attempt at a time
        self._reconnecting = False
        self._delay = 0  # seconds between retries
        # prevent queuing up multiple requests to run _process_tasks()
        self._process_tasks_scheduled = False
        self._process_tasks_lock = threading.Lock()

    def connect(self):
        """Connect to the messaging service."""
        self.processor = eventloop.Thread(self._container_name)
        self.processor.wakeup(lambda: self._do_connect())

    def add_task(self, task):
        """Add a Task for execution on processor thread."""
        self._tasks.put(task)
        self._schedule_task_processing()

    def shutdown(self, wait=True, timeout=None):
        """Shutdown the messaging service."""
        if self.processor:
            LOG.debug("Waiting for eventloop to exit")
            self.processor.shutdown(wait, timeout)
            self.processor = None
        self._tasks = None
        self._senders = None
        for server in self._servers.values():
            server.destroy()
        self._servers.clear()
        self._socket_connection = None
        if self._replies:
            self._replies.destroy()
            self._replies = None
        LOG.debug("Eventloop exited, driver shut down")

    # The remaining methods are reserved to run from the eventloop thread only!
    # They must not be invoked directly!

    # methods executed by Tasks created by the driver:

    def request(self, target, request, result_queue, reply_expected=False):
        """Send a request message to the given target and arrange for a
        result to be put on the result_queue. If reply_expected, the result
        will include the reply message (if successful).
        """
        address = self._resolve(target)
        LOG.debug("Sending request for %(target)s to %(address)s",
                  {'target': target, 'address': address})
        if reply_expected:
            msg_id = self._replies.prepare_for_response(request, result_queue)

        def _callback(link, handle, state, info):
            if state == pyngus.SenderLink.ACCEPTED:  # message received
                if not reply_expected:
                    # can wake up the sender now
                    result = {"status": "OK"}
                    result_queue.put(result)
                else:
                    # we will wake up the sender when the reply message is
                    # received.  See Replies.message_received()
                    pass
            else:  # send failed/rejected/etc
                msg = "Message send failed: remote disposition: %s, info: %s"
                exc = exceptions.MessageDeliveryFailure(msg % (state, info))
                result = {"status": "ERROR", "error": exc}
                if reply_expected:
                    # no response will be received, so cancel the correlation
                    self._replies.cancel_response(msg_id)
                result_queue.put(result)
        self._send(address, request, _callback)

    def response(self, address, response):
        """Send a response message to the client listening on 'address'.
        To prevent a misbehaving client from blocking a server indefinitely,
        the message is send asynchronously.
        """
        LOG.debug("Sending response to %s", address)
        self._send(address, response)

    def subscribe(self, target, in_queue):
        """Subscribe to messages sent to 'target', place received messages on
        'in_queue'.
        """
        addresses = [
            self._server_address(target),
            self._broadcast_address(target),
            self._group_request_address(target)
        ]
        self._subscribe(target, addresses, in_queue)

    def subscribe_notifications(self, target, in_queue):
        """Subscribe for notifications on 'target', place received messages on
        'in_queue'.
        """
        addresses = [self._group_request_address(target)]
        self._subscribe(target, addresses, in_queue)

    def _subscribe(self, target, addresses, in_queue):
        LOG.debug("Subscribing to %(target)s (%(addresses)s)",
                  {'target': target, 'addresses': addresses})
        self._servers[target] = Server(addresses, in_queue)
        self._servers[target].attach(self._socket_connection.connection)

    def _resolve(self, target):
        """Return a link address for a given target."""
        if target.server:
            return self._server_address(target)
        elif target.fanout:
            return self._broadcast_address(target)
        else:
            return self._group_request_address(target)

    def _sender(self, address):
        # if we already have a sender for that address, use it
        # else establish the sender and cache it
        if address in self._senders:
            sender = self._senders[address]
        else:
            sname = "Producer-%s:src=%s:tgt=%s" % (uuid.uuid4().hex,
                                                   address, address)
            conn = self._socket_connection.connection
            sender = conn.create_sender(source_address=address,
                                        target_address=address,
                                        name=sname)
            sender.open()
            self._senders[address] = sender
        return sender

    def _send(self, addr, message, callback=None, handle=None):
        """Send the message out the link addressed by 'addr'.  If a
        delivery_callback is given it will be invoked when the send has
        completed (whether successfully or in error).
        """
        address = str(addr)
        message.address = address
        self._sender(address).send(message, delivery_callback=callback)

    def _server_address(self, target):
        return self._concatenate([self.server_request_prefix,
                                  target.exchange or self.default_exchange,
                                  target.topic, target.server])

    def _broadcast_address(self, target):
        return self._concatenate([self.broadcast_prefix,
                                  target.exchange or self.default_exchange,
                                  target.topic, self.fanout_qualifier])

    def _group_request_address(self, target):
        return self._concatenate([self.group_request_prefix,
                                  target.exchange or self.default_exchange,
                                  target.topic])

    def _concatenate(self, items):
        return self.separator.join(filter(bool, items))

    # commands executed on the processor (eventloop) via 'wakeup()':

    def _do_connect(self):
        """Establish connection and reply subscription on processor thread."""
        host = self.hosts.current
        conn_props = {'hostname': host.hostname}
        if self.idle_timeout:
            conn_props["idle-time-out"] = float(self.idle_timeout)
        if self.trace_protocol:
            conn_props["x-trace-protocol"] = self.trace_protocol
        if self.ssl_ca_file:
            conn_props["x-ssl-ca-file"] = self.ssl_ca_file
        if self.ssl_cert_file:
            # assume this connection is for a server.  If client authentication
            # support is developed, we'll need an explicit flag (server or
            # client)
            conn_props["x-ssl-server"] = True
            conn_props["x-ssl-identity"] = (self.ssl_cert_file,
                                            self.ssl_key_file,
                                            self.ssl_key_password)
            conn_props["x-ssl-allow-cleartext"] = self.ssl_allow_insecure
        # SASL configuration:
        if self.sasl_mechanisms:
            conn_props["x-sasl-mechs"] = self.sasl_mechanisms
        if self.sasl_config_dir:
            conn_props["x-sasl-config-dir"] = self.sasl_config_dir
        if self.sasl_config_name:
            conn_props["x-sasl-config-name"] = self.sasl_config_name

        self._socket_connection = self.processor.connect(host,
                                                         handler=self,
                                                         properties=conn_props)
        LOG.debug("Connection initiated")

    def _process_tasks(self):
        """Execute Task objects in the context of the processor thread."""
        with self._process_tasks_lock:
            self._process_tasks_scheduled = False
        count = 0
        while (not self._tasks.empty() and
               count < self._max_task_batch and
               self._can_process_tasks):
            try:
                self._tasks.get(False).execute(self)
            except Exception as e:
                LOG.exception(_LE("Error processing task: %s"), e)
            count += 1

        # if we hit _max_task_batch, resume task processing later:
        if not self._tasks.empty() and self._can_process_tasks:
            self._schedule_task_processing()

    def _schedule_task_processing(self):
        """_process_tasks() helper: prevent queuing up multiple requests for
        task processing.  This method is called both by the application thread
        and the processing thread.
        """
        if self.processor:
            with self._process_tasks_lock:
                already_scheduled = self._process_tasks_scheduled
                self._process_tasks_scheduled = True
            if not already_scheduled:
                self.processor.wakeup(lambda: self._process_tasks())

    @property
    def _can_process_tasks(self):
        """_process_tasks helper(): indicates that the driver is ready to
        process Tasks.  In order to process messaging-related tasks, the reply
        queue link must be active.
        """
        return (not self._closing and
                self._replies and self._replies.ready())

    def _start_shutdown(self):
        """Called when the driver destroys the controller, this method attempts
        to cleanly close the AMQP connection to the peer.
        """
        LOG.info(_LI("Shutting down AMQP connection"))
        self._closing = True
        if self._socket_connection.connection.active:
            # try a clean shutdown
            self._socket_connection.connection.close()
        else:
            # don't wait for a close from the remote, may never happen
            self._complete_shutdown()

    # reply link active callback:

    def _reply_link_ready(self):
        """Invoked when the Replies reply link has become active.  At this
        point, we are ready to send/receive messages (via Task processing).
        """
        LOG.info(_LI("Messaging is active (%(hostname)s:%(port)s)"),
                 {'hostname': self.hosts.current.hostname,
                  'port': self.hosts.current.port})
        self._schedule_task_processing()

    # callback from eventloop on socket error

    def socket_error(self, error):
        """Called by eventloop when a socket error occurs."""
        LOG.debug("Socket failure: %s", error)
        self._handle_connection_loss()

    # Pyngus connection event callbacks (and their helpers), all invoked from
    # the eventloop thread:

    def connection_failed(self, connection, error):
        """This is a Pyngus callback, invoked by Pyngus when a non-recoverable
        error occurs on the connection.
        """
        if connection is not self._socket_connection.connection:
            # pyngus bug: ignore failure callback on destroyed connections
            return
        LOG.debug("AMQP Connection failure: %s", error)
        self._handle_connection_loss()

    def connection_active(self, connection):
        """This is a Pyngus callback, invoked by Pyngus when the connection to
        the peer is up.  At this point, the driver will activate all subscriber
        links (server) and the reply link.
        """
        LOG.debug("Connection active (%(hostname)s:%(port)s), subscribing...",
                  {'hostname': self.hosts.current.hostname,
                   'port': self.hosts.current.port})
        for s in self._servers.values():
            s.attach(self._socket_connection.connection)
        self._replies = Replies(self._socket_connection.connection,
                                lambda: self._reply_link_ready())
        self._delay = 0

    def connection_closed(self, connection):
        """This is a Pyngus callback, invoked by Pyngus when the connection has
        cleanly closed.  This occurs after the driver closes the connection
        locally, and the peer has acknowledged the close.  At this point, the
        shutdown of the driver's connection is complete.
        """
        LOG.debug("AMQP connection closed.")
        # if the driver isn't being shutdown, failover and reconnect
        self._handle_connection_loss()

    def connection_remote_closed(self, connection, reason):
        """This is a Pyngus callback, invoked by Pyngus when the peer has
        requested that the connection be closed.
        """
        if not self._closing:
            # The messaging service/broker is trying to shut down the
            # connection. Acknowledge the close, and try to reconnect/failover
            # later once the connection has closed (connection_closed is
            # called).
            LOG.info(_LI("Connection closed by peer: %s"),
                     reason or "no reason given")
            self._socket_connection.connection.close()

    def sasl_done(self, connection, pn_sasl, outcome):
        """This is a Pyngus callback invoked when the SASL handshake
        has completed.  The outcome of the handshake is passed in the outcome
        argument.
        """
        if outcome == proton.SASL.OK:
            return
        LOG.error(_LE("AUTHENTICATION FAILURE: Cannot connect to "
                      "%(hostname)s:%(port)s as user %(username)s"),
                  {'hostname': self.hosts.current.hostname,
                   'port': self.hosts.current.port,
                   'username': self.hosts.current.username})
        # connection failure will be handled later

    def _complete_shutdown(self):
        """The AMQP Connection has closed, and the driver shutdown is complete.
        Clean up controller resources and exit.
        """
        self._socket_connection.close()
        self.processor.shutdown()
        LOG.info(_LI("Messaging has shutdown"))

    def _handle_connection_loss(self):
        """The connection to the messaging service has been lost.  Try to
        reestablish the connection/failover.
        """
        if self._closing:
            # we're in the middle of shutting down the driver anyways,
            # just consider it done:
            self._complete_shutdown()
        else:
            # for some reason, we've lost the connection to the messaging
            # service.  Try to re-establish the connection:
            if not self._reconnecting:
                self._reconnecting = True
                self._replies = None
                LOG.info(_LI("delaying reconnect attempt for %d seconds"),
                         self._delay)
                self.processor.schedule(lambda: self._do_reconnect(),
                                        self._delay)
                self._delay = (1 if self._delay == 0
                               else min(self._delay * 2, 60))

    def _do_reconnect(self):
        """Invoked on connection/socket failure, failover and re-connect to the
        messaging service.
        """
        # note well: since this method destroys the connection, it cannot be
        # invoked directly from a pyngus callback.  Use processor.schedule() to
        # run this method on the main loop instead.
        if not self._closing:
            self._reconnecting = False
            self._senders = {}
            self._socket_connection.reset()
            host = self.hosts.next()
            LOG.info(_LI("Reconnecting to: %(hostname)s:%(port)s"),
                     {'hostname': host.hostname, 'port': host.port})
            self._socket_connection.connect(host)


text:
#import "SecurityTokenServiceFederatedUser.h"

@implementation SecurityTokenServiceFederatedUser

@synthesize federatedUserId;
@synthesize arn;

-(id)init
{
    if (self = [super init]) {
        federatedUserId = nil;
        arn             = nil;
    }

    return self;
}

-(id)initWithFederatedUserId:(NSString *)theFederatedUserId andArn:(NSString *)theArn
{
    if (self = [self init]) {
        self.federatedUserId = theFederatedUserId;
        self.arn             = theArn;
    }

    return self;
}

-(NSString *)description
{
    NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256];

    [buffer appendString:@"{"];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"FederatedUserId: %@,", federatedUserId] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"Arn: %@,", arn] autorelease]];
    [buffer appendString:[super description]];
    [buffer appendString:@"}"];

    return [buffer autorelease];
}

-(void)dealloc
{
    [federatedUserId release];
    [arn release];

    [super dealloc];
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Monogr. Uredin. (Lipsiae) 1(1): 128 (1902)

#### Original name
Puccinia onopordi P. Syd. & Syd.

### Remarks
null


text:
package org.apache.drill.exec.physical.impl.partitionsender;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;

import org.apache.drill.common.expression.ErrorCollector;
import org.apache.drill.common.expression.ErrorCollectorImpl;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.exec.exception.ClassTransformationException;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.expr.ClassGenerator;
import org.apache.drill.exec.expr.CodeGenerator;
import org.apache.drill.exec.expr.ExpressionTreeMaterializer;
import org.apache.drill.exec.memory.OutOfMemoryException;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.ops.MetricDef;
import org.apache.drill.exec.ops.OperatorContext;
import org.apache.drill.exec.physical.config.HashPartitionSender;
import org.apache.drill.exec.physical.impl.BaseRootExec;
import org.apache.drill.exec.physical.impl.SendingAccountor;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import org.apache.drill.exec.proto.ExecProtos.FragmentHandle;
import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
import org.apache.drill.exec.record.FragmentWritableBatch;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.drill.exec.record.RecordBatch.IterOutcome;
import org.apache.drill.exec.record.VectorWrapper;
import org.apache.drill.exec.rpc.data.DataTunnel;
import org.apache.drill.exec.vector.CopyUtil;

import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JType;

public class PartitionSenderRootExec extends BaseRootExec {

  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(PartitionSenderRootExec.class);
  private RecordBatch incoming;
  private HashPartitionSender operator;
  private Partitioner partitioner;
  private FragmentContext context;
  private boolean ok = true;
  private final SendingAccountor sendCount = new SendingAccountor();
  private final int outGoingBatchCount;
  private final HashPartitionSender popConfig;
  private final StatusHandler statusHandler;

  private final AtomicIntegerArray remainingReceivers;
  private final AtomicInteger remaingReceiverCount;
  private volatile boolean done = false;

  long minReceiverRecordCount = Long.MAX_VALUE;
  long maxReceiverRecordCount = Long.MIN_VALUE;

  public enum Metric implements MetricDef {
    BATCHES_SENT,
    RECORDS_SENT,
    MIN_RECORDS,
    MAX_RECORDS,
    N_RECEIVERS,
    BYTES_SENT;

    @Override
    public int metricId() {
      return ordinal();
    }
  }

  public PartitionSenderRootExec(FragmentContext context,
                                 RecordBatch incoming,
                                 HashPartitionSender operator) throws OutOfMemoryException {
    super(context, new OperatorContext(operator, context, null, false), operator);
    //super(context, operator);
    this.incoming = incoming;
    this.operator = operator;
    this.context = context;
    this.outGoingBatchCount = operator.getDestinations().size();
    this.popConfig = operator;
    this.statusHandler = new StatusHandler(sendCount, context);
    this.remainingReceivers = new AtomicIntegerArray(outGoingBatchCount);
    this.remaingReceiverCount = new AtomicInteger(outGoingBatchCount);
  }

  private boolean done() {
    for (int i = 0; i < remainingReceivers.length(); i++) {
      if (remainingReceivers.get(i) == 0) {
        return false;
      }
    }
    return true;
  }

  @Override
  public boolean innerNext() {
    boolean newSchema = false;

    if (!ok) {
      stop();

      return false;
    }

    IterOutcome out;
    if (!done) {
      out = next(incoming);
    } else {
      incoming.kill(true);
      out = IterOutcome.NONE;
    }

    logger.debug("Partitioner.next(): got next record batch with status {}", out);
    switch(out){
      case NONE:
        try {
          // send any pending batches
          if(partitioner != null) {
            partitioner.flushOutgoingBatches(true, false);
          } else {
            sendEmptyBatch();
          }
        } catch (IOException e) {
          incoming.kill(false);
          logger.error("Error while creating partitioning sender or flushing outgoing batches", e);
          context.fail(e);
        }
        return false;

      case STOP:
        if (partitioner != null) {
          partitioner.clear();
        }
        return false;

      case OK_NEW_SCHEMA:
        try {
          // send all existing batches
          if (partitioner != null) {
            partitioner.flushOutgoingBatches(false, true);
            partitioner.clear();
          }
          createPartitioner();
        } catch (IOException e) {
          incoming.kill(false);
          logger.error("Error while flushing outgoing batches", e);
          context.fail(e);
          return false;
        } catch (SchemaChangeException e) {
          incoming.kill(false);
          logger.error("Error while setting up partitioner", e);
          context.fail(e);
          return false;
        }
      case OK:
        try {
          partitioner.partitionBatch(incoming);
        } catch (IOException e) {
          context.fail(e);
          incoming.kill(false);
          return false;
        }
        for (VectorWrapper<?> v : incoming) {
          v.clear();
        }
        return true;
      case NOT_YET:
      default:
        throw new IllegalStateException();
    }
  }

  private void createPartitioner() throws SchemaChangeException {

    // set up partitioning function
    final LogicalExpression expr = operator.getExpr();
    final ErrorCollector collector = new ErrorCollectorImpl();
    final ClassGenerator<Partitioner> cg ;

    cg = CodeGenerator.getRoot(Partitioner.TEMPLATE_DEFINITION, context.getFunctionRegistry());
    ClassGenerator<Partitioner> cgInner = cg.getInnerGenerator("OutgoingRecordBatch");

    final LogicalExpression materializedExpr = ExpressionTreeMaterializer.materialize(expr, incoming, collector, context.getFunctionRegistry());
    if (collector.hasErrors()) {
      throw new SchemaChangeException(String.format(
          "Failure while trying to materialize incoming schema.  Errors:\n %s.",
          collector.toErrorString()));
    }

    // generate code to copy from an incoming value vector to the destination partition's outgoing value vector
    JExpression bucket = JExpr.direct("bucket");

    // generate evaluate expression to determine the hash
    ClassGenerator.HoldingContainer exprHolder = cg.addExpr(materializedExpr);
    cg.getEvalBlock().decl(JType.parse(cg.getModel(), "int"), "bucket", exprHolder.getValue().mod(JExpr.lit(outGoingBatchCount)));
    cg.getEvalBlock()._return(cg.getModel().ref(Math.class).staticInvoke("abs").arg(bucket));

    CopyUtil.generateCopies(cgInner, incoming, incoming.getSchema().getSelectionVectorMode() == SelectionVectorMode.FOUR_BYTE);

    try {
      // compile and setup generated code
//      partitioner = context.getImplementationClassMultipleOutput(cg);
      partitioner = context.getImplementationClass(cg);
      partitioner.setup(context, incoming, popConfig, stats, sendCount, oContext, statusHandler);

    } catch (ClassTransformationException | IOException e) {
      throw new SchemaChangeException("Failure while attempting to load generated class", e);
    }
  }

  public void updateStats(List<? extends PartitionOutgoingBatch> outgoing) {
    long records = 0;
    for (PartitionOutgoingBatch o : outgoing) {
      long totalRecords = o.getTotalRecords();
      minReceiverRecordCount = Math.min(minReceiverRecordCount, totalRecords);
      maxReceiverRecordCount = Math.max(maxReceiverRecordCount, totalRecords);
      records += totalRecords;
    }
    stats.addLongStat(Metric.BATCHES_SENT, 1);
    stats.addLongStat(Metric.RECORDS_SENT, records);
    stats.setLongStat(Metric.MIN_RECORDS, minReceiverRecordCount);
    stats.setLongStat(Metric.MAX_RECORDS, maxReceiverRecordCount);
    stats.setLongStat(Metric.N_RECEIVERS, outgoing.size());
  }

  @Override
  public void receivingFragmentFinished(FragmentHandle handle) {
    int id = handle.getMinorFragmentId();
    if (remainingReceivers.compareAndSet(id, 0, 1)) {
      partitioner.getOutgoingBatches().get(handle.getMinorFragmentId()).terminate();
      int remaining = remaingReceiverCount.decrementAndGet();
      if (remaining == 0) {
        done = true;
      }
    }
  }

  public void stop() {
    logger.debug("Partition sender stopping.");
    ok = false;
    if (partitioner != null) {
      partitioner.clear();
    }
    sendCount.waitForSendComplete();

    if (!statusHandler.isOk()) {
      context.fail(statusHandler.getException());
    }

    oContext.close();
    incoming.cleanup();
  }

  public void sendEmptyBatch() {
    FragmentHandle handle = context.getHandle();
    int fieldId = 0;
    StatusHandler statusHandler = new StatusHandler(sendCount, context);
    for (DrillbitEndpoint endpoint : popConfig.getDestinations()) {
      FragmentHandle opposite = context.getHandle().toBuilder().setMajorFragmentId(popConfig.getOppositeMajorFragmentId()).setMinorFragmentId(fieldId).build();
      DataTunnel tunnel = context.getDataTunnel(endpoint, opposite);
      FragmentWritableBatch writableBatch = FragmentWritableBatch.getEmptyLastWithSchema(
              handle.getQueryId(),
              handle.getMajorFragmentId(),
              handle.getMinorFragmentId(),
              operator.getOppositeMajorFragmentId(),
              fieldId,
              incoming.getSchema());
      stats.startWait();
      try {
        tunnel.sendRecordBatch(statusHandler, writableBatch);
      } finally {
        stats.stopWait();
      }
      this.sendCount.increment();
      fieldId++;
    }
  }

}


text:
package main.dialog.impl;

import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.*;
import main.controller.dialog.DialogController;
import main.dialog.Dialog;
import main.loader.*;
import main.loader.impl.LoaderImpl;
import main.model.Model;
import java.io.IOException;

/**
 * @author Marcin Przygoda
 */
public class DialogImpl<T extends Model> implements Dialog<T> {
    private Pane view;
    private DialogController<T> controller;
    private Model model;
    private Stage stage;

    public DialogImpl(Model model, ViewPath viewPath) throws IOException {
        this.model = model;
        stage = new Stage();

        initViewAndController(viewPath);
    }

    private void initViewAndController(ViewPath viewPath) throws IOException {
        Loader loader = new LoaderImpl(viewPath);

        view = loader.getView();
        controller = (DialogController<T>) loader.getController();
    }

    @Override
    public boolean showDialog(String title) {
        configureStage(title);
        configureController();

        stage.showAndWait();

        return controller.isApplied();
    }

    private void configureStage(String title) {
        stage.setScene(new Scene(view));
        stage.setTitle(title);
        stage.setResizable(false);
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.sizeToScene();
    }

    private void configureController() {
        controller.setDialogStage(stage);
        controller.setComponents((T) model);
    }
}


text:
package org.springframework.boot.web.servlet.server;

import java.io.File;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.boot.web.server.AbstractConfigurableWebServerFactory;
import org.springframework.boot.web.server.MimeMappings;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

/**
 * Abstract base class for {@link ConfigurableServletWebServerFactory} implementations.
 *
 * @author Phillip Webb
 * @author Dave Syer
 * @author Andy Wilkinson
 * @author Stephane Nicoll
 * @author Ivan Sopov
 * @author Eddú Meléndez
 * @author Brian Clozel
 * @since 2.0.0
 */
public abstract class AbstractServletWebServerFactory
		extends AbstractConfigurableWebServerFactory
		implements ConfigurableServletWebServerFactory {

	private static final int DEFAULT_SESSION_TIMEOUT = (int) TimeUnit.MINUTES
			.toSeconds(30);

	protected final Log logger = LogFactory.getLog(getClass());

	private String contextPath = "";

	private String displayName;

	private int sessionTimeout = DEFAULT_SESSION_TIMEOUT;

	private boolean persistSession;

	private boolean registerDefaultServlet = true;

	private MimeMappings mimeMappings = new MimeMappings(MimeMappings.DEFAULT);

	private List<ServletContextInitializer> initializers = new ArrayList<>();

	private Jsp jsp = new Jsp();

	private Map<Locale, Charset> localeCharsetMappings = new HashMap<>();

	private final SessionStoreDirectory sessionStoreDir = new SessionStoreDirectory();

	private final DocumentRoot documentRoot = new DocumentRoot(this.logger);

	private final StaticResourceJars staticResourceJars = new StaticResourceJars();

	/**
	 * Create a new {@link AbstractServletWebServerFactory} instance.
	 */
	public AbstractServletWebServerFactory() {
	}

	/**
	 * Create a new {@link AbstractServletWebServerFactory} instance with the specified
	 * port.
	 * @param port the port number for the web server
	 */
	public AbstractServletWebServerFactory(int port) {
		super(port);
	}

	/**
	 * Create a new {@link AbstractServletWebServerFactory} instance with the specified
	 * context path and port.
	 * @param contextPath the context path for the web server
	 * @param port the port number for the web server
	 */
	public AbstractServletWebServerFactory(String contextPath, int port) {
		super(port);
		checkContextPath(contextPath);
		this.contextPath = contextPath;
	}

	/**
	 * Returns the context path for the web server. The path will start with "/" and not
	 * end with "/". The root context is represented by an empty string.
	 * @return the context path
	 */
	public String getContextPath() {
		return this.contextPath;
	}

	@Override
	public void setContextPath(String contextPath) {
		checkContextPath(contextPath);
		this.contextPath = contextPath;
	}

	private void checkContextPath(String contextPath) {
		Assert.notNull(contextPath, "ContextPath must not be null");
		if (contextPath.length() > 0) {
			if ("/".equals(contextPath)) {
				throw new IllegalArgumentException(
						"Root ContextPath must be specified using an empty string");
			}
			if (!contextPath.startsWith("/") || contextPath.endsWith("/")) {
				throw new IllegalArgumentException(
						"ContextPath must start with '/' and not end with '/'");
			}
		}
	}

	public String getDisplayName() {
		return this.displayName;
	}

	@Override
	public void setDisplayName(String displayName) {
		this.displayName = displayName;
	}

	/**
	 * Return the session timeout in seconds.
	 * @return the timeout in seconds
	 */
	public int getSessionTimeout() {
		return this.sessionTimeout;
	}

	@Override
	public void setSessionTimeout(int sessionTimeout) {
		this.sessionTimeout = sessionTimeout;
	}

	@Override
	public void setSessionTimeout(int sessionTimeout, TimeUnit timeUnit) {
		Assert.notNull(timeUnit, "TimeUnit must not be null");
		this.sessionTimeout = (int) timeUnit.toSeconds(sessionTimeout);
	}

	public boolean isPersistSession() {
		return this.persistSession;
	}

	@Override
	public void setPersistSession(boolean persistSession) {
		this.persistSession = persistSession;
	}

	public File getSessionStoreDir() {
		return this.sessionStoreDir.getDirectory();
	}

	@Override
	public void setSessionStoreDir(File sessionStoreDir) {
		this.sessionStoreDir.setDirectory(sessionStoreDir);
	}

	/**
	 * Flag to indicate that the default servlet should be registered.
	 * @return true if the default servlet is to be registered
	 */
	public boolean isRegisterDefaultServlet() {
		return this.registerDefaultServlet;
	}

	@Override
	public void setRegisterDefaultServlet(boolean registerDefaultServlet) {
		this.registerDefaultServlet = registerDefaultServlet;
	}

	/**
	 * Returns the mime-type mappings.
	 * @return the mimeMappings the mime-type mappings.
	 */
	public MimeMappings getMimeMappings() {
		return this.mimeMappings;
	}

	@Override
	public void setMimeMappings(MimeMappings mimeMappings) {
		this.mimeMappings = new MimeMappings(mimeMappings);
	}

	/**
	 * Returns the document root which will be used by the web context to serve static
	 * files.
	 * @return the document root
	 */
	public File getDocumentRoot() {
		return this.documentRoot.getDirectory();
	}

	@Override
	public void setDocumentRoot(File documentRoot) {
		this.documentRoot.setDirectory(documentRoot);
	}

	@Override
	public void setInitializers(List<? extends ServletContextInitializer> initializers) {
		Assert.notNull(initializers, "Initializers must not be null");
		this.initializers = new ArrayList<>(initializers);
	}

	@Override
	public void addInitializers(ServletContextInitializer... initializers) {
		Assert.notNull(initializers, "Initializers must not be null");
		this.initializers.addAll(Arrays.asList(initializers));
	}

	public Jsp getJsp() {
		return this.jsp;
	}

	@Override
	public void setJsp(Jsp jsp) {
		this.jsp = jsp;
	}

	/**
	 * Return the Locale to Charset mappings.
	 * @return the charset mappings
	 */
	public Map<Locale, Charset> getLocaleCharsetMappings() {
		return this.localeCharsetMappings;
	}

	@Override
	public void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) {
		Assert.notNull(localeCharsetMappings, "localeCharsetMappings must not be null");
		this.localeCharsetMappings = localeCharsetMappings;
	}

	/**
	 * Utility method that can be used by subclasses wishing to combine the specified
	 * {@link ServletContextInitializer} parameters with those defined in this instance.
	 * @param initializers the initializers to merge
	 * @return a complete set of merged initializers (with the specified parameters
	 * appearing first)
	 */
	protected final ServletContextInitializer[] mergeInitializers(
			ServletContextInitializer... initializers) {
		List<ServletContextInitializer> mergedInitializers = new ArrayList<>();
		mergedInitializers.addAll(Arrays.asList(initializers));
		mergedInitializers.addAll(this.initializers);
		return mergedInitializers
				.toArray(new ServletContextInitializer[mergedInitializers.size()]);
	}

	/**
	 * Returns whether or not the JSP servlet should be registered with the web server.
	 * @return {@code true} if the servlet should be registered, otherwise {@code false}
	 */
	protected boolean shouldRegisterJspServlet() {
		return this.jsp != null && this.jsp.getRegistered() && ClassUtils
				.isPresent(this.jsp.getClassName(), getClass().getClassLoader());
	}

	/**
	 * Returns the absolute document root when it points to a valid directory, logging a
	 * warning and returning {@code null} otherwise.
	 * @return the valid document root
	 */
	protected final File getValidDocumentRoot() {
		return this.documentRoot.getValidDirectory();
	}

	protected final List<URL> getUrlsOfJarsWithMetaInfResources() {
		return this.staticResourceJars.getUrls();
	}

	protected final File getValidSessionStoreDir() {
		return this.sessionStoreDir.getValidDirectory(true);
	}

	protected final File getValidSessionStoreDir(boolean mkdirs) {
		return this.sessionStoreDir.getValidDirectory(mkdirs);
	}

}