text:
var chai = require('chai');
var expect = chai.expect;
var Promise = require('bluebird');
var knex = require('../db/index');

var scoreMatches = require('../scoreMatches/scoreMatches')(knex);
var matchesController = require('./../../../server/db/dbcontrollers/matchesController')(knex);
var tradesController = require('./../../../server/db/dbcontrollers/tradesController')(knex);

describe('scoreMatches Worker', function () {
  var today = new Date();
  var date = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 14);
  var date_before_start = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1, 14);
  var end_date = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7, 21.5);
  var other_end_date = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 9, 21.5);
  var users = [{
    username: 'EXPERIMENT',
    password: 'ExperimentPassword',
    name: 'experiment1',
    email: 'experiment1@a.com'
  }, {
    username: 'EXPERIMENT2',
    password: 'ExperimentPassword',
    name: 'experiment2',
    email: 'experiment2@a.com'
  }];
  var matches = [
  //solo match
  {
    starting_funds: 100000,
    type: 'solo',
    startdate: date,
    enddate: end_date,
  },
  //active head to head match
  {
    starting_funds: 100000,
    type: 'head',
    startdate: date,
    enddate: end_date,
  },
  //match with different end date
  {
    starting_funds: 100000,
    type: 'head',
    startdate: date,
    enddate: other_end_date,
  }];

  // ============= Setup ============= \\
  before(function (done) {
    //insert users into DB
    knex('users').insert(users, '*')
      .then(function (response) {
        users = response;
      })
      //create a match
      .then(function () {
        var user = users[0];
        return Promise.map(matches, function (match) {
          return matchesController.createMatch(user.u_id, match.starting_funds,
           match.type, match.startdate, match.enddate);
        });
      })
      .then(function (createdMatches) {
        var otherUser = users[1];
        return Promise.map(createdMatches, function (match) {
          if ( match.type === 'head') {
            return knex('matches')
              .where('m_id', '=', match.m_id)
              .update({challengee: otherUser.u_id,
                       status: 'active'
              }, '*')
              .then(function (match) {
                return match[0];
              });
          }
          return knex('matches')
            .where('m_id', '=', match.m_id)
            .update({status: 'active'}, '*')
            .then(function (match) {
              return match[0];
            });
        });
      })
      .then(function (readiedMatches) {
        matches = readiedMatches;
        done();
      });

  });

  // ============= Teardown ============= \\
  after(function (done) {
    //remove trades
    knex('trades')
      .where({
        'match_id': matches[0].m_id
      })
      .orWhere({
        'match_id': matches[1].m_id
      })
      .orWhere({
        'match_id': matches[2].m_id
      }).del()
      //remove matches
      .then(function () {
        return Promise.map(matches, function (match) {
          return knex('matches').where('m_id', match.m_id).del();
        });
      })
      //remove users
      .then(function () {
        return Promise.map(users, function (user) {
          return knex('users').where('email', user.email).del();
        });
      })
      .then(function () {
        done();
      })
      .catch(function (err) {
        console.log(err);
      });

  });

  describe('selectCompletingMatches', function () {
    it('should return all matches that are ending that day', function (done) {

      scoreMatches.selectCompletingMatches(other_end_date)
        .then(function (matches) {
          scoreMatches.selectCompletingMatches(end_date)
          .then(function (otherMatches) {
            expect(matches.length).to.equal(3);
            expect(otherMatches.length).to.equal(2);
            done();
          });
        });
    });

  });

  describe('getPortfolio', function (done) {
    it('should be able to get a user portfolio', function (done) {
      // var user = users[0];
      var match = matches[0];
      var trade = {
        shares: 100,
        symbol: 'FB'
      };

      tradesController.buy(match.creator_id, match.m_id, trade.shares, trade.symbol)
        .then(function (trade) {
          scoreMatches.getPortfolio(match.creator_id, match.m_id)
            .then(function (portfolio) {
              expect(portfolio).to.be.an('object');
              expect(portfolio.stocks.length).to.equal(1);
              expect(portfolio.available_cash).to.be.a('number');
              done();
            });
        });

    });

  });

  describe('determineWinners', function () {
    it('should declare the creator the winner when her portfolio is more valuable', function (done) {
      var match = matches[1];

      var trade = {
        shares: 100,
        symbol: 'FB'
      };

      tradesController.buy(match.creator_id, match.m_id, trade.shares, trade.symbol)
        .then(function (creatorTrade) {
          tradesController.buy(match.challengee, match.m_id, trade.shares * 2, trade.symbol)
          .then(function ( challengeeTrade) {
            scoreMatches.determineWinners([match])
            .then(function (scoredMatches) {
              var scoredMatch = scoredMatches[0];
              expect(scoredMatch.winner).to.equal(match.creator_id);
              done();
            });
          });
        });
    });

    it('should declare the challengee the winner when her portfolio is more valuable', function (done) {
      var match = matches[1];

      var trade = {
        shares: 100,
        symbol: 'FB'
      };

      tradesController.buy(match.creator_id, match.m_id, trade.shares * 5, trade.symbol)
        .then(function (creatorTrade) {
          tradesController.buy(match.challengee, match.m_id, trade.shares, trade.symbol)
          .then(function ( challengeeTrade) {
            scoreMatches.determineWinners([match])
            .then(function (scoredMatches) {
              var scoredMatch = scoredMatches[0];
              expect(scoredMatch.winner).to.equal(match.challengee);
              done();
            });
          });
        });
    });

    it('should declare no winner if there is a tie', function (done) {
      var match = matches[2];

      var trade = {
        shares: 100,
        symbol: 'FB'
      };

      tradesController.buy(match.creator_id, match.m_id, trade.shares, trade.symbol)
        .then(function (creatorTrade) {
          tradesController.buy(match.challengee, match.m_id, trade.shares, trade.symbol)
          .then(function ( challengeeTrade) {
            scoreMatches.determineWinners([match])
            .then(function (scoredMatches) {
              var scoredMatch = scoredMatches[0];
              expect(scoredMatch.winner).to.equal(null);
              done();
            });
          });
        });
    });

  });

  describe('recordWinner', function () {
    it('should update the winner column for the appropriate match', function (done) {
      // var user = users[0];
      var match = matches[1];

      scoreMatches.recordWinner(match.m_id, match.challengee)
        .then(function (scoredMatch) {
          expect(scoredMatch.winner).to.equal(match.challengee);
          done();
        });
    });

  });

});


text:
/**
 * SAML wrapper to make it compatible with hapijs
 */
"use strict";

var Boom = require('boom');

var Saml = require('./saml');

var wrapper = {};

wrapper.authenticate = function(options) {
  var saml = new Saml.SAML(options);

  options.samlFallback = options.samlFallback || 'login-request';

  // Optional verify function.
  // Returns profile as is by default
  options.verifyFunc = options.verifyFunc || function(profile, done) {
    return done(null, profile);
  };

  return function(request, reply) {
    function validateCallback(err, profile, loggedOut) {
      console.log(['debug', 'validateCallback'], profile);

      if (err) {
        return reply(Boom.internal(err));
      }

      if (loggedOut) {
        console.logout();
        if (profile) {
          request.samlLogoutRequest = profile;
          return saml.getLogoutResponseUrl(request, redirectIfSuccess);
        }
        return reply();
      }

      var verified = function (err, user, info) {
        console.log(['debug', 'verified', 'user'], user);
        console.log(['debug', 'verified', 'info'], info);

        if (err) {
          return reply(err);
        }

        if (!user) {
          return reply(Boom.badRequest(info));
        }

        request.auth.session.set(user);
        return reply.redirect('/');
      };

      // Client verification of whether profile is
      // valid or not.
      console.log(['debug', 'pre-verifyFunc'], profile);
      request.info = request.info || {};
      request.info.test = "Testing";
      options.verifyFunc(profile, verified);
    }

    function redirectIfSuccess(err, url) {
      console.log(['debug', 'redirectIfSuccess'], url);

      if (err) {
        return reply(Boom.internal(err));
      } else {
        reply.redirect(url);
      }
    }

    if (request.payload && request.payload.SAMLResponse) {
      console.log(['debug', 'SAMLResponse']);
      saml.validatePostResponse(request.payload, validateCallback);
    } else if (request.payload && request.payload.SAMLRequest) {
      console.log(['debug', 'SAMLRequest']);
      saml.validatePostRequest(request.payload, validateCallback);
    } else {
      console.log(['debug', 'no SAML', 'headers'], request.headers);
      console.log(['debug', 'no SAML', 'info'], request.info);
      console.log(['debug', 'no SAML', 'payload'], request.payload);
      console.log(['debug', 'no SAML', 'auth'], request.auth);
      console.log(['debug', 'no SAML', 'params'], request.params);
      console.log(['debug', 'no SAML', 'body'], request.body);
      var operation = {
        'login-request': 'getAuthorizeUrl',
        'logout-request': 'getLogoutUrl'
      }[options.samlFallback];

      if (!operation) {
        return reply(Boom.internal("No operation"));
      }
      saml[operation](request, redirectIfSuccess);
    }
  };

};

module.exports = wrapper;

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ConnectionManager</title>
<meta name="date" content="2014-12-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

eu.virtuenergy.config

Class ConnectionManager

java.lang.Object

eu.virtuenergy.config.ConnectionManager

public abstract class ConnectionManager
extends java.lang.Object

Provide a configured connection to the MySQL DB

Author:

Jonathan Bowen

Constructor Summary

Constructors

Constructor and Description

ConnectionManager()

Method Summary

Methods

Modifier and Type
Method and Description

static java.sql.Connection
getConnection()

Takes properties from the ConfigFactory

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ConnectionManager

public ConnectionManager()

Method Detail

getConnection

public static java.sql.Connection getConnection()

Takes properties from the ConfigFactory

Returns:

Connection object

See Also:

ConfigFactory

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package info.guardianproject.otr.app.im.engine;

/**
 * Interface for group change events.
 */
public interface GroupListener {
    public static final int ERROR_CREATING_GROUP = -1;
    public static final int ERROR_DELETING_GROUP = -2;
    public static final int ERROR_JOINING_IN_GROUP = -3;
    public static final int ERROR_LEAVING_GROUP = -4;

    /**
     * Called when a chat group was successfully created.
     *
     * @param group the group was created.
     */
    public void onGroupCreated(ChatGroup group);

    /**
     * Called when a chat group was successfully deleted.
     *
     * @param group the group was deleted.
     */
    public void onGroupDeleted(ChatGroup group);

    /**
     * Called on joining in a chat group successfully.
     *
     * @param group the group which was joined into.
     */
    public void onJoinedGroup(ChatGroup group);

    /**
     * Called on leaving a chat group. It may be triggered by the user leaving
     * a group or a server initiated group leaving, e.g. the user got kicked
     * out of the group, the group is deleted, etc.
     *
     * @param group the group has left.
     */
    public void onLeftGroup(ChatGroup group);

    /**
     * Called when an error occurs with a certain group operation.
     *
     * @param errorType the type of the error
     * @param error the error information.
     */
    public void onGroupError(int errorType, String groupName, ImErrorInfo error);
}


text:
package com.groupbyinc.api;

import com.groupbyinc.api.config.ConnectionConfiguration;

/**
 * @internal
 */
public class Bridge extends AbstractBridge {

  public Bridge(String clientKey, String bridgeHost, int bridgePort) {
    this(clientKey, bridgeHost, bridgePort, false);
  }

  public Bridge(String clientKey, String bridgeHost, int bridgePort, boolean secure) {
    this(clientKey, bridgeHost, bridgePort, secure, new ConnectionConfiguration());
  }

  public Bridge(String clientKey, String bridgeHost, int bridgePort, boolean secure, ConnectionConfiguration configuration) {
    this(clientKey, (secure ? HTTPS : HTTP) + bridgeHost + COLON + bridgePort, configuration);
  }

  protected Bridge(String clientKey, String baseUrl) {
    this(clientKey, baseUrl, new ConnectionConfiguration());
  }

  protected Bridge(String clientKey, String baseUrl, ConnectionConfiguration configuration) {
    super(clientKey, baseUrl, configuration);
  }
}


text:
<?php
defined('SYSPATH') or die ('No direct script access.');
/**
 * Model representing Contacts
 */
class Curator_Model extends Auth_User_Model {

	public $headers = array('id', 'username', 'password', 'firstname', 'lastname', 'email', 'icq', 'skype', 'comments');

	protected $primary_val = 'vocative';
	protected $sorting = array('username' => 'asc');

	protected $has_many = array('curator_tokens', 'ratings');
	protected $has_and_belongs_to_many = array('roles');

	public function __construct($id = NULL)
	{
		parent::__construct($id);
	}

	public function __set($key, $value)
	{
		if ($key === 'firstname' or $key === 'lastname')
		{
			// Ensure the name is formatted correctly
			$value = ucwords(strtolower($value));
		}
		parent::__set($key, $value);
	}

	public function __get($column)
	{
		$value = parent::__get($column);
		if ($column == 'vocative')
		{
			$value = $this->firstname.' '.$this->lastname;
		}
		return $value;
	}

	/**
	 * Function check if curator can close final rating for resource
	 * @param $resource_id
	 * @return bool true if curator can close rating
	 */
	public function could_close_rating($resource_id)
	{
		$resource = new Resource_Model($resource_id);
		$is_curated = $resource->is_curated_by($this);
		return $is_curated && $resource->is_ratable();
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
atg.repository (ATG Java API)
</TITLE>

<META NAME="keywords" CONTENT="atg.repository package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

atg.repository

Interfaces

DisplayableItem

MutableRepository

MutableRepositoryItem

NamedQueryView

ParameterSupportQueryBuilder

ParameterSupportView

PropertiesChangedListener

Query

QueryBuilder

QueryExpression

Repository

RepositoryItem

RepositoryItemDescriptor

RepositoryItemGroup

RepositoryView

RepositoryViewContainer

SecuredMutableRepository

SecuredMutableRepositoryItem

SecuredRepository

SecuredRepositoryItem

SecuredRepositoryItemDescriptor

SecuredRepositoryView

SortingConstants

Classes

FilePropertyDescriptor

GroupMembersPropertyDescriptor

ItemDescriptorImpl

MimeTyperPropertyDescriptor

NotEmptyChooserPropertyDescriptor

PropertiesChangedEvent

QueryOptions

RepositoryImpl

RepositoryItemImpl

RepositoryPropertyDescriptor

RepositoryServices

RepositorySorter

RepositoryUtils

RepositoryViewImpl

SortDirective

SortDirectives

Exceptions

ConcurrentUpdateException

DuplicateIdException

RepositoryException

UnsupportedFeatureException


text:
case "$os_platform" in
	Linux)   truffleruby_platform="linux" ;;
	Darwin)  truffleruby_platform="macos" ;;
	*)       fail "Unsupported platform $os_platform" ;;
esac

case "$os_arch" in
	x86_64)  truffleruby_arch="amd64" ;;
	aarch64) truffleruby_arch="aarch64" ;;
	arm64)   truffleruby_arch="aarch64" ;;
	*)       fail "Unsupported platform $os_arch" ;;
esac

ruby_dir_name="truffleruby-$ruby_version-$truffleruby_platform-$truffleruby_arch"
ruby_archive="${ruby_archive:-$ruby_dir_name.tar.gz}"
ruby_mirror="${ruby_mirror:-https://github.com/oracle/truffleruby/releases/download}"
ruby_url="${ruby_url:-$ruby_mirror/vm-$ruby_version/$ruby_archive}"

#
# Install TruffleRuby into $install_dir.
#
function install_ruby()
{
	if [[ "$install_dir" == '/usr/local' ]]; then
		error "Unsupported see https://github.com/oracle/truffleruby/issues/1389"
		return 1
	fi

	log "Installing truffleruby $ruby_version ..."
	copy_into "$src_dir/$ruby_dir_name" "$install_dir" || return $?
}

#
# Post-install tasks.
#
function post_install()
{
	log "Running truffleruby post-install hook ..."
	"$install_dir/lib/truffle/post_install_hook.sh" || return $?
}


text:
/* global module: false */

module.exports = function (grunt) {
    /*  extend the public Grunt API  */
    grunt.extendConfig = function (config) {

        /*  iterate over all config entries (the task configurations)  */
        grunt.util._.forEach(config, function (taskConfig, taskName) {

            /*  iterate over all task entries (the target configurations)  */
            grunt.util._.forEach(taskConfig, function (targetConfig, targetName) {

                /*  merge configuration  */
                if (targetName === "options") {
                    /*  merge the special option configuration in parts
                        (to allow establishing defaults incrementally)
                        into the global Grunt configuration  */
                    grunt.util._.forEach(targetConfig, function (optionValue, optionName) {
                        grunt.config.set([ taskName, targetName, optionName ], optionValue);
                    });
                }
                else {
                    /*  merge the target configuration as a whole
                        into the global Grunt configuration  */
                    grunt.config.set([ taskName, targetName ], targetConfig);
                }
            });
        });
    };
};


text:
ESP-WROVER-KIT V4.1 Getting Started Guide
=========================================

This user guide shows how to get started with the ESP-WROVER-KIT V4.1 development board including description of its functionality and configuration options. For descriptions of other versions of the ESP-WROVER-KIT check :doc:`../hw-reference/index`.

If you would like to start using this board right now, go directly to the :ref:`get-started-esp-wrover-kit-start-development` section.

What You Need
-------------

* 1 × :ref:`ESP-WROVER-KIT V4.1 board <get-started-esp-wrover-kit-v4.1-board-front>`
* 1 x Micro USB 2.0 Cable, Type A to Micro B
* 1 × PC loaded with Windows, Linux or Mac OS

Overview
--------

The ESP-WROVER-KIT is a development board built around the ESP32 and produced by `Espressif <https://espressif.com>`_. This board is compatible with multiple ESP32 modules, including the ESP32-WROOM-32, ESP32-WROVER and ESP32-WROVER-B. The ESP-WROVER-KIT features support for an LCD and a MicroSD card. The I/O pins have been broken out from the ESP32 module for easy extension. The board carries an advanced multi-protocol USB bridge (the FTDI FT2232HL), enabling developers to use JTAG directly to debug the ESP32 through the USB interface. The development board makes secondary development easy and cost-effective.

Functionality Overview
----------------------

The block diagram below illustrates the ESP-WROVER-KIT's main components and their interconnections.

.. figure:: ../../_static/esp32-wrover-kit-block-diagram.png
    :align: center
    :alt: ESP-WROVER-KIT block diagram
    :figclass: align-center

    ESP-WROVER-KIT block diagram

Functional Description
----------------------

The following lists and figures describe the key components, interfaces, and controls of ESP-WROVER-KIT board.

32.768 kHz
    An external precision 32.768 kHz crystal oscillator provides a low-power consumption clock used during Deep-Sleep mode.
FT2232
    The FT2232 chip is a multi-protocol USB-to-serial bridge. Users can control and program the FT2232 chip through the USB interface to establish communication with ESP32. The FT2232 chip also features USB-to-JTAG interface. USB-to-JTAG is available on channel  A of the FT2232, whilst USB-to-serial is on channel B. The embedded FT2232 chip is one of the distinguishing features of the ESP-WROVER-KIT. It enhances users' convenience in terms of application development and debugging. In addition, users need not purchase a JTAG debugger separately, which reduces the development cost, see `ESP-WROVER-KIT V4.1 schematic`_.
0R
    A zero Ohm resistor intended as a placeholder for a current shunt. May be desoldered or replaced with a current shunt to facilitate measurement of current required by ESP32 module depending on power mode.
ESP32-WROVER
    This version of ESP-WROVER-KIT board has ESP-WROVER-B module installed that integrates 64-Mbit PSRAM for flexible extended storage and data processing capabilities. The board can accommodate other versions of ESP modules described under :ref:`esp-wroom-solo-wrover-modules`.

    .. note::

        GPIO16 and GPIO17 are used as the CS and clock signal for PSRAM. To ensure reliable performance, the two GPIOs are not broken out.

Diagnostic LEDs
    Four red LEDs connected to GPIO pins of the FT2232 chip. Intended for future use.
UART
    Serial port: the serial TX/RX signals on the FT2232HL and the ESP32 are broken out to each side of JP2. By default, the two signals are connected with jumpers. To use the ESP32 module serial interface only, the jumpers may be removed and the module can be connected to another external serial device.
SPI
    SPI interface used by ESP32 to access flash and PSRAM memories inside the module. Please note that the voltage level on this interface depends on the module used.
CTS/RTS
    Serial port flow control signals: the pins are not connected to the circuitry by default. To enable them, respective pins of JP14 must be shorted with jumpers.
JTAG
    JTAG interface: the JTAG signals on FT2232HL and ESP32 are broken out to the two sides of JP2. By default, the two signals are disconnected. To enable JTAG, shorting jumpers are required on the signals as shown in section :ref:`get-started-esp-wrover-kit-setup-options`.
USB Port
    USB interface. It functions as the power supply for the board and the communication interface between PC and ESP32 module.
EN Button
    Reset button: pressing this button resets the system.
Boot Button
    Download button: holding down the **Boot** button and pressing the **EN** button initiates the firmware download mode. Then user can download firmware through the serial port.
Power Switch
    Power on/off button: toggling to the right powers the board on; toggling to the left powers the board off.
Power Selector
    Power supply selection interface: the ESP-WROVER-KIT can be powered through the USB interface or the 5V Input interface. The user can select the power supply with a jumper. More details can be found in section :ref:`get-started-esp-wrover-kit-setup-options`, jumper header JP7.
5V Input
    The 5V power supply interface is used as a backup power supply in case of full-load operation.
5V Power On LED
    This red LED indicates that a power supply (either from **USB** or **5V Input**) is applied to the board.
LDO
    NCP1117(1A). 5V-to-3.3V LDO. (There is an alternative pin-compatible LDO — LM317DCY, with an output current of up to 1.5A). NCP1117 can provide a maximum current of 1A. The LDO solutions are available with both fixed output voltage and variable output voltage. For details please refer to `ESP-WROVER-KIT V4.1 schematic`_.
Camera Connector
    Camera interface: a standard OV7670 camera module is supported.
RGB LED
    Red, green and blue (RGB) light emitting diodes (LEDs), which may be controlled by pulse width modulation (PWM).
I/O Connector
    All the pins on the ESP32 module are led out to the pin headers on the ESP-WROVER-KIT. Users can program ESP32 to enable multiple functions such as PWM, ADC, DAC, I2C, I2S, SPI, etc.
Micro SD Card Slot
    Develop applications that access Micro SD card for data storage and retrieval.
LCD
    ESP-WROVER-KIT supports mounting and interfacing a 3.2" SPI (standard 4-wire Serial Peripheral Interface) LCD, as shown on figure :ref:`get-started-esp-wrover-kit-v4.1-board-back`.

.. _get-started-esp-wrover-kit-v4.1-board-front:

.. figure:: ../../_static/esp-wrover-kit-v4.1-layout-front.png
    :align: center
    :alt: ESP-WROVER-KIT board layout - front
    :figclass: align-center

    ESP-WROVER-KIT board layout - front

.. _get-started-esp-wrover-kit-v4.1-board-back:

.. figure:: ../../_static/esp-wrover-kit-v4.1-layout-back.png
    :align: center
    :alt: ESP-WROVER-KIT board layout - back
    :figclass: align-center

    ESP-WROVER-KIT board layout - back

.. _get-started-esp-wrover-kit-setup-options:

Setup Options
-------------

There are three jumper headers available to set up the board functionality. Typical options to select from are listed in table below.

+--------+------------------+--------------------------------------------------+
| Header | Jumper Setting   | Description of Functionality                     |
+--------+------------------+--------------------------------------------------+
|  JP7   | |jp7-ext_5v|     | Power ESP-WROVER-KIT board from an external      |
|        |                  | power supply                                     |
+--------+------------------+--------------------------------------------------+
|  JP7   | |jp7-usb_5v|     | Power ESP-WROVER-KIT board from an USB port      |
+--------+------------------+--------------------------------------------------+
|  JP2   | |jp2-jtag|       | Enable JTAG functionality                        |
+--------+------------------+--------------------------------------------------+
|  JP2   | |jp2-tx-rx|      | Enable UART communication                        |
+--------+------------------+--------------------------------------------------+
|  JP14  | |jp14|           | Enable RTS/CTS flow control for serial           |
|        |                  | communication                                    |
+--------+------------------+--------------------------------------------------+

Allocation of ESP32 Pins
------------------------

Several pins / terminals of ESP32 module are allocated to the on board hardware. Some of them, like GPIO0 or GPIO2, have multiple functions. If certain hardware is not installed, e.g. nothing is plugged in to the Camera / JP4 header, then selected GPIOs may be used for other purposes.

Main I/O Connector / JP1
^^^^^^^^^^^^^^^^^^^^^^^^

The JP1 connector is shown in two columns in the middle under "I/O" headers. The two columns "Shared With" outside, describe where else on the board certain GPIO is used.

+----------------------+------+------+----------------------+
|          Shared With | I/O  | I/O  | Shared With          |
+======================+======+======+======================+
|                      | 3.3V | GND  |                      |
+----------------------+------+------+----------------------+
|              NC/XTAL | IO32 | IO33 | NC/XTAL              |
+----------------------+------+------+----------------------+
|        JTAG, MicroSD | IO12 | IO13 | JTAG, MicroSD        |
+----------------------+------+------+----------------------+
|        JTAG, MicroSD | IO14 | IO27 | Camera               |
+----------------------+------+------+----------------------+
|               Camera | IO26 | IO25 | Camera, LCD          |
+----------------------+------+------+----------------------+
|               Camera | IO35 | IO34 | Camera               |
+----------------------+------+------+----------------------+
|               Camera | IO39 | IO36 | Camera               |
+----------------------+------+------+----------------------+
|                 JTAG | EN   | IO23 | Camera, LCD          |
+----------------------+------+------+----------------------+
|          Camera, LCD | IO22 | IO21 | Camera, LCD, MicroSD |
+----------------------+------+------+----------------------+
|          Camera, LCD | IO19 | IO18 | Camera, LCD          |
+----------------------+------+------+----------------------+
|          Camera, LCD | IO5  | IO17 | PSRAM                |
+----------------------+------+------+----------------------+
|                PSRAM | IO16 | IO4  | LED, Camera, MicroSD |
+----------------------+------+------+----------------------+
|    Camera, LED, Boot | IO0  | IO2  | LED, MicroSD         |
+----------------------+------+------+----------------------+
|        JTAG, MicroSD | IO15 | 5V   |                      |
+----------------------+------+------+----------------------+

Legend:

* NC/XTAL - :ref:`32.768 kHz Oscillator <get-started-esp-wrover-kit-v4.1-xtal>`
* JTAG - :ref:`JTAG / JP8 <get-started-esp-wrover-kit-v4.1-jtag-header>`
* Boot - Boot button / SW2
* Camera - :ref:`Camera / JP4 <get-started-esp-wrover-kit-v4.1-camera-header>`
* LED - :ref:`RGB LED <get-started-esp-wrover-kit-v4.1-rgb-led-connections>`
* MicroSD - :ref:`MicroSD Card / J4 <get-started-esp-wrover-kit-v4.1-microsd-card-slot>`
* LCD - :ref:`LCD / U5 <get-started-esp-wrover-kit-v4.1-lcd-connector>`
* PSRAM - ESP32-WROVER's PSRAM, if ESP32-WROVER is installed

.. _get-started-esp-wrover-kit-v4.1-xtal:

32.768 kHz Oscillator
^^^^^^^^^^^^^^^^^^^^^

+---+-----------+
|   | ESP32 Pin |
+===+===========+
| 1 | GPIO32    |
+---+-----------+
| 2 | GPIO33    |
+---+-----------+

.. note::

    As GPIO32 and GPIO33 are connected to the oscillator, they are not connected to JP1 I/O expansion connector to maintain signal integrity. This allocation may be changed from oscillator to JP1 by desoldering the 0R resistors from positions R11 / R23 and installing them in positions R12 / R24.

.. _get-started-esp-wrover-kit-v4.1-spi-flash-header:

SPI Flash / JP2
^^^^^^^^^^^^^^^

+---+--------------+
|   | ESP32 Pin    |
+===+==============+
| 1 | CLK / GPIO6  |
+---+--------------+
| 2 | SD0 / GPIO7  |
+---+--------------+
| 3 | SD1 / GPIO8  |
+---+--------------+
| 4 | SD2 / GPIO9  |
+---+--------------+
| 5 | SD3 / GPIO10 |
+---+--------------+
| 6 | CMD / GPIO11 |
+---+--------------+

.. important::

    The module's flash bus is connected to the pin header JP2 through 0-Ohm resistors R140 ~ R145. If the flash frequency needs to operate at 80 MHz for reasons such as improving the integrity of bus signals, it is recommended that resistors R140 ~ R145 be desoldered. At this point, the module's flash bus is disconnected with the pin header JP2.

.. _get-started-esp-wrover-kit-v4.1-jtag-header:

JTAG / JP2
^^^^^^^^^^

+---+---------------+-------------+
|   | ESP32 Pin     | JTAG Signal |
+===+===============+=============+
| 1 | EN            | TRST_N      |
+---+---------------+-------------+
| 2 | MTMS / GPIO14 | TMS         |
+---+---------------+-------------+
| 3 | MTDO / GPIO15 | TDO         |
+---+---------------+-------------+
| 4 | MTDI / GPIO12 | TDI         |
+---+---------------+-------------+
| 5 | MTCK / GPIO13 | TCK         |
+---+---------------+-------------+

.. _get-started-esp-wrover-kit-v4.1-camera-header:

Camera / JP4
^^^^^^^^^^^^

+----+--------------+------------------------------+
|    | ESP32 Pin    | Camera Signal                |
+====+==============+==============================+
|  1 | n/a          | 3.3V                         |
+----+--------------+------------------------------+
|  2 | n/a          | Ground                       |
+----+--------------+------------------------------+
|  3 | GPIO27       | SIO_C / SCCB Clock           |
+----+--------------+------------------------------+
|  4 | GPIO26       | SIO_D / SCCB Data            |
+----+--------------+------------------------------+
|  5 | GPIO25       | VSYNC / Vertical Sync        |
+----+--------------+------------------------------+
|  6 | GPIO23       | HREF / Horizontal Reference  |
+----+--------------+------------------------------+
|  7 | GPIO22       | PCLK / Pixel Clock           |
+----+--------------+------------------------------+
|  8 | GPIO21       | XCLK / System Clock          |
+----+--------------+------------------------------+
|  9 | GPIO35       | D7 / Pixel Data Bit 7        |
+----+--------------+------------------------------+
| 10 | GPIO34       | D6 / Pixel Data Bit 6        |
+----+--------------+------------------------------+
| 11 | GPIO39       | D5 / Pixel Data Bit 5        |
+----+--------------+------------------------------+
| 12 | GPIO36       | D4 / Pixel Data Bit 4        |
+----+--------------+------------------------------+
| 13 | GPIO19       | D3 / Pixel Data Bit 3        |
+----+--------------+------------------------------+
| 14 | GPIO18       | D2 / Pixel Data Bit 2        |
+----+--------------+------------------------------+
| 15 | GPIO5        | D1 / Pixel Data Bit 1        |
+----+--------------+------------------------------+
| 16 | GPIO4        | D0 / Pixel Data Bit 0        |
+----+--------------+------------------------------+
| 17 | GPIO0        | RESET / Camera Reset         |
+----+--------------+------------------------------+
| 18 | n/a          | PWDN / Camera Power Down     |
+----+--------------+------------------------------+

* Signals D0 .. D7 denote camera data bus

.. _get-started-esp-wrover-kit-v4.1-rgb-led-connections:

RGB LED
^^^^^^^

+---+-----------+---------+
|   | ESP32 Pin | RGB LED |
+===+===========+=========+
| 1 | GPIO0     | Red     |
+---+-----------+---------+
| 2 | GPIO2     | Green   |
+---+-----------+---------+
| 3 | GPIO4     | Blue    |
+---+-----------+---------+

.. _get-started-esp-wrover-kit-v4.1-microsd-card-slot:

MicroSD Card / J4
^^^^^^^^^^^^^^^^^

+---+---------------+----------------+
|   | ESP32 Pin     | MicroSD Signal |
+===+===============+================+
| 1 | MTDI / GPIO12 | DATA2          |
+---+---------------+----------------+
| 2 | MTCK / GPIO13 | CD / DATA3     |
+---+---------------+----------------+
| 3 | MTDO / GPIO15 | CMD            |
+---+---------------+----------------+
| 4 | MTMS / GPIO14 | CLK            |
+---+---------------+----------------+
| 5 | GPIO2         | DATA0          |
+---+---------------+----------------+
| 6 | GPIO4         | DATA1          |
+---+---------------+----------------+
| 7 | GPIO21        | CD             |
+---+---------------+----------------+

.. _get-started-esp-wrover-kit-v4.1-lcd-connector:

LCD / U5
^^^^^^^^

+---+-----------+------------+
|   | ESP32 Pin | LCD Signal |
+===+===========+============+
| 1 | GPIO18    | RESET      |
+---+-----------+------------+
| 2 | GPIO19    | SCL        |
+---+-----------+------------+
| 3 | GPIO21    | D/C        |
+---+-----------+------------+
| 4 | GPIO22    | CS         |
+---+-----------+------------+
| 5 | GPIO23    | SDA        |
+---+-----------+------------+
| 6 | GPIO25    | SDO        |
+---+-----------+------------+
| 7 | GPIO5     | Backlight  |
+---+-----------+------------+

.. _get-started-esp-wrover-kit-start-development:

Start Application Development
-----------------------------

Before powering up the ESP-WROVER-KIT, please make sure that the board has been received in good condition with no obvious signs of damage.

Initial Setup
^^^^^^^^^^^^^

Select the source of power supply for the board by setting jumper JP7. The options are either **USB** port or an external **5V Input**. For this application, the selection of the USB port is sufficient. Enable UART communication by installing jumpers on JP2. Both selections are shown in table below.

+----------------------+----------------------+
| Power up             | Enable UART          |
| from USB port        | communication        |
+----------------------+----------------------+
| |jp7-usb_5v|         | |jp2-tx-rx|          |
+----------------------+----------------------+

Do not install any other jumpers.

Turn the **Power Switch** on. The **5V Power On LED** should turn on.

Now to Development
^^^^^^^^^^^^^^^^^^

To start development of applications for ESP-WROVER-KIT, proceed to the :doc:`index` section which will walk you through the following steps:

* :ref:`get-started-setup-toolchain` in your PC to develop applications for ESP32 in C language
* :ref:`get-started-connect` the module to the PC and verify if it is accessible
* :ref:`get-started-build-flash` an example application to the ESP32
* :ref:`get-started-build-monitor` instantly what the application is doing

Related Documents
-----------------

* `ESP-WROVER-KIT V4.1 schematic`_ (PDF)
* `ESP32 Datasheet <https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf>`_ (PDF)
* `ESP32-WROVER-B Datasheet <https://espressif.com/sites/default/files/documentation/esp32-wrover-b_datasheet_en.pdf>`_ (PDF)
* :doc:`../api-guides/jtag-debugging/index`
* :doc:`../hw-reference/index`

.. |jp7-ext_5v| image:: ../../_static/esp-wrover-kit-v4.1-jp7-ext_5v.jpg
.. |jp7-usb_5v| image:: ../../_static/esp-wrover-kit-v4.1-jp7-usb_5v.jpg
.. |jp2-jtag| image:: ../../_static/esp-wrover-kit-v4.1-jp2-jtag.jpg
.. |jp2-tx-rx| image:: ../../_static/esp-wrover-kit-v4.1-jp2-tx-rx.jpg
.. |jp14| image:: ../../_static/esp-wrover-kit-v4.1-jp14.jpg

.. _ESP-WROVER-KIT V4.1 schematic: https://dl.espressif.com/dl/schematics/ESP-WROVER-KIT_V4_1.pdf

.. toctree::
    :hidden:

    get-started-wrover-kit-v3.rst
    get-started-wrover-kit-v2.rst


text:
package dpla.ingestion3.mappers.providers

import java.net.URL

import dpla.ingestion3.enrichments.normalizations.StringNormalizationUtils._
import dpla.ingestion3.mappers.utils.{Document, JsonExtractor, MarcXmlMapping}
import dpla.ingestion3.model.DplaMapData._
import dpla.ingestion3.model._
import dpla.ingestion3.utils.{HttpUtils, Utils}
import org.json4s.jackson.JsonMethods._
import org.json4s.JValue
import org.json4s.JsonDSL._

import scala.util.{Success, Try}
import scala.xml._

class HathiMapping extends MarcXmlMapping {

  val isShownAtPrefix: String = "http://catalog.hathitrust.org/Record/"

  override val enforceDataProvider = false;

  // ID minting functions
  override def useProviderName: Boolean = true

  override def getProviderName: Option[String] = Some("hathitrust")

  override def originalId(implicit data: Document[NodeSeq]): ZeroToOne[String] =
    // <controlfield> tag = 001
    controlfield(data, Seq("001"))
      .flatMap(extractStrings)
      .headOption

  // SourceResource mapping

  override def contributor(data: Document[NodeSeq]): ZeroToMany[EdmAgent] =
    // <datafield> tag = 700, 710, 711, or 720
    marcFields(data, Seq("700", "710", "711", "720"))
      .filterNot(filterSubfields(_, Seq("e")) // exclude subfields with @code=e and...
      .flatMap(extractStrings)
      .exists(Seq("aut", "cre").contains(_)) // ...where #text = "aut" or "cre"
    )
      .map(extractStrings)
      .map(_.mkString(" "))
      .map(nameOnlyAgent)

  override def creator(data: Document[NodeSeq]): ZeroToMany[EdmAgent] =
    // <datafield> tag = 100, 110, or 111
    marcFields(data, Seq("100", "110", "111"))
      .map(extractStrings)
      .map(_.mkString(" "))
      .map(nameOnlyAgent)

  override def date(data: Document[NodeSeq]): ZeroToMany[EdmTimeSpan] = {
    // <datafield>    tag = 260   <subfield> code = c
    // <controlfield> tag = 008
    val dDate = marcFields(data, Seq("260"), Seq("c"))
      .flatMap(extractStrings)
      .map(_.cleanupLeadingPunctuation)
      .map(_.cleanupEndingPunctuation)
      .map(_.stripSuffix("."))
      .map(_.stripPrefix("."))
      .map(stringOnlyTimeSpan)

    if (dDate.nonEmpty) dDate // use datafield date if present
    else extractMarcControlDate(data) // else use controlfield date
  }

  override def description(data: Document[NodeSeq]): ZeroToMany[String] =
    // <datafield> tag = any number in the 500s except 538
    marcFields(data, descriptionTags)
      .flatMap(extractStrings)

  override def extent(data: Document[NodeSeq]): ZeroToMany[String] =
    // <datafield> tag = 300 <subfield> code = a or c
    // <datafield> tag = 340 <subfield> code = b
    (marcFields(data, Seq("300"), Seq("a", "c")) ++ marcFields(data, Seq("340"), Seq("b")))
      .map(extractStrings)
      .map(_.mkString(" "))

  override def format(data: Document[NodeSeq]): ZeroToMany[String] = {
    // <leader> #text character at index 6
    // map character to String value in leaderFormats
    val lFormats: Seq[String] = leaderAt(data, 6)
      .flatMap(key => Try{ leaderFormats(key) }.toOption)
      .toSeq

    // <controlfield> code = 007 #text character at index 0
    // map character to String value in controlFormats
    val cFormats: Seq[String] = controlAt(data, "007", 0)
      .flatMap(key => Try{ controlFormats(key) }.toOption)

    // <datafield> tag = 337 or 338            <subfield> code = a
    // <datafield> tag = any from subjectTags  <subfield> code = v
    val dFormats = (marcFields(data, Seq("337", "338"), Seq("a")) ++ marcFields(data, subjectTags, Seq("v")))
        .flatMap(extractStrings)

    (lFormats ++ cFormats ++ dFormats).distinct
  }

  override def identifier(data: Document[NodeSeq]): ZeroToMany[String] = {
    // <datafield>    tag = 050    <subfield> code = a or b   (LC call number)
    // <datafield>    tag = 020    <subfield> code = a        (ISBN)
    // <datafield>    tag = 022    <subfield> code = a        (ISSN)
    // <datafield>    tag = 035    <subfield> code = a
    // <controlfield> tag = 001                               (Hathi)

    val lcIds: Seq[String] = marcFields(data, Seq("050"), Seq("a", "b"))
      .map(extractStrings)
      .map(_.mkString(" "))
      .map("LC call number: " + _)

    val isbnIds: Seq[String] = marcFields(data, Seq("020"), Seq("a"))
      .flatMap(extractStrings)
      .map("ISBN: " + _)

    val issnIds: Seq[String] = marcFields(data, Seq("022"), Seq("a"))
      .flatMap(extractStrings)
      .map("ISSN: " + _)

    val genericIds: Seq[String] = marcFields(data, Seq("035"), Seq("a"))
      .flatMap(extractStrings)

    val hathiIds: Seq[String] = controlfield(data, Seq("001"))
      .flatMap(extractStrings)
      .map("Hathi: " + _)

    lcIds ++ isbnIds ++ issnIds ++ genericIds ++ hathiIds
  }

  override def language(data: Document[NodeSeq]): ZeroToMany[SkosConcept] = {
    // <datafield> tag = 041 <subfield> code = a #text split at every third character
    val dLang: Seq[String] = marcFields(data, Seq("041"), Seq("a"))
      .flatMap(extractStrings)
      .flatMap(_.grouped(3).toList)

    // <controlfield> tag = 008 #text characters 35-37 if #text length > 37
    val controlText: String = controlfield(data, Seq("008")).flatMap(extractStrings).headOption.getOrElse("")

    val cLang: Seq[String] =
      if (controlText.length > 37) Seq(controlText.slice(35,38)) // slice is inclusive on first param, exclusive on second
      else Seq()

    (dLang ++ cLang).map(nameOnlyConcept)
  }

  override def place(data: Document[NodeSeq]): ZeroToMany[DplaPlace] =
    // <datafield> tag = 651                  <subfield> code = a
    // <datafield> tag = any from subjectTags <subfield> code = z
    (marcFields(data, Seq("651"), Seq("a")) ++ marcFields(data, subjectTags, Seq("z")))
      .flatMap(extractStrings)
      .map(_.stripSuffix("."))
      .distinct
      .map(nameOnlyPlace)

  override def publisher(data: Document[NodeSeq]): ZeroToMany[EdmAgent] =
    // <datafield tag=260> <subfield> code = a or b
    marcFields(data, Seq("260"), Seq("a", "b"))
      .map(extractStrings)
      .map(_.mkString(" "))
      .map(nameOnlyAgent)

  override def relation(data: Document[NodeSeq]): ZeroToMany[LiteralOrUri] =
    // <datafield> tag = 760 or 787
    marcFields(data, (760 to 787).map(_.toString))
      .map(extractStrings)
      .map(strings => strings.map(_.stripSuffix(".")))
      .map(_.mkString(". "))
      .map(eitherStringOrUri)

  override def rights(data: Document[NodeSeq]): AtLeastOne[String] =
    // <datafield> tag = 506 or 540
    // <datafield> tag = 974          <subfield> code = r
    (marcFields(data, Seq("974"), Seq("r")) ++ marcFields(data, Seq("506", "540")))
      .flatMap(extractStrings)
      .slice(0,1)
      .flatMap(key => Try{ rightsMapping(key) }.toOption)
      .map(_ + ". Learn more at http://www.hathitrust.org/access_use")

  override def subject(data: Document[NodeSeq]): ZeroToMany[SkosConcept] =
    // <datafield> tag = any from subjectTags <subfield> where code is a letter (not a number)

    datafield(data, subjectTags)
      .map(extractMarcSubject)
      .map(nameOnlyConcept)

  override def temporal(data: Document[NodeSeq]): ZeroToMany[EdmTimeSpan] =
    // <datafield> tag = 648
    // <datafield> tag = any from subjectTags <subfield code=y>
    (marcFields(data, Seq("648")) ++ marcFields(data, subjectTags, Seq("y")))
      .flatMap(extractStrings)
      .map(_.stripEndingPeriod)
      .map(stringOnlyTimeSpan)

  override def title(data: Document[NodeSeq]): ZeroToMany[String] = {
    // <datafield> tag = 245 <subfield> where code != c
    val d1: NodeSeq = datafield(data, Seq("245")).map(n => n \ "subfield")
      .flatMap(nseq => nseq.filterNot(n=> filterAttribute(n, "code", "c")))

    // <datafield> tag = 242 or 240
    val d2: Seq[NodeSeq] = marcFields(data, Seq("242", "240"))

    (d1 +: d2)
      .map(extractStrings)
      .map(_.map(_.cleanupLeadingPunctuation))
      .map(_.map(_.stripEndingPeriod))
      .map(_.mkString(" "))
  }

  override def `type`(data: Document[NodeSeq]): ZeroToMany[String] = {
    // <leader>                     #text characters at index 6 and 7
    // <controlfield> tag = 007_01  #text at index 1
    // <controlfield> tag = 008_21  #text at index 21
    // <datafield>    tag = 970     <subfield> code = a
    // Only map <datafield> if <leader> and <controlfield> have no type value
    val lType = extractMarcLeaderType(data)

    if (lType.isDefined)
      lType.toSeq
    else
      marcFields(data, Seq("970"), Seq("a"))
        .flatMap(extractStrings)
        .flatMap(key => Try{ typeMapping(key) }.toOption)
        .flatMap(_._2)
  }

  // OreAggregation
  override def dplaUri(data: Document[NodeSeq]): ZeroToOne[URI] = mintDplaItemUri(data)

  override def dataProvider(data: Document[NodeSeq]): ZeroToMany[EdmAgent] = {
    // <datafield> tag = 974 <subfield> code = u
    marcFields(data, Seq("974"), Seq("u"))
      .flatMap(extractStrings)
      .flatMap(_.splitAtDelimiter("\\.").slice(0,1)) // split at "." and take first value
      .flatMap(key => Try{ dataProviderMapping(key) }.toOption)
      .map(nameOnlyAgent)
  }

  override def isShownAt(data: Document[NodeSeq]): ZeroToMany[EdmWebResource] =
    // <controlfield> tag = 001
    controlfield(data, Seq("001"))
      .flatMap(extractStrings)
      .map(isShownAtPrefix + _)
      .map(stringOnlyWebResource)

  override def originalRecord(data: Document[NodeSeq]): ExactlyOne[String] = Utils.formatXml(data)

  override def preview(data: Document[NodeSeq]): ZeroToMany[EdmWebResource] = {
    val hathiThumbnailFetcher =
      new HathiThumbnailFetcher(originalId(data), oclcId(data), isbnId(data), googlePrefix(data))

    hathiThumbnailFetcher.thumbnailUrl.toSeq.map(stringOnlyWebResource)
  }

  def oclcId(data: Document[NodeSeq]): Option[String] =
    // <datafield> tag = "035"  <subfield> code = "a"
    marcFields(data, Seq("035"), Seq("a"))
      .flatMap(extractStrings)
      .find(_ contains "(OC")
      .map(_.replaceAll("""\(OCo?LC\)(oc[mn]?)?""", ""))

  def isbnId(data: Document[NodeSeq]): Option[String] =
    // <datafield> tag = "020"  <subfield> code = "a"
    // numerical portion of text, e.g. if #text = "8436305477 (set)" isbnId = "8436305477"
    marcFields(data, Seq("020"), Seq("a"))
      .flatMap(extractStrings)
      .headOption
      .flatMap(_.split(" ").find(_.matches("([0-9]*)")))

  def googlePrefix(data: Document[NodeSeq]): Option[String] =
    // <datafield> tag = "974"  <subfield> code = "u"
    marcFields(data, Seq("974"), Seq("u"))
      .flatMap(extractStrings)
      .map(namespace => {
        // e.g. if namespace = "pst.000061785779", then prefixKey = "pst" and barcode = "000061785779"
        val prefixKey: String = namespace.split("\\.").headOption.getOrElse("")
        lazy val barcode: String = namespace.split("\\.").lastOption.getOrElse("")

        Try {
          // try to match prefixKey to googlePrefixMapping value
          googlePrefixMapping(prefixKey)
        } match {
          // if initial google prefix is "UCAL", use barcode to update prefix
          case Success(p) => if (p == "UCAL") getUcalPrefix(barcode) else p
          case _ => "" // no match
        }
      }).find(_.nonEmpty) // get first prefix

  override def provider(data: Document[NodeSeq]): ExactlyOne[EdmAgent] = agent

  override def sidecar(data: Document[NodeSeq]): JValue =
    ("prehashId" -> buildProviderBaseId()(data)) ~ ("dplaId" -> mintDplaId(data))

  // Helper method
  def agent = EdmAgent(
    name = Some("HathiTrust"),
    uri = Some(URI("http://dp.la/api/contributor/hathi"))
  )

  // <datafield> tags for description
  val descriptionTags: Seq[String] =
    (500 to 599).filterNot(_ == 538).map(_.toString)

  // <datafield> tags for subjects
  private val subjectTags: Seq[String] =
    (Seq(600, 630, 650, 651) ++ (610 to 619) ++ (653 to 658) ++ (690 to 699)).map(_.toString)

  // type and genre mappings, derived from <datafield>
  private val typeMapping: Map[String, (Option[String], Option[String])] = Map(
    "AJ" -> (Some("Journal"), Some("Text")),
    "AN" -> (Some("Newspaper"), Some("Text")),
    "BI" -> (Some("Biography"), Some("Text")),
    "BK" -> (Some("Book"), Some("Text")),
    "CF" -> (Some("Computer File"), Some("Interactive Resource")),
    "CR" -> (Some("CDROM"), Some("Interactive Resource")),
    "CS" -> (Some("Software"), Some("Software")),
    "DI" -> (Some("Dictionaries"), Some("Text")),
    "DR" -> (Some("Directories"), Some("Text")),
    "EN" -> (Some("Encyclopedias"), Some("Text")),
    "HT" -> (Some("HathiTrust"), None),
    "MN" -> (Some("Maps-Atlas"), Some("Image")),
    "MP" -> (Some("Map"), Some("Image")),
    "MS" -> (Some("Musical Score"), Some("Text")),
    "MU" -> (Some("Music"), Some("Text")),
    "MV" -> (Some("Archive"), Some("Collection")),
    "MW" -> (Some("Manuscript"), Some("Text")),
    "MX" -> (Some("Mixed Material"), Some("Collection")),
    "PP" -> (Some("Photograph/Pictorial Works"), Some("Image")),
    "RC" -> (Some("Audio CD"), Some("Sound")),
    "RL" -> (Some("Audio LP"), Some("Sound")),
    "RM" -> (Some("Music"), Some("Sound")),
    "RS" -> (Some("Spoken word"), Some("Sound")),
    "RU" -> (None, Some("Sound")),
    "SE" -> (Some("Serial"), Some("Text")),
    "SX" -> (Some("Serial"), Some("Text")),
    "VB" -> (Some("Video (Blu-ray)"), Some("Moving Image")),
    "VD" -> (Some("Video (DVD)"), Some("Moving Image")),
    "VG" -> (Some("Video Games"), Some("Moving Image")),
    "VH" -> (Some("Video (VHS)"), Some("Moving Image")),
    "VL" -> (Some("Motion Picture"), Some("Moving Image")),
    "VM" -> (Some("Visual Material"), Some("Image")),
    "WM" -> (Some("Microform"), Some("Text")),
    "XC" -> (Some("Conference"), Some("Text")),
    "XS" -> (Some("Statistics"), Some("Text"))
  )

  private val dataProviderMapping: Map[String, String] = Map(
    "bc" -> "Boston College",
    "chi" -> "University of Chicago",
    "coo" -> "Cornell University",
    "dul1" -> "Duke University",
    "gri" -> "Getty Research Institute",
    "hvd" -> "Harvard University",
    "ien" -> "Northwestern University",
    "inu" -> "Indiana University",
    "loc" -> "Library of Congress",
    "mdl" -> "Minnesota Digital Library",
    "mdp" -> "University of Michigan",
    "miua" -> "University of Michigan",
    "miun" -> "University of Michigan",
    "nc01" -> "University of North Carolina",
    "ncs1" -> "North Carolina State University",
    "njp" -> "Princeton University",
    "nnc1" -> "Columbia University",
    "nnc2" -> "Columbia University",
    "nyp" -> "New York Public Library",
    "psia" -> "Penn State University",
    "pst" -> "Penn State University",
    "pur1" -> "Purdue University",
    "pur2" -> "Purdue University",
    "uc1" -> "University of California",
    "uc2" -> "University of California",
    "ucm" -> "Universidad Complutense de Madrid",
    "ufl1" -> "University of Florida",
    "uiug" -> "University of Illinois",
    "uiuo" -> "University of Illinois",
    "umn" -> "University of Minnesota",
    "usu" -> "Utah State University Press",
    "uva" -> "University of Virginia",
    "wu" -> "University of Wisconsin",
    "yale" -> "Yale University"
  )

  private val rightsMapping: Map[String, String] = Map(
    "pd" -> "Public domain",
    "ic-world" -> "In-copyright and permitted as world viewable by the copyright holder",
    "pdus" -> "Public domain only when viewed in the US",
    "cc-by" -> "Creative Commons Attribution license",
    "cc-by-nd" -> "Creative Commons Attribution-NoDerivatives license",
    "cc-by-nc-nd" -> "Creative Commons Attribution-NonCommercial-NoDerivatives license",
    "cc-by-nc" -> "Creative Commons Attribution-NonCommercial license",
    "cc-by-nc-sa" -> "Creative Commons Attribution-NonCommercial-ShareAlike license",
    "cc-by-sa" -> "Creative Commons Attribution-ShareAlike license",
    "cc-zero" -> "Creative Commons Zero license (implies pd)",
    "und-world" -> "undetermined copyright status and permitted as world viewable by the depositor"
  )

  private val googlePrefixMapping: Map[String, String] = Map(
    "chi" -> "CHI",
    "coo" -> "CORNELL",
    "hvd" -> "HARVARD",
    "ien" -> "NWU",
    "inu" -> "IND",
    "mdp" -> "UOM",
    "nnc1" -> "COLUMBIA",
    "nyp" -> "NYPL",
    "pst" -> "PSU",
    "pur1" -> "PURD",
    "uc1" -> "UCAL",
    "ucm" -> "UCM",
    "umn" -> "MINN",
    "uva" -> "UVA",
    "wu" -> "WISC"
  )

  private def getUcalPrefix(barcode: String): String = {
    if (barcode.length == 11 && barcode.startsWith("l")) "UCLA"
    else if (barcode.length == 10) "UCB"
    else if (barcode.length == 14) {
      barcode.slice(1,5) match {
        case "1822" => "UCSD"
        case "1970" => "UCI"
        case "1378" => "UCSF"
        case "2106" => "UCSC"
        case "1205" => "UCSB"
        case "1175" => "UCD"
        case "1158" => "UCLA"
        case "1210" => "UCR"
        case _ => "UCAL"
      }
    } else "UCAL"
  }
}

class HathiThumbnailFetcher(hathiIdOpt: Option[String],
                            oclcIdOpt: Option[String],
                            isbnIdOpt: Option[String],
                            googlePrefixOpt: Option[String]) extends JsonExtractor {

  val baseUrl: String = "http://books.google.com/books?jscmd=viewapi&bibkeys="

  val hathiId: String = hathiIdOpt.getOrElse("")
  val oclcId: String = oclcIdOpt.getOrElse("")
  val isbnId: String = isbnIdOpt.getOrElse("")
  val googlePrefix: String = googlePrefixOpt.getOrElse("")

  // Thumbnail URL request:
  // Base URL: http://books.google.com/books?jscmd=viewapi&bibkeys=<params>
  // Where params are: <google_prefix>:<hathi_id>,OCLC<oclc_id>,ISBN:<isbn>
  // ISBN ID is optional
  val requestUrl: Option[String] = {
    if (hathiId.isEmpty || oclcId.isEmpty || googlePrefix.isEmpty) None
    else {
      val isbnSuffix = if (isbnId.isEmpty) "" else ",ISBN:" + isbnId
      val url = baseUrl + googlePrefix + ":" + hathiId + ",OCLC:" + oclcId + isbnSuffix
      Some(url)
    }
  }

  // Control flow for entire process of constructing request URL, sending request, and processing response.
  val thumbnailUrl: Option[String] = requestUrl
    .flatMap(googleResponse(_).toOption)
    .flatMap(parseResponse(_).toOption)
    .flatMap(extractUrl(_))

  // Make GET request to Google Books
  def googleResponse(requestUrl: String): Try[String] = {
    val userAgent: String = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:20.0) Gecko/20100101 Firefox/20.0"
    val headers: Option[Map[String, String]] = Some(Map("User-agent" -> userAgent))
    HttpUtils.makeGetRequest(new URL(requestUrl), headers)
  }

  // Parse JSON response from Google Books
  def parseResponse(response: String): Try[JValue] = Try {
    val parsable: String = response
      .replace("var _GBSBookInfo = ", "")
      .replace(";", "")
    parse(parsable)
  }

  // Extract thumbnail URL from JSON
  def extractUrl(json: JValue): Option[String] = {
    val root = "OCLC:" + oclcId
    extractString(json \root \ "thumbnail_url")
  }
}


text:
template<class T>
constexpr auto is_member_method = false;

template<class Ret, class C, class... Args>
constexpr auto is_member_method<Ret (C::*)(Args...)> = true;

template<class T>
concept MemberMethod = is_member_method<T>;

template<class Sig, class T>
constexpr auto is_member_method_sig = false;

template<class Ret, class C, class... Args>
constexpr auto is_member_method_sig<Ret(Args...), Ret (C::*)(Args...)> = true;

template<class Sig, class T>
concept MemberMedthodSig = is_member_method_sig<Sig, T>;

template<class Ret, class C, class... Args>
auto memberMethodClass(Ret (C::*)(Args...)) -> C;

template<auto M>
using MemberMethodClass = decltype(memberMethodClass(M));

template<class Ret, class C, class... Args>
auto memberMethodArgsTuple(Ret (C::*)(Args...)) -> std::tuple<std::remove_cvref_t<Args>...>;

template<auto M>
using MemberMethodArgsTuple = decltype(memberMethodArgsTuple(M));

template<class Ret, class C, class... Args>
auto memberMethodClassArgsTuple(Ret (C::*)(Args...))
    -> std::tuple<C *, std::remove_cvref_t<Args>...>;

template<auto M>
using MemberMethodClassArgsTuple = decltype(memberMethodClassArgsTuple(M));

// #include <type_traits>

// struct TC {
//     constexpr int memberMethod(int x) { return x + 5; }
// };

// static_assert(std::is_same_v<MemberMethodClass<&TC::memberMethod>, TC>);

// template<auto M>
// constexpr auto memberCall(TC p, int x) {
//     return (p.*M)(x);
// }

// static_assert(memberCall<&TC::memberMethod>(TC{}, 3) == 8);


text:
                <a href="<?php echo base_url(); ?>admin/news">景区资讯

                景区资讯列表

                <a href="<?php echo base_url(); ?>admin/news/edit/<?php echo $id ?>">编辑景区资讯

 详细信息

                <?php if ($this->session->flashdata('savedResult') == 1): ?>

                        编辑成功

                <?php endif; ?>

                    <form id="frmContent" role="form" method="POST" action="<?php echo base_url(); ?>admin/news/edit/<?php echo $id ? $id : ''; ?>" enctype="multipart/form-data">

                            标题
                            <input name="title" id="txtTitle" type="text" class="form-control" placeholder="标题" value="<?php echo $title ?>">

                            描述
                            <textarea name="description" id="txtDescription" class="form-control" rows="2"><?php echo $description ?></textarea>

                            内容
                            <textarea name="content" id="txtContent" class="form-control" rows="4"><?php echo $content ?></textarea>

                            点击/阅读数
                            <input name="hits" type="text" class="form-control" id="txtHits" placeholder="点击/阅读数" value="<?php echo $hits ?>">

                            推荐

                                    <input name="isRecommended" type="checkbox" <?php echo ($isRecommended == 1 ? "checked" : "") ?>>
                                    是

                            发布时间

                                <input name="publishedTimestamp" type='text' class="form-control" placeholder="发布时间" id="txtPublishedTimestamp"/>

                            状态

                                <select name="status" id="ddlStatus" class="form-control">
                                    <option value="">请选择</option>
                                    <option <?php echo ($status == 1 ? "selected" : "") ?> value="1">激活</option>
                                    <option <?php echo ($status == 2 ? "selected" : "") ?> value="2">未激活</option>
                                </select>

                            封面
                            <input name="coverImage" type="file" id="fileCoverImage" class="upload" data-preview-element-id="imgCoverImage">
                            <img id="imgCoverImage" class="form-control" src="<?php echo ($coverImage ? $coverImage : "http://placehold.it/150x150") ?>" style="margin-top: 3px; width: 150px; height: 150px" alt="coverImage" />

                        <a class="btn btn-primary" href="<?php echo base_url();?>admin/news">

                            返回

                            提交

                    </form>


text:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.connection_string_name">connectionString</property>
    <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="show_sql">true</property>
    <property name="connection.release_mode">auto</property>
    <property name="adonet.batch_size">500</property>
    <property name="default_schema">test.dbo</property>
    <mapping assembly="MassTransit.Tests" />
  </session-factory>
</hibernate-configuration>


text:
#import "CPAnnotation.h"
#import "CPLayer.h"
#import "CPAnnotationHostLayer.h"

/**	@brief An annotation positions a content layer relative to some anchor point.
 *
 *	Annotations can be used to add text or images that are anchored to a feature
 *	of a graph. For example, the graph title is an annotation anchored to the
 *	plot area frame.
 *
 *	@todo More documentation needed
 **/
@implementation CPAnnotation

/**	@property contentLayer
 *	@brief The annotation content.
 **/
@synthesize contentLayer;

/**	@property annotationHostLayer
 *	@brief The host layer for the annotation content.
 **/
@synthesize annotationHostLayer;

/**	@property displacement
 *	@brief The displacement from the layer anchor point.
 **/
@synthesize displacement;

/**	@property contentAnchorPoint
 *	@brief The anchor point for the content layer.
 **/
@synthesize contentAnchorPoint;

/**	@property rotation
 *	@brief The rotation of the label in radians.
 **/
@synthesize rotation;

#pragma mark -
#pragma mark Init/Dealloc

-(id)init
{
    if ( self = [super init] ) {
		annotationHostLayer = nil;
		contentLayer = nil;
        displacement = CGPointZero;
		contentAnchorPoint = CGPointMake(0.5, 0.5);
		rotation = 0.0;
    }
    return self;
}

-(void)dealloc
{
	[contentLayer release];
    [super dealloc];
}

#pragma mark -
#pragma mark Description

-(NSString *)description
{
	return [NSString stringWithFormat:@"<%@ {%@}>", [super description], self.contentLayer];
}

#pragma mark -
#pragma mark Accessors

-(void)setContentLayer:(CPLayer *)newLayer
{
    if ( newLayer != contentLayer ) {
    	[contentLayer removeFromSuperlayer];
        [contentLayer release];
        contentLayer = [newLayer retain];
		if ( contentLayer ) {
			[annotationHostLayer addSublayer:contentLayer];
		}
    }
}

-(void)setAnnotationHostLayer:(CPAnnotationHostLayer *)newLayer
{
    if ( newLayer != annotationHostLayer ) {
    	[contentLayer removeFromSuperlayer];
        annotationHostLayer = newLayer;
		if ( contentLayer ) {
			[annotationHostLayer addSublayer:contentLayer];
		}
    }
}

-(void)setDisplacement:(CGPoint)newDisplacement
{
    if ( !CGPointEqualToPoint(newDisplacement, displacement) ) {
        displacement = newDisplacement;
        [self.contentLayer setNeedsLayout];
    }
}

-(void)setContentAnchorPoint:(CGPoint)newAnchorPoint
{
    if ( !CGPointEqualToPoint(newAnchorPoint, contentAnchorPoint) ) {
        contentAnchorPoint = newAnchorPoint;
        [self.contentLayer setNeedsLayout];
    }
}

-(void)setRotation:(CGFloat)newRotation
{
    if ( newRotation != rotation ) {
        rotation = newRotation;
        [self.contentLayer setNeedsLayout];
    }
}

@end

#pragma mark -
#pragma mark Layout

@implementation CPAnnotation(AbstractMethods)

/**	@brief Positions the content layer relative to its reference anchor.
 *
 *	This method must be overridden by subclasses. The default implementation
 *	does nothing.
 **/
-(void)positionContentLayer
{
	// Do nothing--implementation provided by subclasses
}

@end


text:
.class final Landroid/widget/AbsListView$CheckForTap;
.super Ljava/lang/Object;
.source "AbsListView.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/AbsListView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x12
    name = "CheckForTap"
.end annotation

# instance fields
.field final synthetic this$0:Landroid/widget/AbsListView;

.field x:F

.field y:F

# direct methods
.method private constructor <init>(Landroid/widget/AbsListView;)V
    .locals 0

    iput-object p1, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Landroid/widget/AbsListView;Landroid/widget/AbsListView$CheckForTap;)V
    .locals 0

    invoke-direct {p0, p1}, Landroid/widget/AbsListView$CheckForTap;-><init>(Landroid/widget/AbsListView;)V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 12

    const/4 v11, 0x2

    const/4 v10, 0x1

    const/4 v9, 0x0

    const/4 v8, 0x0

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget v5, v5, Landroid/widget/AbsListView;->mTouchMode:I

    if-nez v5, :cond_4

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iput v10, v5, Landroid/widget/AbsListView;->mTouchMode:I

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget-object v6, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget v6, v6, Landroid/widget/AbsListView;->mMotionPosition:I

    iget-object v7, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget v7, v7, Landroid/widget/AbsListView;->mFirstPosition:I

    sub-int/2addr v6, v7

    invoke-virtual {v5, v6}, Landroid/widget/AbsListView;->getChildAt(I)Landroid/view/View;

    move-result-object v0

    if-eqz v0, :cond_4

    invoke-virtual {v0}, Landroid/view/View;->hasExplicitFocusable()Z

    move-result v5

    xor-int/lit8 v5, v5, 0x1

    if-eqz v5, :cond_4

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-virtual {v5}, Landroid/widget/AbsListView;->getAdapter()Landroid/widget/Adapter;

    move-result-object v5

    if-eqz v5, :cond_4

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget v5, v5, Landroid/widget/AbsListView;->mMotionPosition:I

    if-ltz v5, :cond_4

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-virtual {v5}, Landroid/widget/AbsListView;->getAdapter()Landroid/widget/Adapter;

    move-result-object v5

    check-cast v5, Landroid/widget/ListAdapter;

    iget-object v6, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget v6, v6, Landroid/widget/AbsListView;->mMotionPosition:I

    invoke-interface {v5, v6}, Landroid/widget/ListAdapter;->isEnabled(I)Z

    move-result v5

    if-eqz v5, :cond_4

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iput v9, v5, Landroid/widget/AbsListView;->mLayoutMode:I

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget-boolean v5, v5, Landroid/widget/AbsListView;->mDataChanged:Z

    if-nez v5, :cond_7

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget-object v5, v5, Landroid/widget/AbsListView;->mSweepListAnimator:Lcom/samsung/android/animation/SemSweepListAnimator;

    if-eqz v5, :cond_0

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget-object v5, v5, Landroid/widget/AbsListView;->mSweepListAnimator:Lcom/samsung/android/animation/SemSweepListAnimator;

    invoke-virtual {v5}, Lcom/samsung/android/animation/SemSweepListAnimator;->isSwiping()Z

    move-result v5

    if-eqz v5, :cond_0

    return-void

    :cond_0
    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-static {v5}, Landroid/widget/AbsListView;->-get34(Landroid/widget/AbsListView;)[F

    move-result-object v4

    iget v5, p0, Landroid/widget/AbsListView$CheckForTap;->x:F

    aput v5, v4, v9

    iget v5, p0, Landroid/widget/AbsListView$CheckForTap;->y:F

    aput v5, v4, v10

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-virtual {v5, v4, v0}, Landroid/widget/AbsListView;->transformPointToViewLocal([FLandroid/view/View;)V

    aget v5, v4, v9

    aget v6, v4, v10

    invoke-virtual {v0, v5, v6}, Landroid/view/View;->drawableHotspotChanged(FF)V

    invoke-virtual {v0, v10}, Landroid/view/View;->setPressed(Z)V

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-virtual {v5, v10}, Landroid/widget/AbsListView;->setPressed(Z)V

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-virtual {v5}, Landroid/widget/AbsListView;->layoutChildren()V

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget-object v6, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget v6, v6, Landroid/widget/AbsListView;->mMotionPosition:I

    invoke-virtual {v5, v6, v0}, Landroid/widget/AbsListView;->positionSelector(ILandroid/view/View;)V

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-virtual {v5}, Landroid/widget/AbsListView;->refreshDrawableState()V

    invoke-static {}, Landroid/view/ViewConfiguration;->getLongPressTimeout()I

    move-result v3

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-virtual {v5}, Landroid/widget/AbsListView;->isLongClickable()Z

    move-result v2

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget-object v5, v5, Landroid/widget/AbsListView;->mSelector:Landroid/graphics/drawable/Drawable;

    if-eqz v5, :cond_2

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget-object v5, v5, Landroid/widget/AbsListView;->mSelector:Landroid/graphics/drawable/Drawable;

    invoke-virtual {v5}, Landroid/graphics/drawable/Drawable;->getCurrent()Landroid/graphics/drawable/Drawable;

    move-result-object v1

    if-eqz v1, :cond_1

    instance-of v5, v1, Landroid/graphics/drawable/TransitionDrawable;

    if-eqz v5, :cond_1

    if-eqz v2, :cond_5

    check-cast v1, Landroid/graphics/drawable/TransitionDrawable;

    invoke-virtual {v1, v3}, Landroid/graphics/drawable/TransitionDrawable;->startTransition(I)V

    :cond_1
    :goto_0
    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget-object v5, v5, Landroid/widget/AbsListView;->mSelector:Landroid/graphics/drawable/Drawable;

    iget v6, p0, Landroid/widget/AbsListView$CheckForTap;->x:F

    iget v7, p0, Landroid/widget/AbsListView$CheckForTap;->y:F

    invoke-virtual {v5, v6, v7}, Landroid/graphics/drawable/Drawable;->setHotspot(FF)V

    :cond_2
    if-eqz v2, :cond_6

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-static {v5}, Landroid/widget/AbsListView;->-get24(Landroid/widget/AbsListView;)Landroid/widget/AbsListView$CheckForLongPress;

    move-result-object v5

    if-nez v5, :cond_3

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    new-instance v6, Landroid/widget/AbsListView$CheckForLongPress;

    iget-object v7, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-direct {v6, v7, v8}, Landroid/widget/AbsListView$CheckForLongPress;-><init>(Landroid/widget/AbsListView;Landroid/widget/AbsListView$CheckForLongPress;)V

    invoke-static {v5, v6}, Landroid/widget/AbsListView;->-set7(Landroid/widget/AbsListView;Landroid/widget/AbsListView$CheckForLongPress;)Landroid/widget/AbsListView$CheckForLongPress;

    :cond_3
    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-static {v5}, Landroid/widget/AbsListView;->-get24(Landroid/widget/AbsListView;)Landroid/widget/AbsListView$CheckForLongPress;

    move-result-object v5

    iget v6, p0, Landroid/widget/AbsListView$CheckForTap;->x:F

    iget v7, p0, Landroid/widget/AbsListView$CheckForTap;->y:F

    invoke-static {v5, v6, v7}, Landroid/widget/AbsListView$CheckForLongPress;->-wrap0(Landroid/widget/AbsListView$CheckForLongPress;FF)V

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-static {v5}, Landroid/widget/AbsListView;->-get24(Landroid/widget/AbsListView;)Landroid/widget/AbsListView$CheckForLongPress;

    move-result-object v5

    invoke-virtual {v5}, Landroid/widget/AbsListView$CheckForLongPress;->rememberWindowAttachCount()V

    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iget-object v6, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    invoke-static {v6}, Landroid/widget/AbsListView;->-get24(Landroid/widget/AbsListView;)Landroid/widget/AbsListView$CheckForLongPress;

    move-result-object v6

    int-to-long v8, v3

    invoke-virtual {v5, v6, v8, v9}, Landroid/widget/AbsListView;->postDelayed(Ljava/lang/Runnable;J)Z

    :cond_4
    :goto_1
    return-void

    :cond_5
    check-cast v1, Landroid/graphics/drawable/TransitionDrawable;

    invoke-virtual {v1}, Landroid/graphics/drawable/TransitionDrawable;->resetTransition()V

    goto :goto_0

    :cond_6
    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iput v11, v5, Landroid/widget/AbsListView;->mTouchMode:I

    goto :goto_1

    :cond_7
    iget-object v5, p0, Landroid/widget/AbsListView$CheckForTap;->this$0:Landroid/widget/AbsListView;

    iput v11, v5, Landroid/widget/AbsListView;->mTouchMode:I

    goto :goto_1
.end method


text:
package net.bluemix.connectors.cloudant.config;

import org.ektorp.CouchDbInstance;
import org.springframework.cloud.config.java.AbstractCloudConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class Config {

    @Configuration
    static class CloudConfiguration extends AbstractCloudConfig {

        @Bean
        public CouchDbInstance couchDbInstance() {
            CouchDbInstance instance = connectionFactory().service(CouchDbInstance.class);
            return instance;
        }
    }
}


text:
package org.ihtsdo.otf.rest.client.orchestration;

import org.ihtsdo.otf.rest.client.resty.RestyHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.monoid.json.JSONArray;
import us.monoid.json.JSONException;
import us.monoid.web.JSONResource;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OrchestrationRestClient {

	public static final String ANY_CONTENT_TYPE = "*/*";
	public static final String VALIDATIONS_ENDPOINT = "REST/termserver/validations";

	private final String orchestrationUrl;
	private final RestyHelper resty;
	private final Logger logger = LoggerFactory.getLogger(getClass());

	public OrchestrationRestClient(String orchestrationUrl, String username, String password) {
		this.orchestrationUrl = orchestrationUrl;
		this.resty = new RestyHelper(ANY_CONTENT_TYPE);
		resty.authenticate(orchestrationUrl, username, password.toCharArray());
	}

	public String retrieveValidation(String branchPath) throws Exception {
		final String url = orchestrationUrl + VALIDATIONS_ENDPOINT + "/" + branchPath + "/latest";
		final JSONResource resource = getResource(url);
		if (resource != null) {
			return resource.toObject().toString();
		} else {
			return null;
		}
	}

	public List<String> retrieveValidationStatuses(List<String> branchPaths) throws Exception {
		StringBuilder url = new StringBuilder(orchestrationUrl + VALIDATIONS_ENDPOINT + "/bulk/latest/statuses");
		url.append("?paths=");
		boolean first = true;
		for (String branchPath : branchPaths) {
			if (!first) {
				url.append(",");
			} else {
				first = false;
			}
			url.append(branchPath);
		}
		final JSONResource resource = getResource(url.toString());
		if (resource == null) {
			return null;
		}
		final JSONArray array = resource.array();
		List<String> statuses = new ArrayList<>();
		for (int a = 0; a < array.length(); a++) {
			final String string = array.getString(a);
			statuses.add(!string.equals("null") ? string : null);
		}
		return statuses;
	}

	private JSONResource getResource(String url) throws IOException, JSONException {
		try {
			logger.info("URL '{}'", url);
			final JSONResource json = resty.json(url);
			String httpStatusStr = "Unrecoverable";
			Integer httpStatus = json.getHTTPStatus();
			if (httpStatus != null) {
				httpStatusStr = httpStatus.toString();
			}
			logger.info("URL '{}', response status '{}'", url, httpStatusStr);
			if (httpStatusStr.startsWith("2")) {
				return json;
			}
		} catch (FileNotFoundException e) {
			// Swallowing this. Gulp
		}
		return null;
	}

}


text:
<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;
use Think\Controller;

/**
 * 扩展控制器
 * 用于调度各个扩展的URL访问需求
 */
class AddonsController extends Controller{

    public function _initialize(){
        /* 读取数据库中的配置 */
        $config = S('DB_CONFIG_DATA');
        if(!$config){
            $config = api('Config/lists');
            S('DB_CONFIG_DATA',$config);
        }
        C($config); //添加配置
    }

    protected $addons = null;

    public function execute($_addons = null, $_controller = null, $_action = null){
        if(C('URL_CASE_INSENSITIVE')){
            $_addons = ucfirst(parse_name($_addons, 1));
            $_controller = parse_name($_controller,1);
        }

	    defined ( 'ADDON_PUBLIC_PATH' ) or define ( 'ADDON_PUBLIC_PATH', __ROOT__ . '/Addons/' . $_addons . '/View/default/Public' );
	    defined ( '_ADDONS' ) or define ( '_ADDONS', $_addons );
	    defined ( '_CONTROLLER' ) or define ( '_CONTROLLER', $_controller );
	    defined ( '_ACTION' ) or define ( '_ACTION', $_action );

        $TMPL_PARSE_STRING = C('TMPL_PARSE_STRING');
        $TMPL_PARSE_STRING['__ADDONROOT__'] = __ROOT__ . "/Addons/{$_addons}";
        C('TMPL_PARSE_STRING', $TMPL_PARSE_STRING);

        if(!empty($_addons) && !empty($_controller) && !empty($_action)){
            $Addons = A("Addons://{$_addons}/{$_controller}")->$_action();
        } else {
            $this->error(L('_DAM_'));
        }
    }

	/**
	 * 重写模板显示 调用内置的模板引擎显示方法,
	 *
	 * @access protected
	 * @param string $templateFile
	 *        	指定要调用的模板文件
	 *        	默认为空 由系统自动定位模板文件
	 *        	支持格式: 空, index, UserCenter/index 和 完整的地址
	 * @param string $charset
	 *        	输出编码
	 * @param string $contentType
	 *        	输出类型
	 * @param string $content
	 *        	输出内容
	 * @param string $prefix
	 *        	模板缓存前缀
	 * @return void
	 */
	protected function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
		$templateFile = $this->getAddonTemplate ( $templateFile );
		$this->view->display ( $templateFile, $charset, $contentType, $content, $prefix );
	}
	function getAddonTemplate($templateFile = '') {
		if (file_exists ( $templateFile )) {
			return $templateFile;
		}
		// dump ( $templateFile );
		$oldFile = $templateFile;
		if (empty ( $templateFile )) {
			$templateFile = T ( 'Addons://' . _ADDONS . '@' . _CONTROLLER . '/' . _ACTION );
		} elseif (stripos ( $templateFile, '/Addons/' ) === false && stripos ( $templateFile, THINK_PATH ) === false) {
			if (stripos ( $templateFile, '/' ) === false) { // 如index
				$templateFile = T ( 'Addons://' . _ADDONS . '@' . _CONTROLLER . '/' . $templateFile );
			} elseif (stripos ( $templateFile, '@' ) === false) { // // 如 UserCenter/index
				$templateFile = T ( 'Addons://' . _ADDONS . '@' . $templateFile );
			}
		}

		if (stripos ( $templateFile, '/Addons/' ) !== false && ! file_exists ( $templateFile )) {
			$templateFile = ! empty ( $oldFile ) && stripos ( $oldFile, '/' ) === false ? $oldFile : _ACTION;
		}
		// dump ( $templateFile );//exit;
		return $templateFile;
	}
}


text:
namespace geo {

// This class represents a point on the unit sphere as a pair
// of latitude-longitude coordinates.  Like the rest of the "geometry"
// package, the intent is to represent spherical geometry as a mathematical
// abstraction, so functions that are specifically related to the Earth's
// geometry (e.g. easting/northing conversions) should be put elsewhere.
//
// This class is intended to be copied by value as desired.  It uses
// the default copy constructor and assignment operator.
class S2LatLng {
 public:
  // Constructor.  The latitude and longitude are allowed to be outside
  // the is_valid() range.  However, note that most methods that accept
  // S2LatLngs expect them to be normalized (see Normalized() below).
  inline S2LatLng(S1Angle const& lat, S1Angle const& lng);

  // The default constructor sets the latitude and longitude to zero.  This is
  // mainly useful when declaring arrays, STL containers, etc.
  inline S2LatLng();

  // Convert a direction vector (not necessarily unit length) to an S2LatLng.
  explicit S2LatLng(S2Point const& p);

  // Returns an S2LatLng for which is_valid() will return false.
  inline static S2LatLng Invalid();

  // Convenience functions -- shorter than calling S1Angle::Radians(), etc.
  inline static S2LatLng FromRadians(double lat_radians, double lng_radians);
  inline static S2LatLng FromDegrees(double lat_degrees, double lng_degrees);
  inline static S2LatLng FromE5(int32 lat_e5, int32 lng_e5);
  inline static S2LatLng FromE6(int32 lat_e6, int32 lng_e6);
  inline static S2LatLng FromE7(int32 lat_e7, int32 lng_e7);

  // Convenience functions -- to use when args have been fixed32s in protos.
  //
  // The arguments are static_cast into int32, so very large unsigned values
  // are treated as negative numbers.
  inline static S2LatLng FromUnsignedE6(uint32 lat_e6, uint32 lng_e6);
  inline static S2LatLng FromUnsignedE7(uint32 lat_e7, uint32 lng_e7);

  // Methods to compute the latitude and longitude of a point separately.
  inline static S1Angle Latitude(S2Point const& p);
  inline static S1Angle Longitude(S2Point const& p);

  // Accessor methods.
  S1Angle lat() const { return S1Angle::Radians(coords_[0]); }
  S1Angle lng() const { return S1Angle::Radians(coords_[1]); }
  Vector2_d const& coords() const { return coords_; }

  // Return true if the latitude is between -90 and 90 degrees inclusive
  // and the longitude is between -180 and 180 degrees inclusive.
  inline bool is_valid() const;

  // Clamps the latitude to the range [-90, 90] degrees, and adds or subtracts
  // a multiple of 360 degrees to the longitude if necessary to reduce it to
  // the range [-180, 180].
  S2LatLng Normalized() const;

  // Convert a normalized S2LatLng to the equivalent unit-length vector.
  S2Point ToPoint() const;

  // Return the distance (measured along the surface of the sphere) to the
  // given S2LatLng.  This is mathematically equivalent to:
  //
  //   S1Angle::Radians(ToPoint().Angle(o.ToPoint()))
  //
  // but this implementation is slightly more efficient.  Both S2LatLngs
  // must be normalized.
  S1Angle GetDistance(S2LatLng const& o) const;

  // Simple arithmetic operations for manipulating latitude-longitude pairs.
  // The results are not normalized (see Normalized()).
  friend inline S2LatLng operator+(S2LatLng const& a, S2LatLng const& b);
  friend inline S2LatLng operator-(S2LatLng const& a, S2LatLng const& b);
  friend inline S2LatLng operator*(double m, S2LatLng const& a);
  friend inline S2LatLng operator*(S2LatLng const& a, double m);

  bool operator==(S2LatLng const& o) const { return coords_ == o.coords_; }
  bool operator!=(S2LatLng const& o) const { return coords_ != o.coords_; }
  bool operator<(S2LatLng const& o) const { return coords_ < o.coords_; }
  bool operator>(S2LatLng const& o) const { return coords_ > o.coords_; }
  bool operator<=(S2LatLng const& o) const { return coords_ <= o.coords_; }
  bool operator>=(S2LatLng const& o) const { return coords_ >= o.coords_; }

  bool ApproxEquals(S2LatLng const& o, double max_error = 1e-15) const {
    return coords_.aequal(o.coords_, max_error);
  }

  // Export the latitude and longitude in degrees, separated by a comma.
  // e.g. "94.518000,150.300000"
  std::string ToStringInDegrees() const;
  void ToStringInDegrees(std::string* s) const;

 private:
  // Internal constructor.
  inline S2LatLng(Vector2_d const& _coords) : coords_(_coords) {}

  // This is internal to avoid ambiguity about which units are expected.
  inline S2LatLng(double lat_radians, double lng_radians)
    : coords_(lat_radians, lng_radians) {}

  Vector2_d coords_;
};
DECLARE_POD(S2LatLng);

inline S2LatLng::S2LatLng(S1Angle const& _lat, S1Angle const& _lng)
    : coords_(_lat.radians(), _lng.radians()) {}

inline S2LatLng::S2LatLng() : coords_(0, 0) {}

inline S2LatLng S2LatLng::FromRadians(double lat_radians, double lng_radians) {
  return S2LatLng(lat_radians, lng_radians);
}

inline S2LatLng S2LatLng::FromDegrees(double lat_degrees, double lng_degrees) {
  return S2LatLng(S1Angle::Degrees(lat_degrees), S1Angle::Degrees(lng_degrees));
}

inline S2LatLng S2LatLng::FromE5(int32 lat_e5, int32 lng_e5) {
  return S2LatLng(S1Angle::E5(lat_e5), S1Angle::E5(lng_e5));
}

inline S2LatLng S2LatLng::FromE6(int32 lat_e6, int32 lng_e6) {
  return S2LatLng(S1Angle::E6(lat_e6), S1Angle::E6(lng_e6));
}

inline S2LatLng S2LatLng::FromE7(int32 lat_e7, int32 lng_e7) {
  return S2LatLng(S1Angle::E7(lat_e7), S1Angle::E7(lng_e7));
}

inline S2LatLng S2LatLng::FromUnsignedE6(uint32 lat_e6, uint32 lng_e6) {
  return S2LatLng(S1Angle::UnsignedE6(lat_e6), S1Angle::UnsignedE6(lng_e6));
}

inline S2LatLng S2LatLng::FromUnsignedE7(uint32 lat_e7, uint32 lng_e7) {
  return S2LatLng(S1Angle::UnsignedE7(lat_e7), S1Angle::UnsignedE7(lng_e7));
}

inline S2LatLng S2LatLng::Invalid() {
  // These coordinates are outside the bounds allowed by is_valid().
  return S2LatLng(M_PI, 2 * M_PI);
}

inline S1Angle S2LatLng::Latitude(S2Point const& p) {
  // We use atan2 rather than asin because the input vector is not necessarily
  // unit length, and atan2 is much more accurate than asin near the poles.
  return S1Angle::Radians(atan2(p[2], sqrt(p[0]*p[0] + p[1]*p[1])));
}

inline S1Angle S2LatLng::Longitude(S2Point const& p) {
  // Note that atan2(0, 0) is defined to be zero.
  return S1Angle::Radians(atan2(p[1], p[0]));
}

inline bool S2LatLng::is_valid() const {
  return fabs(lat().radians()) <= M_PI_2 && fabs(lng().radians()) <= M_PI;
}

inline S2LatLng operator+(S2LatLng const& a, S2LatLng const& b) {
  return S2LatLng(a.coords_ + b.coords_);
}

inline S2LatLng operator-(S2LatLng const& a, S2LatLng const& b) {
  return S2LatLng(a.coords_ - b.coords_);
}

inline S2LatLng operator*(double m, S2LatLng const& a) {
  return S2LatLng(m * a.coords_);
}

inline S2LatLng operator*(S2LatLng const& a, double m) {
  return S2LatLng(m * a.coords_);
}

ostream& operator<<(ostream& os, S2LatLng const& ll);

}  // namespace geo

#endif  // UTIL_GEOMETRY_S2LATLNG_H__


text:
var Selectable = function() {

    var select = function(selection) {
        var lastSelected = null;
        selection.on("click", function(d) {
            var node = d3.select(this);
            var selected = !node.classed("selected");

            if (d3.event.ctrlKey && d3.event.shiftKey) {
                if (selected) {
                    lastSelected = lastSelected || d;
                    getrange.call(this, d, lastSelected).classed("selected", true);
                } else {
                    node.classed("selected", selected);
                    lastSelected = lastSelected==d ? null : lastSelected;
                }
            } else if (d3.event.ctrlKey) {
                node.classed("selected", selected);
                if (selected) {
                    lastSelected = d;
                } else if (lastSelected==d) {
                    lastSelected = null;
                }
            } else if (d3.event.shiftKey) {
                selection.classed("selected", false);
                lastSelected = lastSelected || d;
                getrange.call(this, d, lastSelected).classed("selected", true);
            } else {
                if (selection.filter(".selected")[0].length==1) {
                    selection.classed("selected", false);
                    node.classed("selected", selected);
                    lastSelected = selected ? d : null;
                } else {
                    selection.classed("selected", false);
                    node.classed("selected", true);
                    lastSelected = d
                }
            }
            onSelect();
        });

        // Add the Ctrl-A behavior
        var attach = this;
        d3.select("body").on("keyup", function(d) {
            if (d3.event.ctrlKey && d3.event.keyCode==65) {
                var allSelected = selection.filter(function(d) {
                    return !d3.select(this).classed("selected");
                }).empty();
                selection.classed("selected", !allSelected);
                onSelect();
            }
        });
    }

    var getrange = function(a, b) { return [a, b]; };
    var onSelect = function() {};

    select.getrange = function(_) { if (arguments.length==0) return getrange; getrange = _; return select; }
    select.on = function(event, _) {
        if (event!="select") return;
        if (_==null) return onSelect;
        onSelect = _;
        return select;
    }

    return select;
}