text:
---
layout: article
title: "JPA - Lista de exercícios 02"
categories: jee
author: sakurai
date: 2011-02-22 12:30:00
tags: [javaee, jpa]
published: true
excerpt: Exercícios de JPA para praticar.
comments: true
image:
  teaser: 2011-02-11-teaser-jpa-exercicios-02.png
ads: false
---

## Exercício 1

Neste exercício vamos abordar como funciona os relacionamentos entre as entidades, vamos utilizar o relacionamento entre as entidades Cliente e Endereco, quando salvar o cliente também deve salvar o endereço e quando o cliente for consultado deve trazer também as informações do endereço.

Crie um projeto Java chamado **ExercicioJPA4**, adicione as bibliotecas **Hibernate JPA** e **Driver do Oracle ojdbc7.jar** (neste exercício estou usando o driver do Oracle, se quiser faça com outro banco de dados, só lembre de alterar o arquivo persistence.xml e a forma de geração do ID das entidades) e crie:

* Classe entity para representar um endereço com os atributos id, estado, cidade, bairro, logradouro e complemento.

{% highlight java %}
package br.universidadejava.jpa.exercicio1.modelo;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;

/**
 * Classe utilizada para representar um Endereço.
 */
@Entity
@SequenceGenerator(name = "ENDERECO_SEQ", sequenceName = "END_SEQ", initialValue = 1, allocationSize = 1)
public class Endereco implements Serializable {
  private static final long serialVersionUID = 5331450149454053703L;

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ENDERECO_SEQ")
  private Long id;
  private String estado;
  private String cidade;
  private String bairro;
  private String logradouro;
  private String complemento;

  public String getBairro() { return bairro; }
  public void setBairro(String bairro) { this.bairro = bairro; }
  public String getCidade() { return cidade; }
  public void setCidade(String cidade) { this.cidade = cidade; }
  public String getComplemento() { return complemento; }
  public void setComplemento(String complemento) {
    this.complemento = complemento;
  }
  public String getEstado() { return estado; }
  public void setEstado(String estado) { this.estado = estado; }
  public Long getId() { return id; }
  public void setId(Long id) { this.id = id; }
  public String getLogradouro() { return logradouro; }
  public void setLogradouro(String logradouro) { this.logradouro = logradouro; }
}
{% endhighlight %}

* Classe entity para representar um cliente com id, nome e endereço, note que vamos utilizar a anotação javax.persistence.OneToOne para definir o relacionamento de um-para-um entre as entidades Cliente e Endereco.

{% highlight java %}
package br.universidadejava.jpa.exercicio1.modelo;

import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;

/**
 * Classe utilizada para representar um Cliente.
 */
@Entity
@SequenceGenerator(name = "CLIENTE_SEQ", sequenceName = "CLI_SEQ", initialValue = 1, allocationSize = 1)
public class Cliente implements Serializable {
  private static final long serialVersionUID = 4521490124826140567L;

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CLIENTE_SEQ")
  private Long id;
  private String nome;
  @OneToOne(cascade=CascadeType.ALL)
  private Endereco endereco;

  public Endereco getEndereco() { return endereco; }
  public void setEndereco(Endereco endereco) { this.endereco = endereco; }
  public Long getId() { return id; }
  public void setId(Long id) { this.id = id; }
  public String getNome() { return nome; }
  public void setNome(String nome) { this.nome = nome; }
}
{% endhighlight %}

* Crie o banco de dados para guardar os dados de Cliente e Endereco:

{% highlight sql %}
CREATE SEQUENCE CLI_SEQ INCREMENT BY 1 START WITH 1 NOCACHE NOCYCLE;
CREATE SEQUENCE END_SEQ INCREMENT BY 1 START WITH 1 NOCACHE NOCYCLE;

CREATE TABLE ENDERECO (
  id number(5) NOT NULL PRIMARY KEY,
  estado VARCHAR2(50) NOT NULL,
  cidade VARCHAR2(50) NOT NULL,
  bairro VARCHAR2(50) NOT NULL,
  logradouro VARCHAR2(50) NOT NULL,
  complemento VARCHAR2(50) NOT NULL
);

CREATE TABLE CLIENTE (
  id number(5) NOT NULL PRIMARY KEY,
  nome VARCHAR2(100) NOT NULL,
  endereco_id number(5) NOT NULL
);
{% endhighlight %}

* Crie o arquivo persistence.xml dentro da pasta META-INF do projeto, note que neste arquivo vamos informar qual o banco de dados iremos utilizar e quais classes são entidades do banco:

{% highlight xml %}
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

  <persistence-unit name="ExercicioJPA1PU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>br.universidadejava.jpa.exercicio1.modelo.Endereco</class>
    <class>br.universidadejava.jpa.exercicio1.modelo.Cliente</class>
    <properties>
      <property name="hibernate.connection.username" value="usuario"/>
      <property name="hibernate.connection.password" value="senha"/>
      <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
      <property name="hibernate.connection.url" value="jdbc:oracle:thin:@ipDoBanco:1521:nomeDaBase"/>
      <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
      <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9Dialect"/>
      <property name="hibernate.show_sql" value="true"/>
    </properties>
  </persistence-unit>

</persistence>
{% endhighlight %}

* Crie a classe **ClienteDAO** que será responsável por utilizar o **EntityManager** para manipular (salvar, alterar, remover e consultar por id) as informações referentes ao Cliente.

{% highlight java %}
package br.universidadejava.jpa.exercicio1.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import br.universidadejava.jpa.exercicio1.modelo.Cliente;

/**
 * Classe utilizada para fazer as operações de banco de dados sobre a entity Cliente.
 */
public class ClienteDAO {

  /**
   * Método utilizado para obter o entity manager.
   * @return
   */
  private EntityManager getEntityManager() {
    EntityManagerFactory factory = null;
    EntityManager entityManager = null;
    try {
      //Obtem o factory a partir da unidade de persistencia.
      factory = Persistence.createEntityManagerFactory("ExercicioJPA4PU");
      //Cria um entity manager.
      entityManager = factory.createEntityManager();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      factory.close();
    }
    return entityManager;
  }

  /**
   * Método que salva ou atualiza as informações do cliente.
   * @param cliente
   * @return
   * @throws java.lang.Exception
   */
  public Cliente salvar(Cliente cliente) throws Exception {
    EntityManager entityManager = getEntityManager();
    try {
      // Inicia uma transação com o banco de dados.
      entityManager.getTransaction().begin();
      System.out.println("Salvando as informações do cliente.");
      // Verifica se o cliente ainda não está salvo no banco de dados.
      if(cliente.getId() == null) {
        entityManager.persist(cliente);
      } else {
        cliente = entityManager.merge(cliente);
      }
      // Finaliza a transação.
      entityManager.getTransaction().commit();
    } catch(Exception ex) {
      ex.printStackTrace();
      entityManager.getTransaction().rollback();
    } finally {
      entityManager.close();
    }
    // Retorna o cliente salvo.
    return cliente;
  }

  /**
   * Método que apaga as informações do cliente do banco de dados.
   * @param id
   */
  public void apagar(Long id) {
    EntityManager entityManager = getEntityManager();
    try {
      // Inicia uma transação com o banco de dados.
      entityManager.getTransaction().begin();
      // Consulta o cliente na base de dados através do seu ID.
      Cliente cliente = entityManager.find(Cliente.class, id);
      System.out.println("Excluindo o cliente: " + cliente.getNome());
      // Remove o cliente da base de dados.
      entityManager.remove(cliente);
      // Finaliza a transação.
      entityManager.getTransaction().commit();
    } catch(Exception ex) {
      ex.printStackTrace();
      entityManager.getTransaction().rollback();
    } finally {
      entityManager.close();
    }
  }

  /**
   * Consulta o cliente pelo ID.
   * @param id
   * @return
   */
  public Cliente consultarPorId(Long id) {
    EntityManager entityManager = getEntityManager();
    Cliente cliente = null;
    try {
      //Consulta o cliente pelo ID.
      cliente = entityManager.find(Cliente.class, id);
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      entityManager.close();
    }
    //Retorna o cliente consultado.
    return cliente;
  }
}
{% endhighlight %}

Vamos desenvolver a interface gráfica em SWING que será responsável por chamar o ClienteDAO para executar as operações no banco de dados.

Código fonte da tela de cadastro do cliente.

> este código não está completo possui apenas implementado o código dos botões.

{% highlight java %}
package br.universidadejava.jpa.exercicio1.tela;

import javax.swing.JOptionPane;
import br.universidadejava.jpa.exercicio1.dao.ClienteDAO;
import br.universidadejava.jpa.exercicio1.modelo.Cliente;
import br.universidadejava.jpa.exercicio1.modelo.Endereco;

/**
 * Classe utilizada para representar o cadastro do Cliente.
 */
public class CadastroCliente extends javax.swing.JFrame {
  private static final long serialVersionUID = -6011351657657723638L;

  public CadastroCliente() {
    initComponents();
  }

  /**
   * Código para montar a tela.
   */
  @SuppressWarnings("unchecked")
  private void initComponents() {
    //Código que monta a tela mostrada na imagem anterior.
  }

  /**
   * Botão que salva as informações do cliente.
   * @param evt
   */
  private void botaoSalvarActionPerformed(java.awt.event.ActionEvent evt) {
    try {
      //Cria um objeto endereco;
      Endereco e = new Endereco();
      if(!this.id.isEditable()) {
        e.setId(new Long(this.id.getText()));
      }
      e.setEstado(this.estado.getText());
      e.setCidade(this.cidade.getText());
      e.setBairro(this.bairro.getText());
      e.setLogradouro(this.logradouro.getText());
      e.setComplemento(this.complemento.getText());

      //Cria um objeto cliente.
      Cliente c = new Cliente();
      c.setNome(this.nome.getText());
      c.setEndereco(e);

      //Salva o cliente.
      ClienteDAO dao = new ClienteDAO();
      c = dao.salvar(c);

      JOptionPane.showMessageDialog(this, "Cliente " + c.getId() + " - " + c.getNome(), "INFORMAÇÃO", JOptionPane.INFORMATION_MESSAGE);
      limparDados();
    } catch (Exception ex) {
      JOptionPane.showMessageDialog(this, ex.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
    }
  }

  /**
   * Botão que consulta as informações do cliente.
   * @param evt
   */
  private void botaoConsultarActionPerformed(java.awt.event.ActionEvent evt) {
    try {
      ClienteDAO dao = new ClienteDAO();
      Cliente c = dao.consultarPorId(Long.valueOf(this.id.getText()));

      if(c != null) {
        this.id.setEditable(false);
        this.nome.setText(c.getNome());
        this.estado.setText(c.getEndereco().getEstado());
        this.cidade.setText(c.getEndereco().getCidade());
        this.bairro.setText(c.getEndereco().getBairro());
        this.logradouro.setText(c.getEndereco().getLogradouro());
        this.complemento.setText(c.getEndereco().getComplemento());
      } else {
        limparDados();
        JOptionPane.showMessageDialog(this, "Cliente não foi encontrado!", "ERRO", JOptionPane.ERROR_MESSAGE);
      }
    } catch (NumberFormatException ex) {
      JOptionPane.showMessageDialog(this, "O campo código precisa ser um número inteiro", "ERRO", JOptionPane.ERROR_MESSAGE);
    }
  }

  /**
   * Botão para limpar as informações do formulario para cadastrar um
   * novo cliente.
   * @param evt
   */
  private void botaoNovoActionPerformed(java.awt.event.ActionEvent evt) {
    limparDados();
  }

  /**
   * Botão para remover as informações referentes a um cliente.
   * @param evt
   */
  private void botaoApagarActionPerformed(java.awt.event.ActionEvent evt) {
    try {
      ClienteDAO dao = new ClienteDAO();
      dao.apagar(Long.valueOf(this.id.getText()));
      limparDados();
      JOptionPane.showMessageDialog(this, "As informações do cliente foram apagadas do sistema.", "INFORMAÇÃO", JOptionPane.INFORMATION_MESSAGE);
    } catch (NumberFormatException ex) {
      JOptionPane.showMessageDialog(this, "O campo código precisa ser um número inteiro", "ERRO", JOptionPane.ERROR_MESSAGE);
    }
  }

  /**
   * Limpa os dados do formulario.
   */
  private void limparDados() {
    this.id.setText(null);
    this.id.setEditable(true);
    this.nome.setText(null);
    this.estado.setText(null);
    this.cidade.setText(null);
    this.bairro.setText(null);
    this.logradouro.setText(null);
    this.complemento.setText(null);
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        new CadastroCliente().setVisible(true);
      }
    });
  }

  private javax.swing.JTextField bairro;
  private javax.swing.JButton botaoApagar;
  private javax.swing.JButton botaoConsultar;
  private javax.swing.JButton botaoNovo;
  private javax.swing.JButton botaoSalvar;
  private javax.swing.JTextField cidade;
  private javax.swing.JTextField complemento;
  private javax.swing.JTextField estado;
  private javax.swing.JTextField id;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel6;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JLabel jLabel8;
  private javax.swing.JTextField logradouro;
  private javax.swing.JTextField nome;
}
{% endhighlight %}

##Exercício 2

Neste exercício vamos desenvolver uma aplicação Swing ou Console para implementar o seguinte requisito de sistema:
"Precisamos controlar as vendas de instrumentos musicais, desenvolva uma aplicação para cadastrar, alterar, consultar pelo código e remover os instrumentos musicais (marca, modelo e preço). Também devemos cadastrar as vendas feitas para um cliente, onde o cliente (nome, cpf e telefone) pode comprar diversos instrumentos musicais. Não temos a necessidade de controlar o estoque dos produtos, pois apenas será vendido os itens que estão nas prateleiras."

## Conteúdos relacionados

- [Mais exercícios com JPA](http://www.universidadejava.com.br/jee/jpa-exercicios-03/)
- [Exemplo de CRUD com JPA](http://www.universidadejava.com.br/jee/jpa-exemplo-crud/)
- [Usando Query do JPA](http://www.universidadejava.com.br/jee/jpa-query/)
- [Criando uma aplicação com EJB + JPA](http://www.universidadejava.com.br/jee/criando-aplicacao-ejb-jpa/)


text:
package com.marverenic.music.utils;

import com.crashlytics.android.Crashlytics;

import timber.log.Timber;

public class CrashlyticsTree extends Timber.Tree {

    @Override
    protected void log(int priority, String tag, String message, Throwable throwable) {
        if (throwable != null) {
            Crashlytics.log(priority, tag, message);
            Crashlytics.logException(throwable);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
module Faqs::FaqsHelper

end


text:
Karen li(kjl32) Sally Al(sma45)
We had three public variables. We fixed that.
Sally


text:
package DDG::Spice::LeakDB;
# ABSTRACT: Plaintext of hashes, and hashes of plaintexts

use strict;
use DDG::Spice;

triggers startend => 'hashme', 'leakdb';
spice to => 'http://api.leakdb.abusix.com/?j=$1';
spice wrap_jsonp_callback => 1;

handle remainder => sub{
    return if $_ eq '';
    return $_;
};

1;


text:
package org.apache.derby.client.am;

import org.apache.derby.client.ClientPooledConnection;
import org.apache.derby.client.ClientXAConnection;
import org.apache.derby.jdbc.ClientDataSource;
import java.sql.SQLException;
import org.apache.derby.client.am.stmtcache.JDBCStatementCache;
import org.apache.derby.client.am.stmtcache.StatementKey;
import org.apache.derby.jdbc.ClientBaseDataSource;

/**
 *
 * The methods of this interface are used to return JDBC interface
 * implementations to the user depending on the JDBC version supported
 * by the jdk
 *
 */

public interface ClientJDBCObjectFactory {

    /**
     * This method is used to return an instance of
     * ClientPooledConnection (or ClientPooledConnection40) class which
     * implements javax.sql.PooledConnection
     */
    ClientPooledConnection newClientPooledConnection(ClientBaseDataSource ds,
            LogWriter logWriter,String user,String password)
            throws SQLException;

    /**
     * This method is used to return an instance of
     * ClientPooledConnection(or ClientPooledConnection40) class which
     * implements javax.sql.PooledConnection
     */
    ClientPooledConnection newClientPooledConnection(ClientBaseDataSource ds,
            LogWriter logWriter,String user,String password,int rmId)
            throws SQLException;

    /**
     * This method is used to return an instance of
     * ClientXAConnection (or ClientXAConnection40) class which
     * implements javax.sql.XAConnection
     */
    ClientXAConnection newClientXAConnection(ClientBaseDataSource ds,
            LogWriter logWriter,String user,String password)
            throws SQLException;

    /**
     * Returns an instance of org.apache.derby.client.am.CallableStatement.
     * or CallableStatement40 which implements java.sql.CallableStatement
     *
     * @param agent       The instance of NetAgent associated with this
     *                    CallableStatement object.
     * @param connection  The connection object associated with this
     *                    PreparedStatement Object.
     * @param sql         A String object that is the SQL statement to be sent
     *                    to the database.
     * @param type        One of the ResultSet type constants
     * @param concurrency One of the ResultSet concurrency constants
     * @param holdability One of the ResultSet holdability constants
     * @param cpc         The PooledConnection object that will be used to
     *                    notify the PooledConnection reference of the Error
     *                    Occurred and the Close events.
     * @return a CallableStatement object
     * @throws SqlException
     */
    CallableStatement newCallableStatement(Agent agent,
            org.apache.derby.client.am.Connection connection, String sql,
            int type,int concurrency,int holdability,
            ClientPooledConnection cpc) throws SqlException;

    /**
     * Returns an instance of LogicalConnection.
     * This method returns an instance of LogicalConnection
     * (or LogicalConnection40) which implements java.sql.Connection.
     */
    LogicalConnection newLogicalConnection(
                    org.apache.derby.client.am.Connection physicalConnection,
                    ClientPooledConnection pooledConnection)
        throws SqlException;

   /**
    * Returns an instance of a {@code CachingLogicalConnection}, which
    * provides caching of prepared statements.
    *
    * @param physicalConnection the underlying physical connection
    * @param pooledConnection the pooled connection
    * @param stmtCache statement cache
    * @return A logical connection with statement caching capabilities.
    *
    * @throws SqlException if creation of the logical connection fails
    */
    public LogicalConnection newCachingLogicalConnection(
            org.apache.derby.client.am.Connection physicalConnection,
            ClientPooledConnection pooledConnection,
            JDBCStatementCache stmtCache) throws SqlException;

    /**
     * This method returns an instance of PreparedStatement
     * (or PreparedStatement40) which implements java.sql.PreparedStatement
     * It has the ClientPooledConnection as one of its parameters
     * this is used to raise the Statement Events when the prepared
     * statement is closed
     *
     * @param agent The instance of NetAgent associated with this
     *              CallableStatement object.
     * @param connection The connection object associated with this
     *                   PreparedStatement Object.
     * @param sql        A String object that is the SQL statement to be sent
     *                   to the database.
     * @param section    Section
     * @param cpc The ClientPooledConnection wraps the underlying physical
     *            connection associated with this prepared statement.
     *            It is used to pass the Statement closed and the Statement
     *            error occurred events that occur back to the
     *            ClientPooledConnection.
     * @return a PreparedStatement object
     * @throws SqlException
     */
    PreparedStatement newPreparedStatement(Agent agent,
            org.apache.derby.client.am.Connection connection,
            String sql,Section section,ClientPooledConnection cpc)
            throws SqlException;

    /**
     * Returns an instance of PreparedStatement
     * (or PreparedStatement40) which implements java.sql.PreparedStatement
     * It has the ClientPooledConnection as one of its parameters
     * this is used to raise the Statement Events when the prepared
     * statement is closed
     *
     * @param agent The instance of NetAgent associated with this
     *              CallableStatement object.
     * @param connection  The connection object associated with this
     *                    PreparedStatement Object.
     * @param sql         A String object that is the SQL statement
     *                    to be sent to the database.
     * @param type        One of the ResultSet type constants.
     * @param concurrency One of the ResultSet concurrency constants.
     * @param holdability One of the ResultSet holdability constants.
     * @param autoGeneratedKeys a flag indicating whether auto-generated
     *                          keys should be returned.
     * @param columnNames an array of column names indicating the columns that
     *                    should be returned from the inserted row or rows.
     * @param columnIndexes an array of column indexes indicating the columns
     *                    that should be returned form the inserted row.
     * @param cpc The ClientPooledConnection wraps the underlying physical
     *            connection associated with this prepared statement
     *            it is used to pass the Statement closed and the Statement
     *            error occurred events that occur back to the
     *            ClientPooledConnection.
     * @return a PreparedSatement object
     * @throws SqlException
     */
    PreparedStatement newPreparedStatement(Agent agent,
            org.apache.derby.client.am.Connection connection,String sql,
            int type,int concurrency,int holdability,int autoGeneratedKeys,
            String [] columnNames, int[] columnIndexes, ClientPooledConnection cpc)
            throws SqlException;

    /**
     * Returns a new logcial prepared statement object.
     *
     * @param ps underlying physical prepared statement
     * @param stmtKey key for the underlying physical prepared statement
     * @param cacheInteractor the statement cache interactor
     * @return A logical prepared statement.
     */
    LogicalPreparedStatement newLogicalPreparedStatement(
            java.sql.PreparedStatement ps,
            StatementKey stmtKey,
            StatementCacheInteractor cacheInteractor);

    /**
     * Returns a new logical callable statement object.
     *
     * @param cs underlying physical callable statement
     * @param stmtKey key for the underlying physical callable statement
     * @param cacheInteractor the statement cache interactor
     * @return A logical callable statement.
     */
    LogicalCallableStatement newLogicalCallableStatement(
            java.sql.CallableStatement cs,
            StatementKey stmtKey,
            StatementCacheInteractor cacheInteractor);

    /**
     * This method returns an instance of NetConnection (or NetConnection40) class
     * which extends from org.apache.derby.client.am.Connection
     * this implements the java.sql.Connection interface
     */
    org.apache.derby.client.am.Connection newNetConnection(
            LogWriter netLogWriter,
            String databaseName,java.util.Properties properties)
            throws SqlException;

    /**
     * This method returns an instance of NetConnection (or NetConnection40) class
     * which extends from org.apache.derby.client.am.Connection
     * this implements the java.sql.Connection interface
     */
    org.apache.derby.client.am.Connection newNetConnection(
            LogWriter netLogWriter,
            org.apache.derby.jdbc.ClientBaseDataSource clientDataSource,String user,
            String password) throws SqlException;

    /**
     * This method returns an instance of NetConnection (or NetConnection40)
     * class which extends from org.apache.derby.client.am.Connection
     * this implements the java.sql.Connection interface
     */
    org.apache.derby.client.am.Connection newNetConnection(
            LogWriter netLogWriter,
            int driverManagerLoginTimeout,String serverName,
            int portNumber,String databaseName,java.util.Properties properties)
            throws SqlException;

    /**
     * This method returns an instance of NetConnection (or NetConnection40)
     * class which extends from org.apache.derby.client.am.Connection
     * this implements the java.sql.Connection interface
     */
    org.apache.derby.client.am.Connection newNetConnection(
            LogWriter netLogWriter,
            String user,String password,
            org.apache.derby.jdbc.ClientBaseDataSource dataSource,int rmId,
            boolean isXAConn) throws SqlException;

    /**
     * This methos returns an instance of NetConnection
     * (or NetConnection40) class which extends from
     * org.apache.derby.client.am.Connection this implements the
     * java.sql.Connection interface
     */
    org.apache.derby.client.am.Connection newNetConnection(
            LogWriter netLogWriter,String ipaddr,
            int portNumber,org.apache.derby.jdbc.ClientBaseDataSource dataSource,
            boolean isXAConn) throws SqlException;

    /**
     * This method returns an instance of NetConnection (or NetConnection40)
     * class which extends from org.apache.derby.client.am.Connection
     * this implements the java.sql.Connection interface
     * This method is used to pass the ClientPooledConnection
     * object to the NetConnection object which can then be used to pass the
     * statement events back to the user
     *
     * @param netLogWriter placeholder for NetLogWriter object associated with this connection
     * @param user         user id for this connection
     * @param password     password for this connection
     * @param dataSource   The DataSource object passed from the PooledConnection
     *                     object from which this constructor was called
     * @param rmId         The Resource Manager ID for XA Connections
     * @param isXAConn     true if this is a XA connection
     * @param cpc          The ClientPooledConnection object from which this
     *                     NetConnection constructor was called. This is used
     *                     to pass StatementEvents back to the pooledConnection
     *                     object
     * @throws             SqlException
     */
    org.apache.derby.client.am.Connection newNetConnection(
            LogWriter netLogWriter,
            String user,String password,
            org.apache.derby.jdbc.ClientBaseDataSource dataSource,int rmId,
            boolean isXAConn,ClientPooledConnection cpc) throws SqlException;

    /**
     * This method returns an instance of NetResultSet(or NetResultSet40)
     * which extends from org.apache.derby.client.am.ResultSet
     * which implements java.sql.ResultSet
     */
    ResultSet newNetResultSet(Agent netAgent,MaterialStatement netStatement,
            Cursor cursor,
            int qryprctyp, int sqlcsrhld, int qryattscr, int qryattsns,
            int qryattset,long qryinsid,int actualResultSetType,
            int actualResultSetConcurrency,int actualResultSetHoldability)
            throws SqlException;

    /**
     * This method provides an instance of NetDatabaseMetaData
     * (or NetDatabaseMetaData40) which extends from
     * org.apache.derby.client.am.DatabaseMetaData which implements
     * java.sql.DatabaseMetaData
     */
    DatabaseMetaData newNetDatabaseMetaData(Agent netAgent,
            org.apache.derby.client.am.Connection netConnection);

    /**
     * This method provides an instance of Statement or Statement40
     * depending on the jdk version under use
     * @param  agent      Agent
     * @param  connection Connection
     * @return a java.sql.Statement implementation
     * @throws SqlException
     *
     */
     Statement newStatement(Agent agent,
             org.apache.derby.client.am.Connection connection)
             throws SqlException;

     /**
     * This method provides an instance of Statement or Statement40
     * depending on the jdk version under use
     * @param  agent            Agent
     * @param  connection       Connection
     * @param  type             int
     * @param  concurrency      int
     * @param  holdability      int
     * @param autoGeneratedKeys int
     * @param columnNames       String[]
     * @param columnIndexes     int[]
     * @return a java.sql.Statement implementation
     * @throws SqlException
     *
     */
     Statement newStatement(Agent agent,
                     org.apache.derby.client.am.Connection connection, int type,
                     int concurrency, int holdability,
                     int autoGeneratedKeys, String[] columnNames,
                     int[] columnIndexes)
                     throws SqlException;

    /**
     * Returns an instanceof ColumnMetaData or ColumnMetaData40 depending
     * on the jdk version under use
     *
     * @param logWriter LogWriter
     * @return a ColumnMetaData implementation
     *
     */
    ColumnMetaData newColumnMetaData(LogWriter logWriter);

    /**
     * Returns an instanceof ColumnMetaData or ColumnMetaData40 depending
     * on the jdk version under use
     *
     * @param logWriter  LogWriter
     * @param upperBound int
     * @return a ColumnMetaData implementation
     *
     */
    ColumnMetaData newColumnMetaData(LogWriter logWriter, int upperBound);

    /**
     *
     * returns an instance of ParameterMetaData or ParameterMetaData40 depending
     * on the jdk version under use
     *
     * @param columnMetaData ColumnMetaData
     * @return a ParameterMetaData implementation
     *
     */
    ParameterMetaData newParameterMetaData(ColumnMetaData columnMetaData);
}


text:
package org.hecl.net;

import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;

//#ifdef j2me
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
//#if cldc > 1.0
import javax.microedition.io.HttpsConnection;
//#endif
//#else
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
//#endif

public class HttpRequest extends Thread {
    static public final short SETUP = 0;
    static public final short CONNECTED = 1;
    static public final short ERROR = 2;
    static public final short TIMEOUT = 3;
    static public final short OK = 4;

//#ifdef j2me
    public static final int HTTP_UNAUTHORIZED = HttpConnection.HTTP_UNAUTHORIZED;
    public static final int HTTP_FORBIDDEN = HttpConnection.HTTP_FORBIDDEN;
//#else
    public static final int HTTP_UNAUTHORIZED = HttpURLConnection.HTTP_UNAUTHORIZED;
    public static final int HTTP_FORBIDDEN = HttpURLConnection.HTTP_FORBIDDEN;

    public static final String GET = "GET";
    public static final String POST ="POST";
    public static final String HEAD = "HEAD";
    public static final String OPTIONS = "OPTIONS";
    public static final String PUT = "PUT";
    public static final String DELETE = "DELETE";
    public static final String TRACE = "TRACE";
//#endif

    public HttpRequest(String url, QueryParam[] params,
		       boolean validate, Hashtable headerfields) {
	qparams = params;
	setup(url,validate,headerfields);
    }

    public HttpRequest(String url, String queryData,
		       boolean validate, Hashtable headerfields) {
	qdata = queryData;
	setup(url,validate,headerfields);
    }

    private void setup(String url, boolean validate, Hashtable headerfields) {
	urlstr = url;
	if(headerfields != null) {
	    Enumeration e = headerfields.keys();
	    while(e.hasMoreElements()) {
		String key = (String)e.nextElement();
		requestFields.put(key,(String)headerfields.get(key));
	    }
	}
	if(qdata != null || qparams != null) {
	    requestMethod =
//#ifdef j2me
		HttpConnection.POST
//#else
		POST
//#endif
		;
	} else {
	    if(validate)
		requestMethod =
//#ifdef j2me
		    HttpConnection.HEAD
//#else
		    HEAD
//#endif
		    ;
	}
    }

    // Add a header field with key and value when sending a request
    // Must be called before the request.
    public void addRequestField(String key, String value) {
	requestFields.put(key, value);
    }

    // Get the value of a key after the connection is closed.
    // Must be called after the request.
    public String getResponseFieldValue(String key) {
	return (String)responseFields.get(key);
    }

    public Enumeration getResponseFieldNames() {
	return responseFields.keys();
    }

    public String getURL() {
	return urlstr;
    }

    public static String hexdump(byte[] buf) {
	StringBuffer sb = new StringBuffer();

	for(int i=0; i<buf.length; ++i) {
	    byte b = buf[i];

	    sb.append(Integer.toHexString((b&0xf0)>>4));
	    sb.append(Integer.toHexString(b&0x0f));
	    sb.append(' ');
	    if(i!=0 && ((i+1)%8) == 0)
		sb.append(' ');
	    if(i != 0 && ((i+1)%16) == 0)
		sb.append('\n');
	}
	if(sb.charAt(sb.length()-1) != '\n')
	    sb.append('\n');
	return new String(sb);
    }

    public synchronized void run() {
	MyHttpConn co = null;
	rc = -1;
	error = null;
	inData = null;

	try {
	    co = new MyHttpConn(urlstr);
	}
	catch (IOException e) {
	    status = ERROR;
	    error = e;
	    e.printStackTrace();
	    System.err.println("HttpRequest.preparation error");
	    return;
	}

	try {
	    if(DEBUGRC)
		System.err.println("Connecting...");
	    co.connect(requestMethod,requestFields,qdata,qparams);
	    status = CONNECTED;
	    if(DEBUGRC)
		System.err.println("Connected");
	    rc = co.getResponseCode();
	    if(DEBUGRC)
		System.err.println("rc="+rc);
	    if(rc == -1) {
		status = ERROR;
		return;
	    }
	    responseFields = co.readHeader();
	    inData = co.readBody();
	    status = OK;

	    // If no charset is given, use the default (see below).
	    String charset = DEFCHARSET;
	    String ct = (String)responseFields.get(CONTENTTYPE);
	    String coding = (String)responseFields.get(CONTENTENCODING);

	    if(ct == null) {
		// should be present, but who nows...
		ct = "text/plain";
		responseFields.put(CONTENTTYPE,ct);
	    }

	    if((ct != null && !ct.toLowerCase().startsWith("text"))
	       || (coding != null &&
		   (coding.indexOf("gzip") >= 0 || coding.indexOf("compress") >= 0))
		) {
		// binary transfer
		responseFields.put("binary","1");
	    } else {
		// textual transfer
		responseFields.put("binary","0");
		if(ct != null) {
		    int begin = ct.toLowerCase().indexOf("charset=");
		    if (begin >= 0) {
			// In a midlet, an empty encoding string would result
			// in an UnsupportedEncodingException when creating a
			// string object.
			begin += 8;	    // # of chars in 'charset='
			int end = ct.indexOf(';', begin);
			if (end == -1) {
			    end = ct.length();
			}
			charset = ct.substring(begin, end);
			//System.err.println("charset in reply="+charset);
		    }
		}
	    }
	    //System.err.println("charset now="+charset +", isocharset="+isISOCharset(charset));

	    // charset is now detected, create a string holding the result.
	    if(charset == DEFCHARSET || isISOCharset(charset)) {
		//System.err.println("internal ISO 8859 decode");
		body = bytesToString(inData,0,inData.length);
		//System.err.println("ISO 8859 decode done");
		charset = DEFCHARSET;
		responseFields.put("charset",charset);
	    } else {
		for(int i=0; i<3; ++i) {
		    switch(i) {
		      case 0:
			break;
		      case 1:
			charset = charset.toLowerCase();
			break;
		      case 2:
			charset = charset.toUpperCase();
			break;
		    }
		    responseFields.put("charset",charset);
		    try {
			//System.err.println("trying to decode with charset="+charset);
			body = new String(inData,charset);
			//System.err.println("decode success");
			break;
		    }
		    catch(Exception e2) {
			body = "xxx-encoding-failed-xxx\n"+e2.getMessage();
		    }
		}
		//System.err.println("decode bytelen="+inData.length);
		//System.err.println("decode strlen="+body.length());
	    }
	}
	catch (Exception e) {
	    status = ERROR;
	    error = e;
	    e.printStackTrace();
	}
	if(DEBUGBODY)
	    System.err.println(getBody());
	if(co != null) {
	    co.close();
	}
	// no longer needed
	inData = null;
    }

    public static byte[] asISOBytes(String s) {
	byte[] buf = new byte[s.length()];
	for(int i=0; i<s.length(); ++i) {
	    char ch = s.charAt(i);
	    buf[i] = (byte)ch;
	}
	return buf;
    }

    public static String bytesToString(byte[] buf) {
	return bytesToString(buf,0,buf.length);
    }

    public static String bytesToString(byte[] buf,int start,int n) {
	return bytesToStringBuffer(buf,start,n).toString();
    }

    public static StringBuffer bytesToStringBuffer(byte[] buf) {
	return bytesToStringBuffer(buf,0,buf.length);
    }

    public static StringBuffer bytesToStringBuffer(byte[] buf,int start,int n) {
	StringBuffer sb = new StringBuffer(buf.length);
	//System.err.println("old data:");
	//System.err.println(hexdump(buf));
	for(int i=start; n>0; ++i, --n) {
	    sb.append((char)buf[i]);
	}
	//System.err.println("new data:");
	//System.err.println(hexdump(asISOBytes(sb.toString())));
	return sb;
    }

    public int getStatus() {
	return status;
    }

    public Exception getException() {
	return error;
    }

    public String getBody() {
	return body;
    }

//#ifdef notdef
    public byte[] getBytes() {
	return inData;
    }
//#endif

    public int getRC() {
	return rc;
    }

    public static String getStatusText(int status) {
	switch(status) {
	  case SETUP:
	    return "setup";
	  case CONNECTED:
	    return "connected";
	  case ERROR:
	    return "error";
	  case TIMEOUT:
	    return "timeout";
	  case OK:
	    return "ok";
	  default:
	    return "unknown";
	}
    }

    public static byte[] IRIencode(String str) {
	int strlen = str.length();
	int utflen = 0;
 	char[] charr = new char[strlen];
	int c, count = 0;

	str.getChars(0, strlen, charr, 0);

	for (int i = 0; i < strlen; i++) {
	    c = charr[i];
	    if ((c >= 0x0001) && (c <= 0x007F)) {
		utflen++;
	    } else if (c > 0x07FF) {
		utflen += 3;
	    } else {
		utflen += 2;
	    }
	}

	byte[] bytearr = new byte[utflen];
	for (int i = 0; i < strlen; i++) {
	    c = charr[i];
	    if ((c >= 0x0001) && (c <= 0x007F)) {
		bytearr[count++] = (byte)c;
	    } else if (c > 0x07FF) {
		bytearr[count++] = (byte)(0xE0 | ((c >> 12) & 0x0F));
		bytearr[count++] = (byte)(0x80 | ((c >>  6) & 0x3F));
		bytearr[count++] = (byte)(0x80 | ((c >>  0) & 0x3F));
	    } else {
		bytearr[count++] = (byte)(0xC0 | ((c >>  6) & 0x1F));
		bytearr[count++] = (byte)(0x80 | ((c >>  0) & 0x3F));
	    }
	}
	return bytearr;
    }

    public static String urlencode(byte[] s,int start, int n) {
	StringBuffer b = new StringBuffer();
	for(int i = start; n>0; ++i, --n) {
	    b.append(urlencodemap[s[i] & 0xff]);
	}
	return b.toString();
    }

    public static String urlencode(byte[] s) {
	return urlencode(s,0,s.length);
    }

    public static String urlencode(String[] elems) {
	if(elems == null || elems.length == 0)
	    return null;

	StringBuffer b = new StringBuffer();
	if(elems != null) {
	    for(int i = 0; i < elems.length; ++i) {
		if(i > 0) {
		    b.append((i % 2) != 0 ? '=' : '&');
		}
		b.append(urlencode(IRIencode(elems[i])));
	    }
	}
	return b.toString();
    }

    private boolean isISOCharset(String charset) {
	String lower = charset.toLowerCase();

	for(int i=0; i<ISOALIASES.length; ++i) {
	    if(lower.equals(ISOALIASES[i]))
		return true;
	}
	return false;
    }

    private String urlstr = null;
    private byte[] inData = null;
    private String body = "";
    private String qdata = null;
    private QueryParam[] qparams = null;
    private String requestMethod =
//#ifdef j2me
    HttpConnection.GET
//#else
    GET
//#endif
    ;
    private int rc = -1;
    private short status = SETUP;
    Exception error = null;
    private Hashtable requestFields = new Hashtable();
    private Hashtable responseFields = new Hashtable();

    private static String[] urlencodemap = new String[256];
    private static String validUrlChars =
    "-_.!~*'()\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final char[] hexchars = (new String("0123456789ABCDEF")).toCharArray();
    public static boolean DEBUGURL = false;
    public static boolean DEBUGRC = false;
    public static boolean DEBUGBODY = false;
    public static String DEFCHARSET = "ISO8859-1";
    public static final String CONTENTTYPE = "content-type";
    public static final String CONTENTENCODING = "content-encoding";
    static private final String ISOALIASES[]= {
	"iso-8859-1","iso8859-1","iso8859_1","iso_8859_1","iso-8859_1","iso_8859-1"
    };

    static {
	char[] cbuf = new char[3];
	for(int i = 0; i < 256; i++) {
	    char ch = (char)i;
	    int idx = validUrlChars.indexOf(ch);
	    if(idx >= 0) {
		urlencodemap[i] = validUrlChars.substring(idx, idx + 1);
	    } else {
		// !!! Do not use
		// urlencodemap[i] = "%" + Integer.toHexString(i);
		// since it does not print leading 0s
		cbuf[0] = '%';
		cbuf[1] = hexchars[(i&0xf0)>>4];
		cbuf[2] = hexchars[i&0x0f];
		urlencodemap[i] = new String(cbuf);
	    }
	}
	urlencodemap[' '] = "+";
	//urlencodemap['\n'] = "%0D%0A";
    }

}

class MyHttpConn {
    MyHttpConn(String url) throws IOException {
	is = null;
	os = null;
	conn = null;
//#if javaversion >= 1.5 || cldc > 1.0
	secure = url.toLowerCase().startsWith("https");
//#endif

	if(HttpRequest.DEBUGURL)
	    System.err.println("url="+url);
//#ifdef j2me
//#if cldc > 1.0
	conn = secure ?
	    (HttpsConnection)
	    Connector.open(url/*,Connector.READ_WRITE, true*/) :
	    (HttpConnection)
	    Connector.open(url/*,Connector.READ_WRITE, true*/);
//#else
	conn = (HttpConnection)
	    Connector.open(url/*,Connector.READ_WRITE, true*/);
//#endif
//#else
	URL myurl = new URL(url);
	conn = secure ? (HttpsURLConnection) myurl.openConnection() :
	    (HttpURLConnection)myurl.openConnection();
//#endif
    }

    void connect(String rm, Hashtable rfields,
			String qdata,QueryParam[] qparams)
	throws IOException {
	conn.setRequestMethod(rm);
	// Set the request fields.
	Enumeration e = rfields.keys();
	//System.err.println("--- REQUEST -------------------------------------");
	while (e.hasMoreElements()) {
	    String key = (String)e.nextElement();
	    //System.err.println("key: " + key + ", value: " + (String)rfields.get(key));
	    conn.setRequestProperty(key, (String)rfields.get(key));
	}

//#ifndef j2me
	if (qdata != null || qparams != null) {
	    conn.setDoOutput(true);
	}
	// Only JDK: Calling connect will open the connection
	conn.connect();
//#endif

	if (qdata != null || qparams != null) {
//#ifdef j2me
	    os = conn.openOutputStream();
//#else
	    os = conn.getOutputStream();
//#endif
	    if(qdata != null) {
		//System.err.println("writing " + qdata.getBytes(DEFCHARSET).length + " bytes");
		os.write(qdata.getBytes(/*DEFCHARSET*/));
	    } else if (qparams != null) {
		for(int i=0; i<qparams.length; ++i) {
		    //System.err.print("qparams["+i+"]: ");
		    //qparams[i].printon(System.err).println("");
		    if(i != 0)
			os.write('&');
		    qparams[i].send(os);
		}
	    }
	    os.flush();
	    os.close();
	    os = null;
	}
    }

    int getResponseCode() {
	try {
	    // Only MIDP:
	    // Getting the response code will open the connection,
	    // send the request, and read the HTTP response headers.
	    // The headers are stored until requested.
	    return conn.getResponseCode();
	}
	catch(IOException e) {
	    e.printStackTrace();
	}
	return -1;
    }

    Hashtable readHeader() {
	Hashtable tab = new Hashtable();

	// Getting the response fields.
	int idx = 0;
	// Some implementations may treat the 0th header field as special,
	// i.e. as the status line returned by the HTTP server.
	// In this case, getHeaderField(0) returns the status line,
	// but getHeaderFieldKey(0) returns null.
	// For now, it is not clear if this happens on midlets as well.
//#ifndef j2me
	if (conn.getHeaderFieldKey(0) == null) {
	    ++idx;
	}
//#endif
	//System.err.println("--- RESPONSE HEADER-----------------");
	String key = "";
	while (key != null) {
//#ifdef j2me
	    try {
//#endif
		key = conn.getHeaderFieldKey(idx++);
		if (key != null) {
		    tab.put(key.toLowerCase(), conn.getHeaderField(key));
		    //System.err.println("key: " + key + ", value: " + conn.getHeaderField(key));
		}
//#ifdef j2me
	    }
	    catch (IOException shouldnothappen) {
		shouldnothappen.printStackTrace();
	    }
//#endif
	}
	return tab;
    }

    byte[] readBody() throws IOException {
	int len = 0;
	byte[] buf = new byte[0];

//#ifdef j2me
	is = conn.openInputStream();
	len = (int)conn.getLength();
//#else
	is = conn.getInputStream();
	len = conn.getContentLength();
//#endif

	int bytesread = 0;
	int actual = 0;
	if (len >= 0) {
	    buf = new byte[len];

	    while ((bytesread != len) && (actual != -1)) {
		actual = is.read(buf, bytesread, len - bytesread);
		bytesread += actual;
	    }
	} else {
	    buf = new byte[512];
	    do {
		if(bytesread == buf.length) {
		    byte[] newbuf = new byte[buf.length+512];
		    System.arraycopy(buf,0,newbuf,0,bytesread);
		    buf = newbuf;
		}
		actual = is.read(buf, bytesread, buf.length - bytesread);
		if(actual > 0)
		    bytesread += actual;
	    } while(actual > 0);
	}
	if(bytesread != buf.length) {
	    byte[] tmp = new byte[buf.length];
	    System.arraycopy(buf,0,tmp,0,bytesread);
	    buf = tmp;
	}
	return buf;
    }

    void close() {
	if (os != null) {
	    try {os.close();}
	    catch (IOException e) {}
	}
	if (is != null) {
	    try {is.close();}
	    catch (IOException e) {}
	}
	if (conn != null) {
//#ifdef j2me
	    try {
//#endif
//#ifndef j2me
		conn.disconnect();
//#else
		conn.close();
//#endif
//#ifdef j2me
	    }
	    catch (IOException e) {}
//#endif
	}
    }

//#ifdef j2me
    HttpConnection conn;
//#else
    HttpURLConnection conn;
//#endif
    boolean secure = false;
    InputStream is;
    OutputStream os;
}


text:
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*

8l is a modified version of the Plan 9 linker.  The original is documented at

	http://plan9.bell-labs.com/magic/man2html/1/2l

Its target architecture is the x86, referred to by these tools for historical reasons as 386.
It reads files in .8 format generated by 8g, 8c, and 8a and emits
a binary called 8.out by default.

Major changes include:
	- support for ELF and Mach-O binary files
	- support for segmented stacks (this feature is implemented here, not in the compilers).

Original options are listed in the link above.

Options new in this version:

-d
	Elide the dynamic linking header.  With this option, the binary
	is statically linked and does not refer to dynld.  Without this option
	(the default), the binary's contents are identical but it is loaded with dynld.
-H6
	Write Apple Mach-O binaries (default when $GOOS is darwin)
-H7
	Write Linux ELF binaries (default when $GOOS is linux)
-L dir1,dir2,..
	Search for libraries (package files) in the comma-separated list of directories.
	The default is the single location $GOROOT/pkg/$GOOS_386.

*/
package documentation


text:
// Provides control sap.ui.layout.form.FormContainer.
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Element', 'sap/ui/core/theming/Parameters', 'sap/ui/layout/library'],
	function(jQuery, Element, Parameters, library) {
	"use strict";

	/**
	 * Constructor for a new sap.ui.layout.form.FormContainer.
	 *
	 * @param {string} [sId] ID for the new control, generated automatically if no ID is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * A FormContainer represents a group inside a Form. It consists of FormElements.
	 * The rendering of the FormContainer is done by the FormLayout assigned to the Form.
	 * @extends sap.ui.core.Element
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @since 1.16.0
	 * @alias sap.ui.layout.form.FormContainer
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var FormContainer = Element.extend("sap.ui.layout.form.FormContainer", /** @lends sap.ui.layout.form.FormContainer.prototype */ { metadata : {

		library : "sap.ui.layout",
		properties : {

			/**
			 * Container is expanded.
			 *
			 * Note: This property only works if expandable is set to true.
			 */
			expanded : {type : "boolean", group : "Misc", defaultValue : true},

			/**
			 * Defines if the FormContainer is expandable.
			 *
			 * Note: The expander icon will only be shown if a title is set for the FormContainer.
			 */
			expandable : {type : "boolean", group : "Misc", defaultValue : false},

			/**
			 * If set to false, the FormContainer is not rendered.
			 */
			visible : {type : "boolean", group : "Misc", defaultValue : true}
		},
		defaultAggregation : "formElements",
		aggregations : {

			/**
			 * The FormElements contain the content (labels and fields) of the FormContainers.
			 */
			formElements : {type : "sap.ui.layout.form.FormElement", multiple : true, singularName : "formElement"},

			/**
			 * Title of the FormContainer. Can either be a Title element or a string.
			 * If a Title element is used, the style of the title can be set.
			 *
			 * Note: If a Toolbar is used, the Title is ignored.
			 */
			title : {type : "sap.ui.core.Title", altTypes : ["string"], multiple : false},

			/**
			 * Toolbar of the FormContainer.
			 *
			 * Note: If a Toolbar is used, the Title is ignored.
			 * If a title is needed inside the Toolbar it must be added at content to the Toolbar.
			 * In this case add the Title to the ariaLabelledBy association.
			 * @since 1.36.0
			 */
			toolbar : {type : "sap.ui.core.Toolbar", multiple : false},

			/*
			 * Internal Expand button
			 */
			_expandButton : {type : "sap.ui.core.Control", multiple : false, visibility: "hidden"}
		},
		associations: {

			/**
			 * Association to controls / IDs that label this control (see WAI-ARIA attribute aria-labelledby).
			 *
			 * Note: This attribute is only rendered if the FormContainer has it's own
			 * DOM representation in the used FormLayout.
			 * @since 1.36.0
			 */
			ariaLabelledBy: { type: "sap.ui.core.Control", multiple: true, singularName: "ariaLabelledBy" }
		},
		designtime: "sap/ui/layout/designtime/form/FormContainer.designtime"
	}});

	FormContainer.prototype.init = function(){

		this._rb = sap.ui.getCore().getLibraryResourceBundle("sap.ui.layout");

	};

	FormContainer.prototype.exit = function(){

		if (this._oExpandButton) {
			delete this._oExpandButton;
		}
		this._rb = undefined;

	};

	FormContainer.prototype.setExpandable = function(bExpandable){

		this.setProperty("expandable", bExpandable);

		if (bExpandable) {
			if (!this._oExpandButton) {
				if (!this._bExpandButtonRequired) {
					this._bExpandButtonRequired = true;
					library.form.FormHelper.createButton.call(this, this.getId() + "--Exp", _handleExpButtonPress, _expandButtonCreated);
				}
			} else {
				_setExpanderIcon.call(this);
			}
		}

		return this;

	};

	function _expandButtonCreated(oButton) {

		if (!this._bIsBeingDestroyed) {
			this._oExpandButton = oButton;
			this.setAggregation("_expandButton", this._oExpandButton); // invalidate because this could happen after Form is already rendered
			_setExpanderIcon.call(this);
		}

	}

	FormContainer.prototype.setExpanded = function(bExpanded){

		this.setProperty("expanded", bExpanded, true); // no automatic rerendering

		_setExpanderIcon.call(this);

		var oForm = this.getParent();
		if (oForm && oForm.toggleContainerExpanded) {
			oForm.toggleContainerExpanded(this);
		}

		return this;

	};

	FormContainer.prototype.setToolbar = function(oToolbar) {

		// for sap.m.Toolbar Auto-design must be set to transparent
		oToolbar = library.form.FormHelper.setToolbar.call(this, oToolbar);

		this.setAggregation("toolbar", oToolbar);

		return this;

	};

	/*
	 * If onAfterRendering of a field is processed the Form (layout) might need to change it.
	 */
	FormContainer.prototype.contentOnAfterRendering = function(oFormElement, oControl){

		// call function of parent (if assigned)
		var oParent = this.getParent();
		if (oParent && oParent.contentOnAfterRendering) {
			oParent.contentOnAfterRendering( oFormElement, oControl);
		}

	};

	/*
	 * If LayoutData changed on control this may need changes on the layout. So bubble to the form
	 */
	FormContainer.prototype.onLayoutDataChange = function(oEvent){

		// call function of parent (if assigned)
		var oParent = this.getParent();
		if (oParent && oParent.onLayoutDataChange) {
			oParent.onLayoutDataChange(oEvent);
		}

	};

	/*
	 * Checks if properties are fine
	 * Expander only visible if title is set -> otherwise give warning
	 * @return 0 = no problem, 1 = warning, 2 = error
	 * @private
	 */
	FormContainer.prototype._checkProperties = function(){

		var iReturn = 0;

		if (this.getExpandable() && (!this.getTitle() || this.getToolbar())) {
			jQuery.sap.log.warning("Expander only displayed if title is set", this.getId(), "FormContainer");
			iReturn = 1;
		}

		return iReturn;

	};

	/**
	 * As Elements must not have a DOM reference it is not sure if one exists
	 * If the FormContainer has a DOM representation this function returns it,
	 * independent from the ID of this DOM element
	 * @return {Element} The Element's DOM representation or null
	 * @private
	 */
	FormContainer.prototype.getRenderedDomRef = function(){

		var that = this;
		var oForm = this.getParent();

		if (oForm && oForm.getContainerRenderedDomRef) {
			return oForm.getContainerRenderedDomRef(that);
		}else {
			return null;
		}

	};

	/**
	 * As Elements must not have a DOM reference it is not sure if one exists
	 * If the FormElement has a DOM representation this function returns it,
	 * independent from the ID of this DOM element
	 * @param {sap.ui.layout.form.FormElement} oElement FormElement
	 * @return {Element} The Element's DOM representation or null
	 * @private
	 */
	FormContainer.prototype.getElementRenderedDomRef = function(oElement){

		var oForm = this.getParent();

		if (oForm && oForm.getElementRenderedDomRef) {
			return oForm.getElementRenderedDomRef(oElement);
		}else {
			return null;
		}

	};

	/**
	 * Labels inside of a Form must be invalidated if "editable" changed on Form
	 * @private
	 */
	FormContainer.prototype.invalidateLabels = function(){

		var aFormElements = this.getFormElements();

		for (var i = 0; i < aFormElements.length; i++) {
			var oFormElement = aFormElements[i];
			oFormElement.invalidateLabel();
		}

	};

	/**
	 * Determines if the FormContainer is visible or not. Per default it
	 * just returns the value of the visible property.
	 * But this might be overwritten by inherited elements.
	 *
	 * For rendering by FormLayouts this function has to be used instead of
	 * getVisible.
	 *
	 * @returns {boolean} If true, the FormContainer is visible, otherwise not
	 * @public
	 */
	FormContainer.prototype.isVisible = function(){

		return this.getVisible();

	};

	function _setExpanderIcon(){

		if (!this._oExpandButton) {
			return;
		}

		var sIcon, sIconHovered, sText, sTooltip;

		if (this.getExpanded()) {
			sIcon = Parameters._getThemeImage('_sap_ui_layout_Form_FormContainerColImageURL');
			sIconHovered = Parameters._getThemeImage('_sap_ui_layout_Form_FormContainerColImageDownURL');
			sText = "-";
			sTooltip = this._rb.getText("FORM_COLLAPSE");
		} else {
			sIcon = Parameters._getThemeImage('_sap_ui_layout_Form_FormContainerExpImageURL');
			sIconHovered = Parameters._getThemeImage('_sap_ui_layout_Form_FormContainerExpImageDownURL');
			sText = "+";
			sTooltip = this._rb.getText("FORM_EXPAND");
		}

		if (sIcon) {
			sText = "";
		}

		library.form.FormHelper.setButtonContent(this._oExpandButton, sText, sTooltip, sIcon, sIconHovered);

	}

	function _handleExpButtonPress(oEvent){

		this.setExpanded(!this.getExpanded());

	}

	return FormContainer;

});


text:
var mongo = require('mongodb-wrapper')
  , c = require('../conf.js')
  , settings = c.db;

var db = mongo.db(settings.host, settings.port, settings.database, '', settings.username, settings.password);

module.exports = db;


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

package com.google.devtools.coverageoutputgenerator;

import com.google.common.annotations.VisibleForTesting;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/*
 * Stores coverage information for a specific source file.
 */
class SourceFileCoverage {

  private String sourceFileName;
  private final TreeMap<String, Integer> lineNumbers; // function name to line numbers
  private final TreeMap<String, Integer> functionsExecution; // function name to execution count
  private final TreeMap<Integer, BranchCoverage> branches; // line number to branch
  private final TreeMap<Integer, LineCoverage> lines; // line number to line execution

  SourceFileCoverage(String sourcefile) {
    this.sourceFileName = sourcefile;
    this.functionsExecution = new TreeMap<>();
    this.lineNumbers = new TreeMap<>();
    this.lines = new TreeMap<>();
    this.branches = new TreeMap<>();
  }

  SourceFileCoverage(SourceFileCoverage other) {
    this.sourceFileName = other.sourceFileName;

    this.functionsExecution = new TreeMap<>();
    this.lineNumbers = new TreeMap<>();
    this.lines = new TreeMap<>();
    this.branches = new TreeMap<>();

    this.lineNumbers.putAll(other.lineNumbers);
    this.functionsExecution.putAll(other.functionsExecution);
    this.branches.putAll(other.branches);
    this.lines.putAll(other.lines);
  }

  void changeSourcefileName(String newSourcefileName) {
    this.sourceFileName = newSourcefileName;
  }

  /*
   * Returns the merged functions found in the two given {@code SourceFileCoverage}s.
   */
  @VisibleForTesting
  static TreeMap<String, Integer> mergeLineNumbers(SourceFileCoverage s1, SourceFileCoverage s2) {
    TreeMap<String, Integer> merged = new TreeMap<>();
    merged.putAll(s1.lineNumbers);
    merged.putAll(s2.lineNumbers);
    return merged;
  }

  /*
   *
   * Returns the merged execution count found in the two given {@code SourceFileCoverage}s.
   */
  @VisibleForTesting
  static TreeMap<String, Integer> mergeFunctionsExecution(
      SourceFileCoverage s1, SourceFileCoverage s2) {
    return Stream.of(s1.functionsExecution, s2.functionsExecution)
        .map(Map::entrySet)
        .flatMap(Collection::stream)
        .collect(
            Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Integer::sum, TreeMap::new));
  }

  /*
   *
   * Returns the merged branches found in the two given {@code SourceFileCoverage}s.
   */
  @VisibleForTesting
  static TreeMap<Integer, BranchCoverage> mergeBranches(
      SourceFileCoverage s1, SourceFileCoverage s2) {
    return Stream.of(s1.branches, s2.branches)
        .map(Map::entrySet)
        .flatMap(Collection::stream)
        .collect(
            Collectors.toMap(
                Map.Entry::getKey, Map.Entry::getValue, BranchCoverage::merge, TreeMap::new));
  }

  static int getNumberOfBranchesHit(SourceFileCoverage sourceFileCoverage) {
    return (int)
        sourceFileCoverage.branches.entrySet().stream()
            .filter(branch -> branch.getValue().wasExecuted())
            .count();
  }

  /*
   * Returns the merged line execution found in the two given {@code SourceFileCoverage}s.
   */
  @VisibleForTesting
  static TreeMap<Integer, LineCoverage> mergeLines(SourceFileCoverage s1, SourceFileCoverage s2) {
    return Stream.of(s1.lines, s2.lines)
        .map(Map::entrySet)
        .flatMap(Collection::stream)
        .collect(
            Collectors.toMap(
                Map.Entry::getKey, Map.Entry::getValue, LineCoverage::merge, TreeMap::new));
  }

  private static int getNumberOfExecutedLines(SourceFileCoverage sourceFileCoverage) {
    return (int)
        sourceFileCoverage.lines.entrySet().stream()
            .filter(line -> line.getValue().executionCount() > 0)
            .count();
  }

  /**
   * Merges all the fields of {@code other} with the current {@link SourceFileCoverage} into a new
   * {@link SourceFileCoverage}
   *
   * <p>Assumes both the current and the given {@link SourceFileCoverage} have the same {@code
   * sourceFileName}.
   *
   * @return a new {@link SourceFileCoverage} that contains the merged coverage.
   */
  static SourceFileCoverage merge(SourceFileCoverage source1, SourceFileCoverage source2) {
    assert source1.sourceFileName.equals(source2.sourceFileName);
    SourceFileCoverage merged = new SourceFileCoverage(source2.sourceFileName);

    merged.addAllLineNumbers(mergeLineNumbers(source1, source2));
    merged.addAllFunctionsExecution(mergeFunctionsExecution(source1, source2));
    merged.addAllBranches(mergeBranches(source1, source2));
    merged.addAllLines(mergeLines(source1, source2));
    return merged;
  }

  String sourceFileName() {
    return sourceFileName;
  }

  int nrFunctionsFound() {
    return functionsExecution.size();
  }

  int nrFunctionsHit() {
    return (int)
        functionsExecution.entrySet().stream().filter(function -> function.getValue() > 0).count();
  }

  int nrBranchesFound() {
    return branches.size();
  }

  int nrBranchesHit() {
    return getNumberOfBranchesHit(this);
  }

  int nrOfLinesWithNonZeroExecution() {
    return getNumberOfExecutedLines(this);
  }

  int nrOfInstrumentedLines() {
    return this.lines.size();
  }

  Collection<LineCoverage> getAllLineExecution() {
    return lines.values();
  }

  @VisibleForTesting
  TreeMap<String, Integer> getLineNumbers() {
    return lineNumbers;
  }

  Set<Entry<String, Integer>> getAllLineNumbers() {
    return lineNumbers.entrySet();
  }

  @VisibleForTesting
  TreeMap<String, Integer> getFunctionsExecution() {
    return functionsExecution;
  }

  Set<Entry<String, Integer>> getAllExecutionCount() {
    return functionsExecution.entrySet();
  }

  Collection<BranchCoverage> getAllBranches() {
    return branches.values();
  }

  @VisibleForTesting
  Map<Integer, LineCoverage> getLines() {
    return lines;
  }

  void addLineNumber(String functionName, Integer lineNumber) {
    this.lineNumbers.put(functionName, lineNumber);
  }

  void addAllLineNumbers(TreeMap<String, Integer> lineNumber) {
    this.lineNumbers.putAll(lineNumber);
  }

  void addFunctionExecution(String functionName, Integer executionCount) {
    this.functionsExecution.put(functionName, executionCount);
  }

  void addAllFunctionsExecution(TreeMap<String, Integer> functionsExecution) {
    this.functionsExecution.putAll(functionsExecution);
  }

  void addBranch(Integer lineNumber, BranchCoverage branch) {
    if (this.branches.get(lineNumber) != null) {
      this.branches.put(lineNumber, BranchCoverage.merge(this.branches.get(lineNumber), branch));
      return;
    }
    this.branches.put(lineNumber, branch);
  }

  void addAllBranches(TreeMap<Integer, BranchCoverage> branches) {
    this.branches.putAll(branches);
  }

  void addLine(Integer lineNumber, LineCoverage line) {
    if (this.lines.get(lineNumber) != null) {
      this.lines.put(lineNumber, LineCoverage.merge(line, this.lines.get(lineNumber)));
      return;
    }
    this.lines.put(lineNumber, line);
  }

  void addAllLines(TreeMap<Integer, LineCoverage> lines) {
    this.lines.putAll(lines);
  }
}


text:
namespace Loxone.Client.Transport.Serialization
{
    using System;
    using System.Text.Json;
    using System.Text.Json.Serialization;

    internal sealed class UuidConverter : JsonConverter<Uuid>
    {
        public override Uuid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            => Uuid.Parse(reader.GetString());

        public override void Write(Utf8JsonWriter writer, Uuid value, JsonSerializerOptions options)
            => writer.WriteStringValue(value.ToString());
    }
}


text:
Pattern: Missing use of `Rails.public_path`

Issue: -

## Description

Favor `Rails.public_path` over `Rails.root` with `'public'`

## Examples

```ruby
# bad
Rails.root.join('public')
Rails.root.join('public/file.pdf')
Rails.root.join('public', 'file.pdf')

# good
Rails.public_path
Rails.public_path.join('file.pdf')
Rails.public_path.join('file.pdf')
```
## Further Reading

* [Rails - Rails/RootPublicPath](https://docs.rubocop.org/rubocop-rails/cops_rails.html#railsrootpublicpath)


text:
import json
from email.utils import parseaddr

from django.contrib import messages
from django.core.urlresolvers import reverse as urlreverse
from django.core.validators import validate_email, ValidationError
from django.db.models import Q, Prefetch
from django.http import HttpResponse, HttpResponseForbidden
from django.shortcuts import render, render_to_response, get_object_or_404, redirect
from django.template import RequestContext

from ietf.doc.models import Document
from ietf.ietfauth.utils import role_required, has_role
from ietf.group.models import Group, Role
from ietf.liaisons.models import (LiaisonStatement,LiaisonStatementEvent,
    LiaisonStatementAttachment)
from ietf.liaisons.utils import (get_person_for_user, can_add_outgoing_liaison,
    can_add_incoming_liaison, can_edit_liaison,can_submit_liaison_required,
    can_add_liaison)
from ietf.liaisons.forms import liaison_form_factory, SearchLiaisonForm, EditAttachmentForm, AddCommentForm
from ietf.liaisons.mails import notify_pending_by_email, send_liaison_by_email
from ietf.liaisons.fields import select2_id_liaison_json
from ietf.name.models import LiaisonStatementTagName

EMAIL_ALIASES = {
    'IETFCHAIR':'The IETF Chair <chair@ietf.org>',
    'IESG':'The IESG <iesg@ietf.org>',
    'IAB':'The IAB <iab@iab.org>',
    'IABCHAIR':'The IAB Chair <iab-chair@iab.org>',
    'IABEXECUTIVEDIRECTOR':'The IAB Executive Director <execd@iab.org>'}

# -------------------------------------------------
# Helper Functions
# -------------------------------------------------
def _can_reply(liaison, user):
    '''Returns true if the user can send a reply to this liaison'''
    if user.is_authenticated():
        person = get_person_for_user(user)
        if has_role(user, "Secretariat"):
            return True
        if liaison.is_outgoing() and Role.objects.filter(group__in=liaison.to_groups.all(),person=person,name='auth'):
            return True
        if not liaison.is_outgoing() and Role.objects.filter(group__in=liaison.from_groups.all(),person=person,name='liaiman'):
            return True
    return False

def _can_take_care(liaison, user):
    '''Returns True if user can take care of awaiting actions associated with this liaison'''
    if not liaison.deadline or liaison.action_taken:
        return False

    if user.is_authenticated():
        if has_role(user, "Secretariat"):
            return True
        else:
            return _find_person_in_emails(liaison, get_person_for_user(user))
    return False

def _find_person_in_emails(liaison, person):
    '''Returns true if person corresponds with any of the email addresses associated
    with this liaison statement'''
    if not person:
        return False

    emails = ','.join(e for e in [liaison.response_contacts, liaison.cc_contacts,
                                  liaison.to_contacts,liaison.technical_contacts] if e)
    for email in emails.split(','):
        name, addr = parseaddr(email)
        try:
            validate_email(addr)
        except ValidationError:
            continue

        if person.email_set.filter(address=addr):
            return True
        elif addr in ('chair@ietf.org', 'iesg@ietf.org') and has_role(person.user, "IETF Chair"):
            return True
        elif addr in ('iab@iab.org', 'iab-chair@iab.org') and has_role(person.user, "IAB Chair"):
            return True
        elif addr in ('execd@iab.org', ) and has_role(person.user, "IAB Executive Director"):
            return True

    return False

def contacts_from_roles(roles):
    '''Returns contact string for given roles'''
    emails = [ u'{} <{}>'.format(r.person.plain_name(),r.email.address) for r in roles ]
    return ','.join(emails)

def get_cc(group):
    '''Returns list of emails to use as CC for group.  Simplified refactor of IETFHierarchy
    get_cc() and get_from_cc()
    '''
    emails = []

    # role based CCs
    if group.acronym in ('ietf','iesg'):
        emails.append(EMAIL_ALIASES['IESG'])
        emails.append(EMAIL_ALIASES['IETFCHAIR'])
    elif group.acronym in ('iab'):
        emails.append(EMAIL_ALIASES['IAB'])
        emails.append(EMAIL_ALIASES['IABCHAIR'])
        emails.append(EMAIL_ALIASES['IABEXECUTIVEDIRECTOR'])
    elif group.type_id == 'area':
        emails.append(EMAIL_ALIASES['IETFCHAIR'])
        ad_roles = group.role_set.filter(name='ad')
        emails.extend([ u'{} <{}>'.format(r.person.plain_name(),r.email.address) for r in ad_roles ])
    elif group.type_id == 'wg':
        ad_roles = group.parent.role_set.filter(name='ad')
        emails.extend([ u'{} <{}>'.format(r.person.plain_name(),r.email.address) for r in ad_roles ])
        chair_roles = group.role_set.filter(name='chair')
        emails.extend([ u'{} <{}>'.format(r.person.plain_name(),r.email.address) for r in chair_roles ])
        if group.list_email:
            emails.append(u'{} Discussion List <{}>'.format(group.name,group.list_email))
    elif group.type_id == 'sdo':
        liaiman_roles = group.role_set.filter(name='liaiman')
        emails.extend([ u'{} <{}>'.format(r.person.plain_name(),r.email.address) for r in liaiman_roles ])

    # explicit CCs
    if group.liaisonstatementgroupcontacts_set.exists() and group.liaisonstatementgroupcontacts_set.first().cc_contacts:
        emails = emails + group.liaisonstatementgroupcontacts_set.first().cc_contacts.split(',')

    return emails

def get_contacts_for_group(group):
    '''Returns default contacts for groups as a comma separated string'''
    contacts = []

    # use explicit default contacts if defined
    if group.liaisonstatementgroupcontacts_set.first():
        contacts.append(group.liaisonstatementgroupcontacts_set.first().contacts)

    # otherwise construct based on group type
    elif group.type_id == 'area':
        roles = group.role_set.filter(name='ad')
        contacts.append(contacts_from_roles(roles))
    elif group.type_id == 'wg':
        roles = group.role_set.filter(name='chair')
        contacts.append(contacts_from_roles(roles))
    elif group.acronym == 'ietf':
        contacts.append(EMAIL_ALIASES['IETFCHAIR'])
    elif group.acronym == 'iab':
        contacts.append(EMAIL_ALIASES['IABCHAIR'])
        contacts.append(EMAIL_ALIASES['IABEXECUTIVEDIRECTOR'])
    elif group.acronym == 'iesg':
        contacts.append(EMAIL_ALIASES['IESG'])

    return ','.join(contacts)

def get_details_tabs(stmt, selected):
    return [
        t + (t[0].lower() == selected.lower(),)
        for t in [
        ('Statement', urlreverse('ietf.liaisons.views.liaison_detail', kwargs={ 'object_id': stmt.pk })),
        ('History', urlreverse('ietf.liaisons.views.liaison_history', kwargs={ 'object_id': stmt.pk }))
    ]]

def needs_approval(group,person):
    '''Returns True if the person does not have authority to send a Liaison Statement
    from group.  For outgoing Liaison Statements only'''
    user = person.user
    if group.acronym in ('ietf','iesg') and has_role(user, 'IETF Chair'):
        return False
    if group.acronym == 'iab' and (has_role(user,'IAB Chair') or has_role(user,'IAB Executive Director')):
        return False
    if group.type_id == 'area' and group.role_set.filter(name='ad',person=person):
        return False
    if group.type_id == 'wg' and group.parent and group.parent.role_set.filter(name='ad',person=person):
        return False
    return True

def normalize_sort(request):
    sort = request.GET.get('sort', "")
    if sort not in ('date', 'deadline', 'title', 'to_groups', 'from_groups'):
        sort = "date"

    # reverse dates
    order_by = "-" + sort if sort in ("date", "deadline") else sort

    return sort, order_by

def post_only(group,person):
    '''Returns true if the user is restricted to post_only (vs. post_and_send) for this
    group.  This is for incoming liaison statements.
    - Secretariat have full access.
    - Authorized Individuals have full access for the group they are associated with
    - Liaison Managers can post only
    '''
    if group.type_id == 'sdo' and ( not(has_role(person.user,"Secretariat") or group.role_set.filter(name='auth',person=person)) ):
        return True
    else:
        return False

# -------------------------------------------------
# Ajax Functions
# -------------------------------------------------
@can_submit_liaison_required
def ajax_get_liaison_info(request):
    '''Returns dictionary of info to update entry form given the groups
    that have been selected
    '''
    person = get_person_for_user(request.user)

    from_groups = request.GET.getlist('from_groups', None)
    if not any(from_groups):
        from_groups = []
    to_groups = request.GET.getlist('to_groups', None)
    if not any(to_groups):
        to_groups = []
    from_groups = [ Group.objects.get(id=id) for id in from_groups ]
    to_groups = [ Group.objects.get(id=id) for id in to_groups ]

    cc = []
    does_need_approval = []
    can_post_only = []
    to_contacts = []
    response_contacts = []
    result = {'response_contacts':[],'to_contacts': [], 'cc': [], 'needs_approval': False, 'post_only': False, 'full_list': []}

    for group in from_groups:
        cc.extend(get_cc(group))
        does_need_approval.append(needs_approval(group,person))
        can_post_only.append(post_only(group,person))
        response_contacts.append(get_contacts_for_group(group))

    for group in to_groups:
        cc.extend(get_cc(group))
        to_contacts.append(get_contacts_for_group(group))

    # if there are from_groups and any need approval
    if does_need_approval:
        if  any(does_need_approval):
            does_need_approval = True
        else:
            does_need_approval = False
    else:
        does_need_approval = True

    result.update({'error': False,
                   'cc': list(set(cc)),
                   'response_contacts':list(set(response_contacts)),
                   'to_contacts': list(set(to_contacts)),
                   'needs_approval': does_need_approval,
                   'post_only': any(can_post_only)})

    json_result = json.dumps(result)
    return HttpResponse(json_result, content_type='text/javascript')

def ajax_select2_search_liaison_statements(request):
    query = [w.strip() for w in request.GET.get('q', '').split() if w.strip()]

    if not query:
        objs = LiaisonStatement.objects.none()
    else:
        qs = LiaisonStatement.objects.filter(state='posted')

        for term in query:
            if term.isdigit():
                q = Q(title__icontains=term)|Q(pk=term)
            else:
                q = Q(title__icontains=term)
            qs = qs.filter(q)

        objs = qs.distinct().order_by("-id")[:20]

    return HttpResponse(select2_id_liaison_json(objs), content_type='application/json')

# -------------------------------------------------
# Redirects for backwards compatibility
# -------------------------------------------------

def redirect_add(request):
    """Redirects old add urls"""
    if 'incoming' in request.GET.keys():
        return redirect('ietf.liaisons.views.liaison_add', type='incoming')
    else:
        return redirect('ietf.liaisons.views.liaison_add', type='outgoing')

def redirect_for_approval(request, object_id=None):
    """Redirects old approval urls"""
    if object_id:
        return redirect('ietf.liaisons.views.liaison_detail', object_id=object_id)
    else:
        return redirect('ietf.liaisons.views.liaison_list', state='pending')

# -------------------------------------------------
# View Functions
# -------------------------------------------------
@role_required('Secretariat',)
def add_comment(request, object_id):
    """Add comment to history"""
    statement = get_object_or_404(LiaisonStatement, id=object_id)
    login = request.user.person

    if request.method == 'POST':
        form = AddCommentForm(request.POST)
        if form.is_valid():
            if form.cleaned_data.get('private'):
                type_id = 'private_comment'
            else:
                type_id = 'comment'

            LiaisonStatementEvent.objects.create(
                by=login,
                type_id=type_id,
                statement=statement,
                desc=form.cleaned_data['comment']
            )
            messages.success(request, 'Comment added.')
            return redirect("ietf.liaisons.views.liaison_history", object_id=statement.id)
    else:
        form = AddCommentForm()

    return render(request, 'liaisons/add_comment.html',dict(liaison=statement,form=form))

@can_submit_liaison_required
def liaison_add(request, type=None, **kwargs):
    if type == 'incoming' and not can_add_incoming_liaison(request.user):
        return HttpResponseForbidden("Restricted to users who are authorized to submit incoming liaison statements")
    if type == 'outgoing' and not can_add_outgoing_liaison(request.user):
        return HttpResponseForbidden("Restricted to users who are authorized to submit outgoing liaison statements")

    if request.method == 'POST':
        form = liaison_form_factory(request, data=request.POST.copy(),
                                    files=request.FILES, type=type, **kwargs)

        if form.is_valid():
            liaison = form.save()

            # notifications
            if 'save' in request.POST:
                # the result of an edit, no notifications necessary
                messages.success(request, 'The statement has been updated')
            elif 'send' in request.POST and liaison.state.slug == 'posted':
                send_liaison_by_email(request, liaison)
                messages.success(request, 'The statement has been sent and posted')
            elif liaison.state.slug == 'pending':
                notify_pending_by_email(request, liaison)
                messages.success(request, 'The statement has been submitted and is awaiting approval')

            return redirect('ietf.liaisons.views.liaison_detail', object_id=liaison.pk)

    else:
        form = liaison_form_factory(request,type=type,**kwargs)

    return render_to_response(
        'liaisons/edit.html',
        {'form': form,
         'liaison': kwargs.get('instance')},
        context_instance=RequestContext(request),
    )

def liaison_history(request, object_id):
    """Show the history for a specific liaison statement"""
    liaison = get_object_or_404(LiaisonStatement, id=object_id)
    events = liaison.liaisonstatementevent_set.all().order_by("-time", "-id").select_related("by")
    if not has_role(request.user, "Secretariat"):
        events = events.exclude(type='private_comment')

    return render(request, "liaisons/detail_history.html",  {
        'events':events,
        'liaison': liaison,
        'tabs': get_details_tabs(liaison, 'History'),
        'selected_tab_entry':'history'
    })

def liaison_delete_attachment(request, object_id, attach_id):
    liaison = get_object_or_404(LiaisonStatement, pk=object_id)
    attach = get_object_or_404(LiaisonStatementAttachment, pk=attach_id)
    if not ( request.user.is_authenticated() and can_edit_liaison(request.user, liaison) ):
        return HttpResponseForbidden("You are not authorized for this action")

    attach.removed = True
    attach.save()

    # create event
    LiaisonStatementEvent.objects.create(
        type_id='modified',
        by=get_person_for_user(request.user),
        statement=liaison,
        desc='Attachment Removed: {}'.format(attach.document.title)
    )
    messages.success(request, 'Attachment Deleted')
    return redirect('ietf.liaisons.views.liaison_detail', object_id=liaison.pk)

def liaison_detail(request, object_id):
    liaison = get_object_or_404(LiaisonStatement, pk=object_id)
    can_edit = request.user.is_authenticated() and can_edit_liaison(request.user, liaison)
    can_take_care = _can_take_care(liaison, request.user)
    can_reply = _can_reply(liaison, request.user)
    person = get_person_for_user(request.user)

    if request.method == 'POST':
        if request.POST.get('approved'):
            liaison.change_state(state_id='approved',person=person)
            liaison.change_state(state_id='posted',person=person)
            send_liaison_by_email(request, liaison)
            messages.success(request,'Liaison Statement Approved and Posted')
        elif request.POST.get('dead'):
            liaison.change_state(state_id='dead',person=person)
            messages.success(request,'Liaison Statement Killed')
        elif request.POST.get('resurrect'):
            liaison.change_state(state_id='pending',person=person)
            messages.success(request,'Liaison Statement Resurrected')
        elif request.POST.get('do_action_taken') and can_take_care:
            liaison.tags.remove('required')
            liaison.tags.add('taken')
            can_take_care = False
            messages.success(request,'Action handled')

    relations_by = [i.target for i in liaison.source_of_set.filter(target__state__slug='posted')]
    relations_to = [i.source for i in liaison.target_of_set.filter(source__state__slug='posted')]

    return render_to_response("liaisons/detail.html", {
        "liaison": liaison,
        'tabs': get_details_tabs(liaison, 'Statement'),
        "can_edit": can_edit,
        "can_take_care": can_take_care,
        "can_reply": can_reply,
        "relations_to": relations_to,
        "relations_by": relations_by,
    }, context_instance=RequestContext(request))

def liaison_edit(request, object_id):
    liaison = get_object_or_404(LiaisonStatement, pk=object_id)
    if not (request.user.is_authenticated() and can_edit_liaison(request.user, liaison)):
        return HttpResponseForbidden('You do not have permission to edit this liaison statement')
    return liaison_add(request, instance=liaison)

def liaison_edit_attachment(request, object_id, doc_id):
    '''Edit the Liaison Statement attachment title'''
    liaison = get_object_or_404(LiaisonStatement, pk=object_id)
    doc = get_object_or_404(Document, pk=doc_id)
    if not ( request.user.is_authenticated() and can_edit_liaison(request.user, liaison) ):
        return HttpResponseForbidden("You are not authorized for this action")

    if request.method == 'POST':
        form = EditAttachmentForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            doc.title = title
            doc.save()

            # create event
            LiaisonStatementEvent.objects.create(
                type_id='modified',
                by=get_person_for_user(request.user),
                statement=liaison,
                desc='Attachment Title changed to {}'.format(title)
            )
            messages.success(request,'Attachment title changed')
            return redirect('ietf.liaisons.views.liaison_detail', object_id=liaison.pk)

    else:
        form = EditAttachmentForm(initial={'title':doc.title})

    return render_to_response(
        'liaisons/edit_attachment.html',
        {'form': form,
         'liaison': liaison},
        context_instance=RequestContext(request),
    )

def liaison_list(request, state='posted'):
    """A generic list view with tabs for different states: posted, pending, dead"""
    # use prefetch to speed up main liaison page load
    selected_menu_entry = state
    liaisons = LiaisonStatement.objects.filter(state=state).prefetch_related(
        Prefetch('from_groups',queryset=Group.objects.order_by('acronym').select_related('type'),to_attr='prefetched_from_groups'),
        Prefetch('to_groups',queryset=Group.objects.order_by('acronym').select_related('type'),to_attr='prefetched_to_groups'),
        Prefetch('tags',queryset=LiaisonStatementTagName.objects.filter(slug='taken'),to_attr='prefetched_tags'),
        Prefetch('liaisonstatementevent_set',queryset=LiaisonStatementEvent.objects.filter(type='posted'),to_attr='prefetched_posted_events')
        )

    # check authorization for pending and dead tabs
    if state in ('pending','dead') and not can_add_liaison(request.user):
        msg = "Restricted to participants who are authorized to submit liaison statements on behalf of the various IETF entities"
        return HttpResponseForbidden(msg)

    if 'tags' in request.GET:
        value = request.GET.get('tags')
        liaisons = liaisons.filter(tags__slug=value)
        selected_menu_entry = 'action needed'

    # perform search / filter
    if 'text' in request.GET:
        form = SearchLiaisonForm(data=request.GET,queryset=liaisons)
        search_conducted = True
        if form.is_valid():
            results = form.get_results()
            liaisons = results
    else:
        form = SearchLiaisonForm(queryset=liaisons)
        search_conducted = False

    # perform sort
    sort, order_by = normalize_sort(request)
    if sort == 'date':
        liaisons = sorted(liaisons, key=lambda a: a.sort_date, reverse=True)

    if sort == 'from_groups':
        liaisons = sorted(liaisons, key=lambda a: a.sort_date, reverse=True)
        liaisons = sorted(liaisons, key=lambda a: a.from_groups_display.lower())
    if sort == 'to_groups':
        liaisons = sorted(liaisons, key=lambda a: a.sort_date, reverse=True)
        liaisons = sorted(liaisons, key=lambda a: a.to_groups_display.lower())
    if sort == 'deadline':
        liaisons = liaisons.order_by('-deadline')
    if sort == 'title':
        liaisons = liaisons.order_by('title')

    # add menu entries
    entries = []
    entries.append(("Posted", urlreverse("ietf.liaisons.views.liaison_list", kwargs={'state':'posted'})))
    if can_add_liaison(request.user):
        entries.append(("Action Needed", urlreverse("ietf.liaisons.views.liaison_list", kwargs={'state':'posted'}) + '?tags=required'))
        entries.append(("Pending", urlreverse("ietf.liaisons.views.liaison_list", kwargs={'state':'pending'})))
        entries.append(("Dead", urlreverse("ietf.liaisons.views.liaison_list", kwargs={'state':'dead'})))

    # add menu actions
    actions = []
    if can_add_incoming_liaison(request.user):
        actions.append(("New incoming liaison", urlreverse("ietf.liaisons.views.liaison_add", kwargs={'type':'incoming'})))
    if can_add_outgoing_liaison(request.user):
        actions.append(("New outgoing liaison", urlreverse("ietf.liaisons.views.liaison_add", kwargs={'type':'outgoing'})))

    return render(request, 'liaisons/liaison_base.html',  {
        'liaisons':liaisons,
        'selected_menu_entry':selected_menu_entry,
        'menu_entries':entries,
        'menu_actions':actions,
        'sort':sort,
        'form':form,
        'with_search':True,
        'search_conducted':search_conducted,
        'state':state,
    })

def liaison_reply(request,object_id):
    '''Returns a new liaison form with initial data to reply to the given liaison'''
    liaison = get_object_or_404(LiaisonStatement, pk=object_id)
    if liaison.is_outgoing():
        reply_type = 'incoming'
    else:
        reply_type = 'outgoing'
    initial = dict(
        to_groups=[ x.pk for x in liaison.from_groups.all() ],
        from_groups=[ x.pk for x in liaison.to_groups.all() ],
        to_contacts=liaison.response_contacts,
        related_to=str(liaison.pk))

    return liaison_add(request,type=reply_type,initial=initial)

@role_required('Secretariat',)
def liaison_resend(request, object_id):
    '''Resend the liaison statement notification email'''
    liaison = get_object_or_404(LiaisonStatement, pk=object_id)
    person = get_person_for_user(request.user)
    send_liaison_by_email(request,liaison)
    LiaisonStatementEvent.objects.create(type_id='resent',by=person,statement=liaison,desc='Statement Resent')
    messages.success(request,'Liaison Statement resent')
    return redirect('ietf.liaisons.views.liaison_list')


text:
require "rake"

Rake::Task.clear
CodeunionApi::Application.load_tasks
Rake::Task["resources:refresh"].invoke


text:
package org.pentaho.di.trans.steps.samplerows;

import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.RangeSet;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.trans.step.BaseStepData;
import org.pentaho.di.trans.step.StepDataInterface;

/**
 * @author Samatar
 * @since 24-jan-2008
 */
public class SampleRowsData extends BaseStepData implements StepDataInterface {

  public RangeSet<Integer> rangeSet;
  public boolean addlineField;
  public RowMetaInterface previousRowMeta;
  public RowMetaInterface outputRowMeta;
  public Object[] outputRow;
  public int NrPrevFields;

  public SampleRowsData() {
    super();
    rangeSet = ImmutableRangeSet.of();
    addlineField = false;
    outputRow = null;
  }

}


text:
(function($) {
    function dbg(msg){window.console && console.log && console.log(msg);}

    function cmsplayer_ready (element, options)
    {
        element.data('cmsplayer.playlist', options.playlist);
        function get_playlist(){
            return element.data('cmsplayer.playlist');
        }
        var playerid = options.playerid;
        var autoplay = options.autoplay;
        var autonext = options.autonext;
        var playItem = 0;
        var playtime = $("#play_time_"+playerid);
        var totaltime =  $("#total_time_"+playerid);
        element.jPlayer("cssId", "play", "player_play_"+playerid)
        .jPlayer("cssId", "pause", "player_pause_"+playerid)
        .jPlayer("cssId", "stop", "player_stop_"+playerid)
        .jPlayer("cssId", "loadBar", "player_progress_load_bar_"+playerid)
        .jPlayer("cssId", "playBar", "player_progress_play_bar_"+playerid)
        .jPlayer("cssId", "volumeMin", "player_volume_min_"+playerid)
        .jPlayer("cssId", "volumeMax", "player_volume_max_"+playerid)
        .jPlayer("cssId", "volumeBar", "player_volume_bar_"+playerid)
        .jPlayer("cssId", "volumeBarValue", "player_volume_bar_value_"+playerid)
        .jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
            var myPlayedTime = new Date(playedTime);
            var ptMin = (myPlayedTime.getUTCMinutes() < 10) ? "0" + myPlayedTime.getUTCMinutes() : myPlayedTime.getUTCMinutes();
            var ptSec = (myPlayedTime.getUTCSeconds() < 10) ? "0" + myPlayedTime.getUTCSeconds() : myPlayedTime.getUTCSeconds();
            playtime.text(ptMin+":"+ptSec);

            var myTotalTime = new Date(totalTime);
            var ttMin = (myTotalTime.getUTCMinutes() < 10) ? "0" + myTotalTime.getUTCMinutes() : myTotalTime.getUTCMinutes();
            var ttSec = (myTotalTime.getUTCSeconds() < 10) ? "0" + myTotalTime.getUTCSeconds() : myTotalTime.getUTCSeconds();
            totaltime.text(ttMin+":"+ttSec);
        }).jPlayer("onSoundComplete", function() {
            element.trigger('cmsplayer_songcomplete', [get_playlist()[playItem]]);
            if(autonext){
                playListNext();
            }
        });

        $("#ctrl_prev_"+playerid).click( function() {
            playListPrev();
            return false;
        });

        $("#ctrl_next_"+playerid).click( function() {
            playListNext();
            return false;
        });

        function displayPlayList() {
            var playlist = get_playlist();
            for (i=0; i < playlist.length; i++) {
                song = playlist[i];
                $("#playlist_item_"+playerid+"_"+i).data("cmsplayer.index", i).hover(
                    function() {
                        if (playItem != $(this).data("cmsplayer.index")) {
                            $(this).addClass("playlist_hover");
                        }
                    },
                    function() {
                        $(this).removeClass("playlist_hover");
                    }
                ).click( function() {
                    var index = $(this).data("cmsplayer.index");
                    playListChange(index);
                });
            }
        }
        element.data('cmsplayer.displayPlayList', displayPlayList);

        function playListInit(autoplay) {
            element.trigger('cmsplayer_init', [get_playlist()[playItem]]);
            if(autoplay) {
                playListChange(playItem);
            } else {
                playListConfig(playItem);
            }
        }
        element.data('cmsplayer.playListInit', playListInit);

        function playListConfig(index) {
            $("#playlist_item_"+playerid+"_"+playItem).removeClass("playlist_current");
            $("#playlist_item_"+playerid+"_"+index).addClass("playlist_current");
            playItem = index;
            var playlist = get_playlist();
            if (playlist[playItem].ogg)
            {
                element.jPlayer("setFile", playlist[playItem].mp3, playlist[playItem].ogg);
            }
            else
            {
                element.jPlayer("setFile", playlist[playItem].mp3);
            }
            element.trigger('cmsplayer_config', [playlist[playItem]]);
        }
        element.data('cmsplayer.playListConfig', playListConfig);

        function playListChange( index ) {
            playListConfig( index );
            element.jPlayer("play");
            element.trigger('cmsplayer_change', [get_playlist()[playItem]]);
        }

        function playListNext() {
            var index = (playItem+1 < get_playlist().length) ? playItem+1 : 0;
            playListChange( index );
        }
        element.data('cmsplayer.playListNext', playListNext);

        function playListPrev() {
            var index = (playItem-1 >= 0) ? playItem-1 : get_playlist().length-1;
            playListChange( index );
        }
        element.data('cmsplayer.playListPrev', playListPrev);

        function init(){
            playItem = 0;
            displayPlayList();
            playListInit(autoplay);
        }
        element.data('cmsplayer.init', init);

        function replacePlaylist(new_playlist){
            element.data('cmsplayer.playlist', new_playlist);
        }
        element.data('cmsplayer.replacePlaylist', replacePlaylist);

        function getPlayItem(){
            return playItem;
        }
        element.data('cmsplayer.getPlayItem', getPlayItem);

        init();
    }
    $.fn.cmsPlayer = function(options) {
        var das = $(this);
        if (typeof options == 'string')
        {
            var args = Array.prototype.slice.call(arguments, 1);
            var func = das.data('cmsplayer.' + options);
            if (func){
                func(args);
            } else {
                das.jPlayer(options, args);
            }
        } else {
            if (!options){
                var options = {};
            }
            $.extend(options, {
                ready: function(){cmsplayer_ready(das, options)}
            });
            var fulloptions = {
                autoplay: true,
                autonext: true
            };
            $.extend(fulloptions, options);
            if (!fulloptions.playerid || !fulloptions.playlist)
            {
                dbg("[CMSPLAYER] ERROR: playerid and playlist *must* be defined!");
                return das;
            }
            $(das).jPlayer(fulloptions);
        }
        return das;
    };
})(jQuery);

document.cmsPlayerLoaded = true;


text:
require File.dirname(__FILE__) + '/spec_helper'

describe "Recaptcha#ajax_with_callback" do
  describe "HTTP" do
    before(:each) do
      @response = dispatch_to(Recaptcha, "ajax_with_callback")
    end

    it "should load script from api url" do
      @response.should have_xpath("//script[@src='http://api.recaptcha.net/js/recaptcha_ajax.js']")
    end

    it "should send element_id ('recaptcha_with_callback')" do
      @response.should have_xpath("//script[contains(., 'Recaptcha.create') and contains(., \"getElementById('recaptcha_with_callback')\")]")
    end

    it "should create options array containing callback value ('test_callback')" do
      @response.should have_xpath("//script[contains(., 'Recaptcha.create') and contains(., 'var options = {\"callback\": test_callback};')]")
    end

    it_should_behave_like "ajax recaptcha"
  end

  describe "HTTPS" do
    before(:each) do
      @response = dispatch_to(Recaptcha, "ajax_with_callback", {}, { "HTTPS" => "on" })
    end

    it "should load script from secure api url" do
      @response.should have_xpath("//script[@src='https://api-secure.recaptcha.net/js/recaptcha_ajax.js']")
    end

    it_should_behave_like "ajax recaptcha"
  end
end