text:
//========= Copyright 2014, Valve Corporation, All rights reserved. ===========
//
// Purpose: Helper to display various hmd stats via GUIText
//
//=============================================================================

using UnityEngine;

public class SteamVR_Stats : MonoBehaviour
{
	public GUIText text;

	public Color fadeColor = Color.black;
	public float fadeDuration = 1.0f;

	void Awake()
	{
		if (text == null)
		{
			text = GetComponent<GUIText>();
			text.enabled = false;
		}

		if (fadeDuration > 0)
		{
			SteamVR_Fade.Start(fadeColor, 0);
			SteamVR_Fade.Start(Color.clear, fadeDuration);
		}
	}

	double lastUpdate = 0.0f;

	void Update()
	{
		if (text != null)
		{
			if (Input.GetKeyDown(KeyCode.I))
			{
				text.enabled = !text.enabled;
			}

			if (text.enabled)
			{
				var vr = SteamVR.instance;
				if (vr != null)
				{
					var timing = new Valve.VR.Compositor_FrameTiming();
					timing.size = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(Valve.VR.Compositor_FrameTiming));
					vr.compositor.GetFrameTiming(ref timing, 0);

					var update = timing.frameStart + timing.frameVSync;
					if (update > lastUpdate)
					{
						var framerate = (lastUpdate > 0.0f) ? 1.0f / (update - lastUpdate) : 0.0f;
						lastUpdate = update;
						text.text = string.Format("framerate: {0:N0}\ndropped frames: {1}", framerate, (int)timing.droppedFrames);
					}
					else
					{
						lastUpdate = update;
					}
				}
			}
		}
	}
}


text:
from ..algorithms import *
from branch_generator import *
DEBUG = False
inf = float("infinity")

def turn(player, player_list, wall_list, available_positions, adjacency_list):
    # current game state
    game_state = {}
    game_state['player'] = player
    game_state['wall_list'] = wall_list
    game_state['player_list'] = player_list
    game_state['turn'] = 0

    # bot stupefying
    opponents_walls_counter = 0
    for opponent in player_list:
        if opponent != player:
            opponents_walls_counter += opponent['amount_of_walls']
    if player['amount_of_walls'] != 0:
        if opponents_walls_counter != 0:
            depth = 2
        else:
            depth = 2
    else:
        if opponents_walls_counter != 0:
            depth = 0
        else:
            depth = 6

    # game tree
    index = 0
    game_tree = {}
    root = {index: {'parent': None, 'child': [], 'game_state': game_state, 'expanded': False, 'initial': -inf, 'final': -inf, 'alpha': None, 'beta': None, 'owner': 'max', 'action': None, 'is_node': False}}
    game_tree.update(root)
    # game tree dfs
    level = 0
    stack = [index]
    while stack:
        # get ancestor
        parent = stack[-1]
        #print 'parent: '
        #print parent
        if game_tree[parent]['expanded']:
            stack.pop(-1)
            level -= 1
        else:
            level += 1
        #print 'stack:'
        #print stack
        current_game_state = game_tree[parent]['game_state']
        #print current_game_state
        # owner detector
        if level % len(player_list) == 0:
            owner = 'max'
        else:
            owner = 'min'

        # final branches detection
        if level < depth:
            is_final = False
        else:
            is_final = True

        if not game_tree[parent]['expanded']:
            # brach generator
            if owner == 'max':
                if game_tree[parent]['owner'] == 'min':
                    initial = final = -inf
            elif owner == 'min':
                if game_tree[parent]['owner'] == 'max':
                    initial = final = inf
            if DEBUG:
                print owner
                print game_tree[parent]['owner']

            # in depth params transition
            if parent != 0:
                grandparent = game_tree[parent]['parent']
                alpha = game_tree[grandparent]['alpha']
                beta = game_tree[grandparent]['beta']
                game_tree[parent]['alpha'] = alpha
                game_tree[parent]['beta'] = beta
                if DEBUG:
                    print "in depth params transition"
                    print "from", grandparent, "to", parent
                    print game_tree[grandparent]['owner']
                    print game_tree[parent]['owner']
                    print "alpha:", alpha, "beta:", beta
            else:
                if owner == 'max':
                    if game_tree[parent]['owner'] == 'min':
                        alpha = None
                        beta = game_tree[parent]['initial']
                elif owner == 'min':
                    if game_tree[parent]['owner'] == 'max':
                        alpha = game_tree[parent]['initial']
                        beta = None
            branch = branch_generator(current_game_state, adjacency_list, game_tree[parent]['owner'], game_tree[parent]['alpha'], game_tree[parent]['beta'], is_final, depth)
            #print branch['nodes']
            child_list = []
            weighted_subbranches = []
            for state in branch['nodes']:
                index += 1
                action = state['action']
                value = action['cost']
                #print action
                node_game_state = state['game_state']
                node = {index: {'parent': parent, 'child': [], 'game_state': node_game_state, 'action': action, 'expanded': False, 'initial': initial, 'final': final, 'alpha': alpha, 'beta': beta, 'owner': owner, 'is_node': False}}
                game_tree.update(node)
                #print node
                child_list.append(index)
                if level < depth and abs(value) != inf:
                    weighted_subbranches.append((index, value))
                else:
                    game_tree[index]['is_node'] = True
                    if DEBUG:
                        print 'node:', index, ' termination'
                    if owner == 'max':
                        initial = final = - value
                        #print initial
                        game_tree[index]['initial'] = initial
                        game_tree[index]['final'] = final
                        if game_tree[parent]['owner'] == 'min':
                            if game_tree[parent]['initial'] > final:
                                game_tree[parent]['initial'] = final
                                if final == -inf:
                                    game_tree[parent]['alpha'] = -inf

                    elif owner == 'min':
                        initial = final = value
                        #print initial
                        game_tree[index]['initial'] = initial
                        game_tree[index]['final'] = final
                        if game_tree[parent]['owner'] == 'max':
                            if game_tree[parent]['initial'] < final:
                                game_tree[parent]['initial'] = final
                                if final == inf:
                                    game_tree[parent]['beta'] = final

            game_tree[parent]['child'].extend(child_list)
            game_tree[parent]['expanded'] = True
            if DEBUG:
                print 'subbranches: '
                print weighted_subbranches

            # ordering subbranches by preliminary evaluation
            weighted_subbranches = sorted(weighted_subbranches, key=lambda subbranch: subbranch[1], reverse=True)

            if DEBUG: print weighted_subbranches

            subbranches = [subbranch for (subbranch, weight) in weighted_subbranches]

            # stack forming
            subbranches.reverse()
            stack.extend(subbranches)

        else:
            initial = game_tree[parent]['initial']
            final = initial
            #print 'final: ', final
            game_tree[parent]['final'] = final
            grandparent = game_tree[parent]['parent']
            if parent != 0:
                if DEBUG:
                    print game_tree[parent]['owner']
                    print game_tree[grandparent]['owner']
                game_tree[parent]['action']['cost'] = final
                grandparent = game_tree[parent]['parent']
                initial = game_tree[grandparent]['initial']
                # from depth params transition
                if owner == 'max':
                    #print game_tree[parent]['final']
                    if game_tree[grandparent]['owner'] == 'min':
                        if initial >= final:
                            game_tree[grandparent]['initial'] = final
                            if final != inf:
                                game_tree[grandparent]['alpha'] = final
                            else:
                                game_tree[grandparent]['alpha'] = None
                elif owner == 'min':
                    #print game_tree[parent]['final']
                    if game_tree[grandparent]['owner'] == 'max':
                        if initial < final:
                            game_tree[grandparent]['initial'] = final
                            if final != -inf:
                                game_tree[grandparent]['beta'] = final
                            else:
                                game_tree[grandparent]['beta'] = None

        # branch pruning
        if parent != 0:
            grandparent = game_tree[parent]['parent']
            value = game_tree[parent]['initial']
            alpha = game_tree[parent]['alpha']
            beta = game_tree[parent]['beta']
            if DEBUG:
                print 'owner:', owner
                print 'grandparent owner:', game_tree[grandparent]['owner']
                print 'parent owner:', game_tree[parent]['owner']
                print 'value:', value
                print 'alpha:', alpha
                print 'beta:', beta

            if game_tree[grandparent]['owner'] == 'max':
                #print game_tree[parent]['final']
                if game_tree[parent]['owner'] == 'min':
                    if alpha != None:
                        if value > alpha:
                            if DEBUG:
                                print "alpha pruning"
                                print parent
                                print game_tree[parent]['child']
                                print game_tree[grandparent]['child']
                                print stack
                            for child in game_tree[grandparent]['child']:
                                if DEBUG:
                                    print child, game_tree[child]['expanded']
                                if not game_tree[child]['expanded'] and child in stack:
                                    if DEBUG:
                                        print "pruning node", child
                                    stack.remove(child)
                                    game_tree[grandparent]['child'].remove(child)

            if game_tree[grandparent]['owner'] == 'min':
                #print game_tree[parent]['final']
                if game_tree[parent]['owner'] == 'max':
                    if beta != None:
                        if (value < beta) or (beta == inf):
                            if DEBUG:
                                print "beta pruning"
                                print parent
                                print game_tree[parent]['child']
                                print game_tree[grandparent]['child']
                                print stack
                            for child in game_tree[grandparent]['child']:
                                if DEBUG:
                                    print child, game_tree[child]['expanded']
                                if not game_tree[child]['expanded'] and child in stack:
                                    if DEBUG:
                                        print "pruning node", child
                                    stack.remove(child)
                                    game_tree[grandparent]['child'].remove(child)

        if DEBUG:
            print "debug output. game tree structure."
            sequence = []
            sequence.append(0)
            while sequence:
                node = sequence.pop(0)
                parent = game_tree[node]['parent']
                child_list = game_tree[node]['child']
                initial = game_tree[node]['initial']
                final = game_tree[node]['final']
                alpha = game_tree[node]['alpha']
                beta = game_tree[node]['beta']
                owner = game_tree[node]['owner']
                is_node = game_tree[node]['is_node']
                expanded = game_tree[node]['expanded']
                print "node: %s; expanded: %s, is_node: %s; parent: %s; child: %s; initial: %s; final: %s; alpha: %s; beta: %s; owner: %s;"\
                        %(node, expanded, is_node, parent, child_list, initial, final, alpha, beta, owner)
                #print 'action: ', game_tree[node]['action']
                sequence.extend(child_list)

    # action select
    level = 0
    action_list = []
    #print 'actions: '
    #print 'level: ', level
    #print game_tree[level]['child']
    for child in game_tree[level]['child']:
        action_list.append(game_tree[child]['action'])
        #print game_tree[child]['action']

    action = action_choice_greedy(action_list)

    if action['action_type'] == 'movement':
        (x, y) = action['location']
        player['location'] = (x, y)
    elif action['action_type'] == 'building':
        wall_list.append(action['wall'])
        player['amount_of_walls'] -= 1
    else:
        pass

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package edu.incense.android.datatask.sink;

import android.util.Log;
import edu.incense.android.datatask.Input;
import edu.incense.android.datatask.data.AudioData;
import edu.incense.android.datatask.data.Data;

/**
 * @author mxpxgx
 *
 */
public class AudioSink extends DataSink {
    private final static String TAG = "AudioSink";
    private final static long MAX_TIME_WITHOUT_AUDIO = 2000;
    private long lastDataTime;
    private RawAudioSinkWritter sinkWritter;
    private boolean started;

    /**
     * @param sinkWritter
     */
    public AudioSink(RawAudioSinkWritter sinkWritter) {
        super(sinkWritter, 1);
        this.sinkWritter = sinkWritter;
        lastDataTime = System.currentTimeMillis() + MAX_TIME_WITHOUT_AUDIO; // TODO
                                                                            // not
                                                                            // sure
                                                                            // about
                                                                            // this
                                                                            // addition
        started = false;
    }

    // protected void compute2() {
    // Data latestData = null;
    // for (Input i : inputs) {
    // do {
    // latestData = i.pullData();
    // if (latestData != null) {
    // // Log.d(TAG, "Audio frame received");
    // sink.add(latestData);
    // lastDataTime = System.currentTimeMillis();
    // } else {
    // // Log.d(TAG, "Data NOT added to sink!");
    // }
    // } while (latestData != null);
    // }
    // long timeLength = System.currentTimeMillis() - lastDataTime;
    // // Log.d(TAG, "Comparing: "+timeLength+" >= "+MAX_TIME_WITHOUT_AUDIO);
    // if(sink !=null && sink.size() > 0 && timeLength >=
    // MAX_TIME_WITHOUT_AUDIO){
    // Log.d(TAG, "Sink sent to writter with size: "+sink.size());
    // sinkWritter.writeSink(name, removeSink());
    // }
    // }

    @Override
    protected void compute() {
        try {
            Data latestData = null;
            for (Input i : inputs) {
                latestData = i.pullData();
                if (latestData != null) {
                    if (!started) {
                        sinkWritter.start(name);
                        started = true;
                    }
                    if (started) {
                        // Log.d(TAG, "Audio frame received");
                        sinkWritter.writeFrame((AudioData) latestData);
                        lastDataTime = System.currentTimeMillis();
                    }
                }
            }
            long timeLength = System.currentTimeMillis() - lastDataTime;
            // Log.d(TAG,
            // "Comparing: "+timeLength+" >= "+MAX_TIME_WITHOUT_AUDIO);
            if (timeLength >= MAX_TIME_WITHOUT_AUDIO && started) {
                // Log.d(TAG, "Sink sent to writter with size: "+sink.size());
                started = false;
                sinkWritter.stop();
            }
        } catch (Exception e) {
            Log.e(TAG, "Sink problem: ", e);
        }
    }

}


text:
package ibis.ipl.impl.stacking.lrmc.util;

// import ibis.util.Timer;

public class MessageQueue {

    private final int limit;

    private Message head;
    private Message tail;

    private int size = 0;

    private boolean finish = false;

    // Timer enqueueTimer = Timer.createTimer();

    public MessageQueue() {
        // no limit...
        this(Integer.MAX_VALUE);
    }

    public MessageQueue(int limit) {
        this.limit = limit;
    }

    public synchronized void terminate() {
        finish = true;
        // System.out.println("lrmc: wait " + enqueueTimer.nrTimes()
        // + " times, total " + Timer.format(enqueueTimer.totalTimeVal()));
        notifyAll();
    }

    public synchronized int size() {
        return size;
    }

    public synchronized void enqueue(Message m) {

        while (!finish && size >= limit) {
            // enqueueTimer.start();
            try {
                wait();
            } catch (Exception e) {
                // Ignored
                // } finally {
                // enqueueTimer.stop();
            }
        }

        if (finish) {
            return;
        }

        if (head == null) {
            head = tail = m;
            m.next = null;
            notifyAll();
        } else {
            tail.next = m;
            tail = m;
        }

        size++;

        // System.err.println("enqueue, q size = " + size);
    }

    public synchronized Message dequeue() {

        while (size == 0 && !finish) {
            try {
                wait();
            } catch (Exception e) {
                // Ignored
            }
        }

        if (finish) {
            return null;
        }

        Message tmp = head;
        head = head.next;
        tmp.next = null;

        size--;
        // System.err.println("dequeue, q size = " + size);

        if (size == limit - 1) {
            notifyAll();
        }

        return tmp;
    }

}


text:
"""
MOST OF THIS CODE IS NOT USED
ITS COPY/PASTED AND LEFT HERE FOR CONVENIENCE
"""

import os
import sys

# in case our module isn't installed (running from this folder)
if not os.path.abspath('../../../') in sys.path:
    sys.path.append('../../../') # helps spyder get docs

import swhlab
import matplotlib.pyplot as plt
import numpy as np

import warnings # suppress VisibleDeprecationWarning warning
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)

def kernel_gaussian(size=100, sigma=None):
    sigma=size/10 if sigma is None else int(sigma)
    points=np.exp(-np.power(np.arange(size)-size/2,2)/(2*np.power(sigma,2)))
    return points/sum(points)

def analyzeSweep(abf,plotColor=None):

    Y=abf.sweepYsmartbase()
    Y=Y[abf.pointsPerSec*.5:]

    # create a 1 Kbin histogram with bins centered around 3x the SD from the mean
    AV,SD=np.average(Y),np.std(Y)
    B1,B2=AV-SD*3,AV+SD*3
    nBins=1000
    hist, bin_edges = np.histogram(Y, density=True, bins=nBins, range=(B1,B2))
    histSmooth=np.convolve(hist,kernel_gaussian(nBins/2),mode='same')

    if plotColor:
        plt.plot(bin_edges[:-1],histSmooth,'-',alpha=.3,color=plotColor,lw=2)

    return

if __name__=="__main__":
    abfFile=R"C:\Users\scott\Documents\important\demodata\abfs\16d07022.abf"
    abf=swhlab.ABF(abfFile)
    abf.kernel=abf.kernel_gaussian(sizeMS=500) # needed for smart base

    plt.figure(figsize=(10,10))
    plt.grid()
    plt.title("10 sweeps baseline (blue), in drug (blue), and washout (yellow)")
    plt.ylabel("power")
    plt.xlabel(abf.units2)
    plt.axhline(0,color='k')

    for sweep in [(5*60/abf.sweepLength)+x for x in range(10)]:
        print("plotting sweep",sweep)
        abf.setsweep(sweep)
        analyzeSweep(abf,plotColor='b')

    for sweep in [(6.5*60/abf.sweepLength)+x for x in range(10)]:
        print("plotting sweep",sweep)
        abf.setsweep(sweep)
        analyzeSweep(abf,plotColor='r')

    for sweep in [(12*60/abf.sweepLength)+x for x in range(12)]:
        print("plotting sweep",sweep)
        abf.setsweep(sweep)
        analyzeSweep(abf,plotColor='y')

    plt.show()
    print("DONE")


text:
@interface CPTXYPlotSpace(testingAdditions)

-(CPTPlotRange *)constrainRange:(CPTPlotRange *)existingRange toGlobalRange:(CPTPlotRange *)globalRange;

@end

#pragma mark -

@implementation CPTXYPlotSpaceTests

@synthesize graph;

-(void)setUp
{
    self.graph = [[CPTXYGraph alloc] initWithFrame:CPTRectMake(0.0, 0.0, 100.0, 50.0)];

    self.graph.paddingLeft   = 0.0;
    self.graph.paddingRight  = 0.0;
    self.graph.paddingTop    = 0.0;
    self.graph.paddingBottom = 0.0;

    [self.graph layoutIfNeeded];
}

-(void)tearDown
{
    self.graph = nil;
}

#pragma mark -
#pragma mark View point for plot point (linear)

-(void)testViewPointForPlotPointArrayLinear
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLinear;
    plotSpace.yScaleType = CPTScaleTypeLinear;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];

    CPTNumberArray plotPoint = @[@5.0, @5.0];

    CGPoint viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(25.0), CPTFloat(0.01), @"");

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@5.0];

    viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(50.0), CPTFloat(0.01), @"");
}

-(void)testViewPointForPlotPointLinear
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLinear;
    plotSpace.yScaleType = CPTScaleTypeLinear;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];

    NSDecimal plotPoint[2];
    plotPoint[CPTCoordinateX] = CPTDecimalFromDouble(5.0);
    plotPoint[CPTCoordinateY] = CPTDecimalFromDouble(5.0);

    CGPoint viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint numberOfCoordinates:2];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(25.0), CPTFloat(0.01), @"");

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@5.0];

    viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint numberOfCoordinates:2];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(50.0), CPTFloat(0.01), @"");
}

-(void)testViewPointForDoublePrecisionPlotPointLinear
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLinear;
    plotSpace.yScaleType = CPTScaleTypeLinear;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];

    double plotPoint[2];
    plotPoint[CPTCoordinateX] = 5.0;
    plotPoint[CPTCoordinateY] = 5.0;

    CGPoint viewPoint = [plotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint numberOfCoordinates:2];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(25.0), CPTFloat(0.01), @"");

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@5.0];

    viewPoint = [plotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint numberOfCoordinates:2];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(50.0), CPTFloat(0.01), @"");
}

#pragma mark -
#pragma mark View point for plot point (log)

-(void)testViewPointForPlotPointArrayLog
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLog;
    plotSpace.yScaleType = CPTScaleTypeLog;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];

    CPTNumberArray plotPoint = @[@( sqrt(10.0) ), @( sqrt(10.0) )];

    CGPoint viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(25.0), CPTFloat(0.01), @"");

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@10.0
                                                    length:@90.0];

    viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, -CPTFloat(25.0), CPTFloat(0.01), @"");
}

-(void)testViewPointForPlotPointLog
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLog;
    plotSpace.yScaleType = CPTScaleTypeLog;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];

    NSDecimal plotPoint[2];
    plotPoint[CPTCoordinateX] = CPTDecimalFromDouble( sqrt(10.0) );
    plotPoint[CPTCoordinateY] = CPTDecimalFromDouble( sqrt(10.0) );

    CGPoint viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint numberOfCoordinates:2];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(25.0), CPTFloat(0.01), @"");

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@10.0
                                                    length:@90.0];

    viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint numberOfCoordinates:2];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, -CPTFloat(25.0), CPTFloat(0.01), @"");
}

-(void)testViewPointForDoublePrecisionPlotPointLog
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLog;
    plotSpace.yScaleType = CPTScaleTypeLog;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];

    double plotPoint[2];
    plotPoint[CPTCoordinateX] = sqrt(10.0);
    plotPoint[CPTCoordinateY] = sqrt(10.0);

    CGPoint viewPoint = [plotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint numberOfCoordinates:2];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(25.0), CPTFloat(0.01), @"");

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@10.0
                                                    length:@90.0];

    viewPoint = [plotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint numberOfCoordinates:2];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(50.0), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, -CPTFloat(25.0), CPTFloat(0.01), @"");
}

#pragma mark -
#pragma mark View point for plot point (log modulus)

-(void)testViewPointForPlotPointArrayLogModulus
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLogModulus;
    plotSpace.yScaleType = CPTScaleTypeLogModulus;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];

    NSArray *plotPoint = @[@9.0, @0.0];

    CGPoint viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(74.95), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(25.0), CPTFloat(0.01), @"");
}

-(void)testViewPointForPlotPointLogModulus
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLogModulus;
    plotSpace.yScaleType = CPTScaleTypeLogModulus;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];

    NSDecimal plotPoint[2];
    plotPoint[CPTCoordinateX] = CPTDecimalFromInteger(9);
    plotPoint[CPTCoordinateY] = CPTDecimalFromInteger(0);

    CGPoint viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint numberOfCoordinates:2];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(74.95), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(25.0), CPTFloat(0.01), @"");
}

-(void)testViewPointForDoublePrecisionPlotPointLogModulus
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLogModulus;
    plotSpace.yScaleType = CPTScaleTypeLogModulus;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];

    double plotPoint[2];
    plotPoint[CPTCoordinateX] = 9.0;
    plotPoint[CPTCoordinateY] = 0.0;

    CGPoint viewPoint = [plotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint numberOfCoordinates:2];

    XCTAssertEqualWithAccuracy(viewPoint.x, CPTFloat(74.95), CPTFloat(0.01), @"");
    XCTAssertEqualWithAccuracy(viewPoint.y, CPTFloat(25.0), CPTFloat(0.01), @"");
}

#pragma mark -
#pragma mark Plot point for view point (linear)

-(void)testPlotPointArrayForViewPointLinear
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLinear;
    plotSpace.yScaleType = CPTScaleTypeLinear;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];

    CGPoint viewPoint        = CPTPointMake(50.0, 25.0);
    CPTNumberArray plotPoint = [plotSpace plotPointForPlotAreaViewPoint:viewPoint];
    NSString *errMessage;

    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateX] was %@", plotPoint[CPTCoordinateX]];
    XCTAssertTrue(CPTDecimalEquals( [plotPoint[CPTCoordinateX] decimalValue], CPTDecimalFromDouble(5.0) ), @"%@", errMessage);
    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateY] was %@", plotPoint[CPTCoordinateY]];
    XCTAssertTrue(CPTDecimalEquals( [plotPoint[CPTCoordinateY] decimalValue], CPTDecimalFromDouble(5.0) ), @"%@", errMessage);
}

-(void)testPlotPointForViewPointLinear
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLinear;
    plotSpace.yScaleType = CPTScaleTypeLinear;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];

    NSDecimal plotPoint[2];
    CGPoint viewPoint = CPTPointMake(50.0, 25.0);
    NSString *errMessage;

    [plotSpace plotPoint:plotPoint numberOfCoordinates:2 forPlotAreaViewPoint:viewPoint];

    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateX] was %@", NSDecimalString(&plotPoint[CPTCoordinateX], nil)];
    XCTAssertTrue(CPTDecimalEquals( plotPoint[CPTCoordinateX], CPTDecimalFromDouble(5.0) ), @"%@", errMessage);
    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateY] was %@", NSDecimalString(&plotPoint[CPTCoordinateY], nil)];
    XCTAssertTrue(CPTDecimalEquals( plotPoint[CPTCoordinateY], CPTDecimalFromDouble(5.0) ), @"%@", errMessage);
}

-(void)testDoublePrecisionPlotPointForViewPointLinear
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLinear;
    plotSpace.yScaleType = CPTScaleTypeLinear;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];

    double plotPoint[2];
    CGPoint viewPoint = CPTPointMake(50.0, 25.0);
    NSString *errMessage;

    [plotSpace doublePrecisionPlotPoint:plotPoint numberOfCoordinates:2 forPlotAreaViewPoint:viewPoint];

    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateX] was %g", plotPoint[CPTCoordinateX]];
    XCTAssertEqual(plotPoint[CPTCoordinateX], 5.0, @"%@", errMessage);
    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateY] was %g", plotPoint[CPTCoordinateY]];
    XCTAssertEqual(plotPoint[CPTCoordinateY], 5.0, @"%@", errMessage);
}

#pragma mark -
#pragma mark Plot point for view point (log)

-(void)testPlotPointArrayForViewPointLog
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLog;
    plotSpace.yScaleType = CPTScaleTypeLog;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];

    CGPoint viewPoint        = CPTPointMake(50.0, 25.0);
    CPTNumberArray plotPoint = [plotSpace plotPointForPlotAreaViewPoint:viewPoint];
    NSString *errMessage;

    [plotSpace plotPointForPlotAreaViewPoint:viewPoint];

    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateX] was %@", plotPoint[CPTCoordinateX]];
    XCTAssertEqual([plotPoint[CPTCoordinateX] doubleValue], sqrt(10.0), @"%@", errMessage);
    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateY] was %@", plotPoint[CPTCoordinateY]];
    XCTAssertEqual([plotPoint[CPTCoordinateY] doubleValue], sqrt(10.0), @"%@", errMessage);
}

-(void)testPlotPointForViewPointLog
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLog;
    plotSpace.yScaleType = CPTScaleTypeLog;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];

    NSDecimal plotPoint[2];
    CGPoint viewPoint = CPTPointMake(50.0, 25.0);
    NSString *errMessage;

    [plotSpace plotPoint:plotPoint numberOfCoordinates:2 forPlotAreaViewPoint:viewPoint];

    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateX] was %@", NSDecimalString(&plotPoint[CPTCoordinateX], nil)];
    XCTAssertTrue(CPTDecimalEquals( plotPoint[CPTCoordinateX], CPTDecimalFromDouble( sqrt(10.0) ) ), @"%@", errMessage);
    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateY] was %@", NSDecimalString(&plotPoint[CPTCoordinateY], nil)];
    XCTAssertTrue(CPTDecimalEquals( plotPoint[CPTCoordinateY], CPTDecimalFromDouble( sqrt(10.0) ) ), @"%@", errMessage);
}

-(void)testDoublePrecisionPlotPointForViewPointLog
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLog;
    plotSpace.yScaleType = CPTScaleTypeLog;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@1.0
                                                    length:@9.0];

    double plotPoint[2];
    CGPoint viewPoint = CPTPointMake(50.0, 25.0);
    NSString *errMessage;

    [plotSpace doublePrecisionPlotPoint:plotPoint numberOfCoordinates:2 forPlotAreaViewPoint:viewPoint];

    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateX] was %g", plotPoint[CPTCoordinateX]];
    XCTAssertEqual(plotPoint[CPTCoordinateX], sqrt(10.0), @"%@", errMessage);
    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateY] was %g", plotPoint[CPTCoordinateY]];
    XCTAssertEqual(plotPoint[CPTCoordinateY], sqrt(10.0), @"%@", errMessage);
}

#pragma mark -
#pragma mark Plot point for view point (log modulus)

-(void)testPlotPointArrayForViewPointLogModulus
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLogModulus;
    plotSpace.yScaleType = CPTScaleTypeLogModulus;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];

    CGPoint viewPoint  = CPTPointMake(74.95, 25.0);
    NSArray *plotPoint = [plotSpace plotPointForPlotAreaViewPoint:viewPoint];
    NSString *errMessage;

    [plotSpace plotPointForPlotAreaViewPoint:viewPoint];

    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateX] was %@", plotPoint[CPTCoordinateX]];
    XCTAssertEqualWithAccuracy([plotPoint[CPTCoordinateX] doubleValue], CPTInverseLogModulus(1.0), CPTFloat(0.01), @"%@", errMessage);
    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateY] was %@", plotPoint[CPTCoordinateY]];
    XCTAssertEqual([plotPoint[CPTCoordinateY] doubleValue], 0.0, @"%@", errMessage);
}

-(void)testPlotPointForViewPointLogModulus
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLogModulus;
    plotSpace.yScaleType = CPTScaleTypeLogModulus;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];

    NSDecimal plotPoint[2];
    CGPoint viewPoint = CPTPointMake(50.0, 25.0);
    NSString *errMessage;

    [plotSpace plotPoint:plotPoint numberOfCoordinates:2 forPlotAreaViewPoint:viewPoint];

    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateX] was %@", NSDecimalString(&plotPoint[CPTCoordinateX], nil)];
    XCTAssertTrue(CPTDecimalEquals( plotPoint[CPTCoordinateX], CPTDecimalFromInteger(0) ), @"%@", errMessage);
    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateY] was %@", NSDecimalString(&plotPoint[CPTCoordinateY], nil)];
    XCTAssertTrue(CPTDecimalEquals( plotPoint[CPTCoordinateY], CPTDecimalFromInteger(0) ), @"%@", errMessage);
}

-(void)testDoublePrecisionPlotPointForViewPointLogModulus
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.xScaleType = CPTScaleTypeLogModulus;
    plotSpace.yScaleType = CPTScaleTypeLogModulus;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@(-100.0)
                                                    length:@200.0];

    double plotPoint[2];
    CGPoint viewPoint = CPTPointMake(74.95, 25.0);
    NSString *errMessage;

    [plotSpace doublePrecisionPlotPoint:plotPoint numberOfCoordinates:2 forPlotAreaViewPoint:viewPoint];

    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateX] was %g", plotPoint[CPTCoordinateX]];
    XCTAssertEqualWithAccuracy(plotPoint[CPTCoordinateX], CPTInverseLogModulus(1.0), CPTFloat(0.01), @"%@", errMessage);
    errMessage = [NSString stringWithFormat:@"plotPoint[CPTCoordinateY] was %g", plotPoint[CPTCoordinateY]];
    XCTAssertEqual(plotPoint[CPTCoordinateY], 0.0, @"%@", errMessage);
}

#pragma mark -
#pragma mark Constrain ranges

-(void)testConstrainNilRanges
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    XCTAssertEqualObjects([plotSpace constrainRange:plotSpace.xRange toGlobalRange:nil], plotSpace.xRange, @"Constrain to nil global range should return original range.");
    XCTAssertNil([plotSpace constrainRange:nil toGlobalRange:plotSpace.xRange], @"Constrain nil range should return nil.");
}

-(void)testConstrainRanges1
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    CPTPlotRange *existingRange = [CPTPlotRange plotRangeWithLocation:@2.0
                                                               length:@5.0];
    CPTPlotRange *globalRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                             length:@10.0];
    CPTPlotRange *expectedRange = existingRange;

    CPTPlotRange *constrainedRange = [plotSpace constrainRange:existingRange toGlobalRange:globalRange];
    NSString *errMessage           = [NSString stringWithFormat:@"constrainedRange was %@, expected %@", constrainedRange, expectedRange];

    XCTAssertTrue([constrainedRange isEqualToRange:expectedRange], @"%@", errMessage);
}

-(void)testConstrainRanges2
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    CPTPlotRange *existingRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                               length:@10.0];
    CPTPlotRange *globalRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                             length:@5.0];
    CPTPlotRange *expectedRange = globalRange;

    CPTPlotRange *constrainedRange = [plotSpace constrainRange:existingRange toGlobalRange:globalRange];
    NSString *errMessage           = [NSString stringWithFormat:@"constrainedRange was %@, expected %@", constrainedRange, expectedRange];

    XCTAssertTrue([constrainedRange isEqualToRange:expectedRange], @"%@", errMessage);
}

-(void)testConstrainRanges3
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    CPTPlotRange *existingRange = [CPTPlotRange plotRangeWithLocation:@(-1.0)
                                                               length:@8.0];
    CPTPlotRange *globalRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                             length:@10.0];
    CPTPlotRange *expectedRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                               length:@8.0];

    CPTPlotRange *constrainedRange = [plotSpace constrainRange:existingRange toGlobalRange:globalRange];
    NSString *errMessage           = [NSString stringWithFormat:@"constrainedRange was %@, expected %@", constrainedRange, expectedRange];

    XCTAssertTrue([constrainedRange isEqualToRange:expectedRange], @"%@", errMessage);
}

-(void)testConstrainRanges4
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    CPTPlotRange *existingRange = [CPTPlotRange plotRangeWithLocation:@3.0
                                                               length:@8.0];
    CPTPlotRange *globalRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                             length:@10.0];
    CPTPlotRange *expectedRange = [CPTPlotRange plotRangeWithLocation:@2.0
                                                               length:@8.0];

    CPTPlotRange *constrainedRange = [plotSpace constrainRange:existingRange toGlobalRange:globalRange];
    NSString *errMessage           = [NSString stringWithFormat:@"constrainedRange was %@, expected %@", constrainedRange, expectedRange];

    XCTAssertTrue([constrainedRange isEqualToRange:expectedRange], @"%@", errMessage);
}

#pragma mark -
#pragma mark Scaling

-(void)testScaleByAboutPoint1
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.allowsUserInteraction = YES;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@10.0
                                                    length:@(-10.0)];

    CGRect myBounds = self.graph.bounds;

    [plotSpace scaleBy:0.5 aboutPoint:CGPointMake( CGRectGetMidX(myBounds), CGRectGetMidY(myBounds) )];

    CPTPlotRange *expectedRangeX = [CPTPlotRange plotRangeWithLocation:@(-5.0)
                                                                length:@20.0];
    CPTPlotRange *expectedRangeY = [CPTPlotRange plotRangeWithLocation:@15.0
                                                                length:@(-20.0)];

    NSString *errMessage = [NSString stringWithFormat:@"xRange was %@, expected %@", plotSpace.xRange, expectedRangeX];
    XCTAssertTrue([plotSpace.xRange isEqualToRange:expectedRangeX], @"%@", errMessage);

    errMessage = [NSString stringWithFormat:@"yRange was %@, expected %@", plotSpace.yRange, expectedRangeY];
    XCTAssertTrue([plotSpace.yRange isEqualToRange:expectedRangeY], @"%@", errMessage);
}

-(void)testScaleByAboutPoint2
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.allowsUserInteraction = YES;

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                    length:@10.0];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:@10.0
                                                    length:@(-10.0)];

    CGRect myBounds = self.graph.bounds;

    [plotSpace scaleBy:2.0 aboutPoint:CGPointMake( CGRectGetMidX(myBounds), CGRectGetMidY(myBounds) )];

    CPTPlotRange *expectedRangeX = [CPTPlotRange plotRangeWithLocation:@2.5
                                                                length:@5.0];
    CPTPlotRange *expectedRangeY = [CPTPlotRange plotRangeWithLocation:@7.5
                                                                length:@(-5.0)];

    NSString *errMessage = [NSString stringWithFormat:@"xRange was %@, expected %@", plotSpace.xRange, expectedRangeX];
    XCTAssertTrue([plotSpace.xRange isEqualToRange:expectedRangeX], @"%@", errMessage);

    errMessage = [NSString stringWithFormat:@"yRange was %@, expected %@", plotSpace.yRange, expectedRangeY];
    XCTAssertTrue([plotSpace.yRange isEqualToRange:expectedRangeY], @"%@", errMessage);
}

#pragma mark -
#pragma mark NSCoding Methods

-(void)testKeyedArchivingRoundTrip
{
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;

    plotSpace.globalXRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                          length:@10.0];
    plotSpace.globalYRange = [CPTPlotRange plotRangeWithLocation:@10.0
                                                          length:@(-10.0)];

    CPTXYPlotSpace *newPlotSpace = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:plotSpace]];

    NSString *errMessage = [NSString stringWithFormat:@"xRange was %@, expected %@", plotSpace.xRange, newPlotSpace.xRange];
    XCTAssertTrue([plotSpace.xRange isEqualToRange:newPlotSpace.xRange], @"%@", errMessage);

    errMessage = [NSString stringWithFormat:@"yRange was %@, expected %@", plotSpace.yRange, newPlotSpace.yRange];
    XCTAssertTrue([plotSpace.yRange isEqualToRange:newPlotSpace.yRange], @"%@", errMessage);

    errMessage = [NSString stringWithFormat:@"globalXRange was %@, expected %@", plotSpace.globalXRange, newPlotSpace.globalXRange];
    XCTAssertTrue([plotSpace.globalXRange isEqualToRange:newPlotSpace.globalXRange], @"%@", errMessage);

    errMessage = [NSString stringWithFormat:@"globalYRange was %@, expected %@", plotSpace.globalYRange, newPlotSpace.globalYRange];
    XCTAssertTrue([plotSpace.globalYRange isEqualToRange:newPlotSpace.globalYRange], @"%@", errMessage);

    XCTAssertEqual(plotSpace.xScaleType, newPlotSpace.xScaleType, @"xScaleType not equal");
    XCTAssertEqual(plotSpace.yScaleType, newPlotSpace.yScaleType, @"yScaleType not equal");
}

@end


text:
package org.apache.ivy.ant;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.ivy.core.report.ArtifactDownloadReport;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Location;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.types.ResourceCollection;
import org.apache.tools.ant.types.resources.BaseResourceCollectionWrapper;
import org.apache.tools.ant.types.resources.FileResource;

public class IvyResources extends IvyCacheTask implements ResourceCollection {

    /**
     * Delegate for the implementation of the resource collection
     */
    private class IvyBaseResourceCollectionWrapper extends BaseResourceCollectionWrapper {

        protected Collection getCollection() {
            return resolveResources(null);
        }

    }

    private IvyBaseResourceCollectionWrapper wrapper = new IvyBaseResourceCollectionWrapper();

    // delegate the ProjectComponent API on the wrapper

    public void setLocation(Location location) {
        super.setLocation(location);
        wrapper.setLocation(location);
    }

    public void setProject(Project project) {
        super.setProject(project);
        wrapper.setProject(project);
    }

    public void setDescription(String desc) {
        super.setDescription(desc);
        wrapper.setDescription(desc);
    }

    // delegate the DataType API on the wrapper

    public void setRefid(Reference ref) {
        wrapper.setRefid(ref);
    }

    // delegate the AbstractResourceCollectionWrapper API on the wrapper

    public void setCache(boolean b) {
        wrapper.setCache(b);
    }

    // implementation of the Resource Collection API

    public boolean isFilesystemOnly() {
        return true;
    }

    public Iterator iterator() {
        return wrapper.iterator();
    }

    public int size() {
        return wrapper.size();
    }

    // convert the ivy reports into an Ant Resource collection

    private Collection resolveResources(String id) throws BuildException {
        prepareAndCheck();
        try {
            List/* <FileResource> */resources = new ArrayList();
            if (id != null) {
                getProject().addReference(id, this);
            }
            for (Iterator iter = getArtifactReports().iterator(); iter.hasNext();) {
                ArtifactDownloadReport a = (ArtifactDownloadReport) iter.next();
                resources.add(new FileResource(a.getLocalFile()));
            }
            return resources;
        } catch (Exception ex) {
            throw new BuildException("impossible to build ivy resources: " + ex, ex);
        }
    }

    // implementation of the IvyPostResolveTask API

    public void doExecute() throws BuildException {
        // TODO : maybe there is a way to implement it ?
        throw new BuildException("ivy:resources should not be used as a Ant Task");
    }

}


text:
@interface LYPhotoGalleryViewController () <RMPhotoPageViewControllerDelegate, UIActionSheetDelegate, RMPhotoPageViewControllerDataSource, RMPhotoPageViewControllerDelegate,RMPhotoViewControllerDelegate>

@property (nonatomic, strong) LYPhotoPageViewController *pageViewController;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UILabel *indexLabel;
@property (weak, nonatomic) IBOutlet UIButton *backButton;
@property (weak, nonatomic) IBOutlet UIButton *deleteButton;
@property (weak, nonatomic) IBOutlet UITapGestureRecognizer *tapGestureRecognizer;

@end

@implementation LYPhotoGalleryViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.pageViewController = [LYPhotoPageViewController viewController];
    self.pageViewController.delegate = self;
    self.pageViewController.dataSource = self;
    self.pageViewController.view.frame = self.view.bounds;
    UIImage *image = [self.backButton imageForState:UIControlStateNormal];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [self.backButton setImage:image forState:UIControlStateNormal];
    self.backButton.tintColor = [UIColor whiteColor];
    [self.view insertSubview:self.pageViewController.view atIndex:0];
    [self addChildViewController:self.pageViewController];
    [self loadPageViewControllerData];
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)loadPageViewControllerData
{
    self.indexLabel.text = [NSString stringWithFormat:@"%@/%@",@(self.currentIndex + 1).stringValue,@(self.photoList.count).stringValue];
    [self.pageViewController setCurrentIndex:self.currentIndex scrollAnimation:EPhotoPageScrollAnimationDirectionAfter completion:nil];
}

- (IBAction)handleTapGesture
{
    self.topView.hidden = !self.topView.hidden;
}

- (IBAction)didTappedDeleteButton:(UIButton *)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:@"删除照片"
                                                    otherButtonTitles:nil, nil];
    [actionSheet showInView:self.view];
}

- (IBAction)didTappedBackButton:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSMutableArray *photoList = [NSMutableArray arrayWithArray:self.photoList];
        [photoList removeObjectAtIndex:self.currentIndex];
        if (!photoList.count) {
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            self.photoList = photoList;
            [self.pageViewController deletePhotoViewControllerAtIndex:self.currentIndex scrollAnimation:EPhotoPageScrollAnimationDirectionAutomic completion:^(BOOL finished) {
                self.currentIndex = self.pageViewController.currentIndex;
                self.indexLabel.text = [NSString stringWithFormat:@"%@/%@",@(self.currentIndex + 1).stringValue,@(self.photoList.count).stringValue];
            }];
        }
    }
}

#pragma mark -

- (NSUInteger)numberOfIndexInPhotoPageViewController:(LYPhotoPageViewController *)photoPageViewController
{
    return self.photoList.count;
}

- (RMPhotoViewController *)photoPageViewController:(LYPhotoPageViewController *)photoPageViewController atIndex:(NSUInteger)index
{
    LYPhotoItem *photoItem = self.photoList[index];
    RMPhotoViewController *photoViewController = [RMPhotoViewController viewControllerForimageURL:photoItem.largeURL placeholderImage:nil];
    photoViewController.delegate = self;
    [self.tapGestureRecognizer requireGestureRecognizerToFail:photoViewController.doubleTapRecognizer];
    return photoViewController;
}

#pragma mark-RMPhotoPageViewControllerDelegate

- (void)photoPageViewController:(LYPhotoPageViewController *)photoPageViewController didScorllToIndex:(NSUInteger)index
{
    self.indexLabel.text = [NSString stringWithFormat:@"%@/%@",@(index + 1).stringValue,@(self.photoList.count).stringValue];
    self.currentIndex = index;
}

- (CGFloat)originScaleOfImageSize:(CGSize)size
{
    return self.view.frame.size.width / size.width;
}

@end


text:
package org.apache.tez.mapreduce.input;

import javax.annotation.Nullable;

import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import com.google.protobuf.ByteString;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceAudience.Public;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.split.JobSplit.TaskSplitIndex;
import org.apache.hadoop.mapreduce.split.JobSplit.TaskSplitMetaInfo;
import org.apache.hadoop.security.Credentials;
import org.apache.tez.common.TezUtils;
import org.apache.tez.common.counters.TaskCounter;
import org.apache.tez.dag.api.DataSourceDescriptor;
import org.apache.tez.dag.api.InputDescriptor;
import org.apache.tez.dag.api.InputInitializerDescriptor;
import org.apache.tez.dag.api.TezUncheckedException;
import org.apache.tez.dag.api.UserPayload;
import org.apache.tez.dag.api.VertexLocationHint;
import org.apache.tez.mapreduce.common.MRInputAMSplitGenerator;
import org.apache.tez.mapreduce.common.MRInputSplitDistributor;
import org.apache.tez.mapreduce.hadoop.InputSplitInfo;
import org.apache.tez.mapreduce.hadoop.MRHelpers;
import org.apache.tez.mapreduce.hadoop.MRInputHelpers;
import org.apache.tez.mapreduce.hadoop.MRJobConfig;
import org.apache.tez.mapreduce.input.base.MRInputBase;
import org.apache.tez.mapreduce.lib.MRInputUtils;
import org.apache.tez.mapreduce.lib.MRReader;
import org.apache.tez.mapreduce.lib.MRReaderMapReduce;
import org.apache.tez.mapreduce.lib.MRReaderMapred;
import org.apache.tez.mapreduce.protos.MRRuntimeProtos;
import org.apache.tez.mapreduce.protos.MRRuntimeProtos.MRSplitProto;
import org.apache.tez.runtime.api.Event;
import org.apache.tez.runtime.api.Input;
import org.apache.tez.runtime.api.InputContext;
import org.apache.tez.runtime.api.events.InputDataInformationEvent;
import org.apache.tez.runtime.library.api.KeyValueReader;
import org.apache.tez.runtime.library.api.TezRuntimeConfiguration;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

/**
 * {@link MRInput} is an {@link Input} which provides key/values pairs
 * for the consumer.
 *
 * It is compatible with all standard Apache Hadoop MapReduce
 * {@link InputFormat} implementations.
 *
 * This class is not meant to be extended by external projects.
 */
@Public
public class MRInput extends MRInputBase {

  /**
   * Helper class to configure {@link MRInput}
   *
   */
  public static class MRInputConfigBuilder {
    final Configuration conf;
    final Class<?> inputFormat;
    final boolean inputFormatProvided;
    boolean useNewApi;
    boolean groupSplitsInAM = true;
    boolean generateSplitsInAM = true;
    String inputClassName = MRInput.class.getName();
    boolean getCredentialsForSourceFilesystem = true;
    String inputPaths = null;
    InputInitializerDescriptor customInitializerDescriptor = null;

    MRInputConfigBuilder(Configuration conf, Class<?> inputFormatParam) {
      this.conf = conf;
      if (inputFormatParam != null) {
        inputFormatProvided = true;
        this.inputFormat = inputFormatParam;
        if (org.apache.hadoop.mapred.InputFormat.class.isAssignableFrom(inputFormatParam)) {
          useNewApi = false;
        } else if (org.apache.hadoop.mapreduce.InputFormat.class.isAssignableFrom(inputFormatParam)) {
          useNewApi = true;
        } else {
          throw new TezUncheckedException("inputFormat must be assignable from either " +
              "org.apache.hadoop.mapred.InputFormat or " +
              "org.apache.hadoop.mapreduce.InputFormat" +
              " Given: " + inputFormatParam.getName());
        }
      } else {
        inputFormatProvided = false;
        useNewApi = conf.getBoolean(MRJobConfig.NEW_API_MAPPER_CONFIG, true);
        try {
          if (useNewApi) {
            this.inputFormat = conf.getClassByName(conf.get(MRJobConfig.INPUT_FORMAT_CLASS_ATTR));
            Preconditions.checkState(org.apache.hadoop.mapreduce.InputFormat.class
                .isAssignableFrom(this.inputFormat));
          } else {
            this.inputFormat = conf.getClassByName(conf.get("mapred.input.format.class"));
            Preconditions.checkState(org.apache.hadoop.mapred.InputFormat.class
                .isAssignableFrom(this.inputFormat));
          }
        } catch (ClassNotFoundException e) {
          throw new TezUncheckedException(e);
        }
        initializeInputPath();
      }
    }

    MRInputConfigBuilder setInputClassName(String className) {
      this.inputClassName = className;
      return this;
    }

    private MRInputConfigBuilder setInputPaths(String inputPaths) {
      if (!(org.apache.hadoop.mapred.FileInputFormat.class.isAssignableFrom(inputFormat) ||
          FileInputFormat.class.isAssignableFrom(inputFormat))) {
        throw new TezUncheckedException("When setting inputPaths the inputFormat must be " +
            "assignable from either org.apache.hadoop.mapred.FileInputFormat or " +
            "org.apache.hadoop.mapreduce.lib.input.FileInputFormat. " +
            "Otherwise use the non-path configBuilder." +
            " Given: " + inputFormat.getName());
      }
      conf.set(FileInputFormat.INPUT_DIR, inputPaths);
      this.inputPaths = inputPaths;
      return this;
    }

    private void initializeInputPath() {
      Preconditions.checkState(inputFormatProvided == false,
          "Should only be invoked when no inputFormat is provided");
      if (org.apache.hadoop.mapred.FileInputFormat.class.isAssignableFrom(inputFormat) ||
          FileInputFormat.class.isAssignableFrom(inputFormat)) {
        inputPaths = conf.get(FileInputFormat.INPUT_DIR);
      }
    }

    /**
     * Set whether splits should be grouped (default true)
     * @param value whether to group splits in the AM or not
     * @return {@link org.apache.tez.mapreduce.input.MRInput.MRInputConfigBuilder}
     */
    public MRInputConfigBuilder groupSplits(boolean value) {
      groupSplitsInAM = value;
      return this;
    }

    /**
     * Set whether splits should be generated in the Tez App Master (default true)
     * @param value whether to generate splits in the AM or not
     * @return {@link org.apache.tez.mapreduce.input.MRInput.MRInputConfigBuilder}
     */
    public MRInputConfigBuilder generateSplitsInAM(boolean value) {
      generateSplitsInAM = value;
      return this;
    }

    /**
     * Get the credentials for the inputPaths from their {@link FileSystem}s
     * Use the method to turn this off when not using a {@link FileSystem}
     * or when {@link Credentials} are not supported
     * @param value whether to get credentials or not. (true by default)
     * @return {@link org.apache.tez.mapreduce.input.MRInput.MRInputConfigBuilder}
     */
    public MRInputConfigBuilder getCredentialsForSourceFileSystem(boolean value) {
      getCredentialsForSourceFilesystem = value;
      return this;
    }

    /**
     * This method is intended to be used in case a custom {@link org.apache.tez.runtime.api.InputInitializer}
     * is being used along with MRInput. If a custom descriptor is used, the config builder will not be
     * able to setup location hints, parallelism, etc, and configuring the {@link
     * org.apache.tez.dag.api.Vertex} on which this Input is used is the responsibility of the user.
     *
     * Credential fetching can be controlled via the {@link #getCredentialsForSourceFilesystem} method.
     * Whether grouping is enabled or not can be controlled via {@link #groupSplitsInAM} method.
     *
     * @param customInitializerDescriptor the initializer descriptor
     * @return {@link org.apache.tez.mapreduce.input.MRInput.MRInputConfigBuilder}
     */
    public MRInputConfigBuilder setCustomInitializerDescriptor(
        InputInitializerDescriptor customInitializerDescriptor) {
      this.customInitializerDescriptor = customInitializerDescriptor;
      return this;
    }

    /**
     * Create the {@link DataSourceDescriptor}
     *
     * @return {@link DataSourceDescriptor}
     */
    public DataSourceDescriptor build() {
      if (org.apache.hadoop.mapred.FileInputFormat.class.isAssignableFrom(inputFormat) ||
          FileInputFormat.class.isAssignableFrom(inputFormat)) {
        if (inputPaths == null) {
          throw new TezUncheckedException(
              "InputPaths must be specified for InputFormats based on " +
                  FileInputFormat.class.getName() + " or " +
                  org.apache.hadoop.mapred.FileInputFormat.class.getName());
        }
      }
      try {
        if (this.customInitializerDescriptor != null) {
          return createCustomDataSource();
        } else {
          if (generateSplitsInAM) {
            return createGeneratorDataSource();
          } else {
            return createDistributorDataSource();
          }
        }
      } catch (Exception e) {
        throw new TezUncheckedException(e);
      }
    }

    private DataSourceDescriptor createDistributorDataSource() throws IOException {
      InputSplitInfo inputSplitInfo;
      setupBasicConf(conf);
      try {
        inputSplitInfo = MRInputHelpers.generateInputSplitsToMem(conf, false, 0);
      } catch (Exception e) {
        throw new TezUncheckedException(e);
      }
      MRHelpers.translateMRConfToTez(conf);

      UserPayload payload = MRInputHelpersInternal.createMRInputPayload(conf,
          inputSplitInfo.getSplitsProto());
      Credentials credentials = null;
      if (getCredentialsForSourceFilesystem && inputSplitInfo.getCredentials() != null) {
        credentials = inputSplitInfo.getCredentials();
      }
      DataSourceDescriptor ds = DataSourceDescriptor.create(
          InputDescriptor.create(inputClassName).setUserPayload(payload),
          InputInitializerDescriptor.create(MRInputSplitDistributor.class.getName()),
          inputSplitInfo.getNumTasks(), credentials,
          VertexLocationHint.create(inputSplitInfo.getTaskLocationHints()), null);
      if (conf.getBoolean(TezRuntimeConfiguration.TEZ_RUNTIME_CONVERT_USER_PAYLOAD_TO_HISTORY_TEXT,
          TezRuntimeConfiguration.TEZ_RUNTIME_CONVERT_USER_PAYLOAD_TO_HISTORY_TEXT_DEFAULT)) {
        ds.getInputDescriptor().setHistoryText(TezUtils.convertToHistoryText(conf));
      }

      return ds;
    }

    private DataSourceDescriptor createCustomDataSource() throws IOException {
      setupBasicConf(conf);

      MRHelpers.translateMRConfToTez(conf);

      Collection<URI> uris = maybeGetURIsForCredentials();

      UserPayload payload = null;
      if (groupSplitsInAM) {
        payload = MRInputHelpersInternal.createMRInputPayloadWithGrouping(conf);
      } else {
        payload = MRInputHelpersInternal.createMRInputPayload(conf, null);
      }

      DataSourceDescriptor ds = DataSourceDescriptor
          .create(InputDescriptor.create(inputClassName).setUserPayload(payload),
              customInitializerDescriptor, null);

      if (conf.getBoolean(TezRuntimeConfiguration.TEZ_RUNTIME_CONVERT_USER_PAYLOAD_TO_HISTORY_TEXT,
          TezRuntimeConfiguration.TEZ_RUNTIME_CONVERT_USER_PAYLOAD_TO_HISTORY_TEXT_DEFAULT)) {
        ds.getInputDescriptor().setHistoryText(TezUtils.convertToHistoryText(conf));
      }

      if (uris != null) {
        ds.addURIsForCredentials(uris);
      }
      return ds;
    }

    private DataSourceDescriptor createGeneratorDataSource() throws IOException {
      setupBasicConf(conf);
      MRHelpers.translateMRConfToTez(conf);

      Collection<URI> uris = maybeGetURIsForCredentials();

      UserPayload payload = null;
      if (groupSplitsInAM) {
        payload = MRInputHelpersInternal.createMRInputPayloadWithGrouping(conf);
      } else {
        payload = MRInputHelpersInternal.createMRInputPayload(conf, null);
      }

      DataSourceDescriptor ds = DataSourceDescriptor.create(
          InputDescriptor.create(inputClassName).setUserPayload(payload),
          InputInitializerDescriptor.create(MRInputAMSplitGenerator.class.getName()), null);

      if (conf.getBoolean(TezRuntimeConfiguration.TEZ_RUNTIME_CONVERT_USER_PAYLOAD_TO_HISTORY_TEXT,
          TezRuntimeConfiguration.TEZ_RUNTIME_CONVERT_USER_PAYLOAD_TO_HISTORY_TEXT_DEFAULT)) {
        ds.getInputDescriptor().setHistoryText(TezUtils.convertToHistoryText(conf));
      }

      if (uris != null) {
        ds.addURIsForCredentials(uris);
      }
      return ds;
    }

    private void setupBasicConf(Configuration inputConf) {
      if (inputFormatProvided) {
        inputConf.setBoolean(MRJobConfig.NEW_API_MAPPER_CONFIG, useNewApi);
        if (useNewApi) {
          inputConf.set(MRJobConfig.INPUT_FORMAT_CLASS_ATTR, inputFormat.getName());
        } else {
          inputConf.set("mapred.input.format.class", inputFormat.getName());
        }
      }
    }

    private Collection<URI> maybeGetURIsForCredentials() {
      if (getCredentialsForSourceFilesystem && inputPaths != null) {
        try {
          List<URI> uris = Lists.newLinkedList();
          for (String inputPath : inputPaths.split(",")) {
            Path path = new Path(inputPath);
            FileSystem fs;
            fs = path.getFileSystem(conf);
            Path qPath = fs.makeQualified(path);
            uris.add(qPath.toUri());
          }
          return uris;
        } catch (IOException e) {
          throw new TezUncheckedException(e);
        }
      }
      return null;
    }

  }

  /**
   * Create an {@link org.apache.tez.mapreduce.input.MRInput.MRInputConfigBuilder}

   * The preferred usage model is to provide all of the parameters, and use methods to configure
   * the Input.
   *

   * For legacy applications, which may already have a fully configured {@link Configuration}
   * instance, the inputFormat can be specified as null
   *
   * @param conf        Configuration for the {@link MRInput}. This configuration instance will be
   *                    modified in place
   * @param inputFormat InputFormat derived class. This can be null. If the InputFormat specified
   *                    is
   *                    null, the provided configuration should be complete.
   * @return {@link org.apache.tez.mapreduce.input.MRInput.MRInputConfigBuilder}
   */
  public static MRInputConfigBuilder createConfigBuilder(Configuration conf,
                                                         @Nullable Class<?> inputFormat) {
    return new MRInputConfigBuilder(conf, inputFormat);
  }

  /**
   * Create an {@link org.apache.tez.mapreduce.input.MRInput.MRInputConfigBuilder}
   * for {@link org.apache.hadoop.mapreduce.lib.input.FileInputFormat}
   * or {@link org.apache.hadoop.mapred.FileInputFormat} format based InputFormats.
   *

   * The preferred usage model is to provide all of the parameters, and use methods to configure
   * the Input.
   *

   * For legacy applications, which may already have a fully configured {@link Configuration}
   * instance, the inputFormat and inputPath can be specified as null
   *
   * @param conf        Configuration for the {@link MRInput}. This configuration instance will be
   *                    modified in place
   * @param inputFormat InputFormat derived class. This can be null. If the InputFormat specified
   *                    is
   *                    null, the provided configuration should be complete.
   * @param inputPaths  Comma separated input paths
   * @return {@link org.apache.tez.mapreduce.input.MRInput.MRInputConfigBuilder}
   */
  public static MRInputConfigBuilder createConfigBuilder(Configuration conf,
                                                         @Nullable Class<?> inputFormat,
                                                         @Nullable String inputPaths) {
    MRInputConfigBuilder configurer = new MRInputConfigBuilder(conf, inputFormat);
    if (inputPaths != null) {
      return configurer.setInputPaths(inputPaths);
    }
    return configurer;
  }

  private static final Logger LOG = LoggerFactory.getLogger(MRInput.class);

  private final ReentrantLock rrLock = new ReentrantLock();
  private final Condition rrInited = rrLock.newCondition();

  private volatile boolean eventReceived = false;

  private boolean readerCreated = false;

  protected MRReader mrReader;

  protected TaskSplitIndex splitMetaInfo = new TaskSplitIndex();

  // Potential counters - #splits, #totalSize, #actualyBytesRead

  @Private
  volatile boolean splitInfoViaEvents;

  public MRInput(InputContext inputContext, int numPhysicalInputs) {
    super(inputContext, numPhysicalInputs);
  }

  @Override
  public List<Event> initialize() throws IOException {
    super.initialize();
    getContext().inputIsReady();
    this.splitInfoViaEvents = jobConf.getBoolean(MRJobConfig.MR_TEZ_SPLITS_VIA_EVENTS,
        MRJobConfig.MR_TEZ_SPLITS_VIA_EVENTS_DEFAULT);
    LOG.info("Using New mapreduce API: " + useNewApi
        + ", split information via event: " + splitInfoViaEvents);
    initializeInternal();
    return null;
  }

  @Override
  public void start() {
    Preconditions.checkState(getNumPhysicalInputs() == 0 || getNumPhysicalInputs() == 1,
        "Expecting 0 or 1 physical input for MRInput");
    LOG.info("MRInput setup to received {} events", getNumPhysicalInputs());
  }

  @Private
  void initializeInternal() throws IOException {
    // Primarily for visibility
    rrLock.lock();
    try {

      if (splitInfoViaEvents) {
        if (useNewApi) {
          mrReader = new MRReaderMapReduce(jobConf, getContext().getCounters(), inputRecordCounter,
              getContext().getApplicationId().getClusterTimestamp(), getContext()
                  .getTaskVertexIndex(), getContext().getApplicationId().getId(), getContext()
                  .getTaskIndex(), getContext().getTaskAttemptNumber());
        } else {
          mrReader = new MRReaderMapred(jobConf, getContext().getCounters(), inputRecordCounter);
        }
      } else {
        TaskSplitMetaInfo[] allMetaInfo = MRInputUtils.readSplits(jobConf);
        TaskSplitMetaInfo thisTaskMetaInfo = allMetaInfo[getContext().getTaskIndex()];
        TaskSplitIndex splitMetaInfo = new TaskSplitIndex(thisTaskMetaInfo.getSplitLocation(),
            thisTaskMetaInfo.getStartOffset());
        if (useNewApi) {
          org.apache.hadoop.mapreduce.InputSplit newInputSplit = MRInputUtils
              .getNewSplitDetailsFromDisk(splitMetaInfo, jobConf, getContext().getCounters()
                  .findCounter(TaskCounter.SPLIT_RAW_BYTES));
          mrReader = new MRReaderMapReduce(jobConf, newInputSplit, getContext().getCounters(),
              inputRecordCounter, getContext().getApplicationId().getClusterTimestamp(),
              getContext().getTaskVertexIndex(), getContext().getApplicationId().getId(),
              getContext().getTaskIndex(), getContext().getTaskAttemptNumber());
        } else {
          org.apache.hadoop.mapred.InputSplit oldInputSplit = MRInputUtils
              .getOldSplitDetailsFromDisk(splitMetaInfo, jobConf, getContext().getCounters()
                  .findCounter(TaskCounter.SPLIT_RAW_BYTES));
          mrReader =
              new MRReaderMapred(jobConf, oldInputSplit, getContext().getCounters(),
                  inputRecordCounter);
        }
      }
    } finally {
      rrLock.unlock();
    }
    LOG.info("Initialzed MRInput: " + getContext().getSourceVertexName());
  }

  /**
   * Returns a {@link KeyValueReader} that can be used to read
   * Map Reduce compatible key value data. An exception will be thrown if next()
   * is invoked after false, either from the framework or from the underlying InputFormat
   */
  @Override
  public KeyValueReader getReader() throws IOException {
    Preconditions
        .checkState(readerCreated == false,
            "Only a single instance of record reader can be created for this input.");
    readerCreated = true;
    if (getNumPhysicalInputs() == 0) {
      return new KeyValueReader() {
        @Override
        public boolean next() throws IOException {
          return false;
        }

        @Override
        public Object getCurrentKey() throws IOException {
          return null;
        }

        @Override
        public Object getCurrentValue() throws IOException {
          return null;
        }
      };
    }
    rrLock.lock();
    try {
      if (!mrReader.isSetup())
        checkAndAwaitRecordReaderInitialization();
    } finally {
      rrLock.unlock();
    }

    return mrReader;
  }

  @Override
  public void handleEvents(List<Event> inputEvents) throws Exception {
    if (getNumPhysicalInputs() == 0) {
      throw new IllegalStateException(
          "Unexpected event. MRInput has been setup to receive 0 events");
    }
    if (eventReceived || inputEvents.size() != 1) {
      throw new IllegalStateException(
          "MRInput expects only a single input. Received: current eventListSize: "
              + inputEvents.size() + "Received previous input: "
              + eventReceived);
    }
    Event event = inputEvents.iterator().next();
    Preconditions.checkArgument(event instanceof InputDataInformationEvent,
        getClass().getSimpleName()
            + " can only handle a single event of type: "
            + InputDataInformationEvent.class.getSimpleName());

    processSplitEvent((InputDataInformationEvent) event);
  }

  @Override
  public List<Event> close() throws IOException {
    mrReader.close();
    long inputRecords = getContext().getCounters()
        .findCounter(TaskCounter.INPUT_RECORDS_PROCESSED).getValue();
    getContext().getStatisticsReporter().reportItemsProcessed(inputRecords);

    return null;
  }

  /**
   * {@link MRInput} sets some additional parameters like split location when using
   * the new API. This methods returns the list of additional updates, and
   * should be used by Processors using the old MapReduce API with {@link MRInput}.
   *
   * @return the additional fields set by {@link MRInput}
   */
  public Configuration getConfigUpdates() {
    if (!useNewApi) {
      return ((MRReaderMapred) mrReader).getConfigUpdates();
    } else {
      return null;
    }
  }

  public float getProgress() throws IOException, InterruptedException {
    return mrReader.getProgress();
  }

  void processSplitEvent(InputDataInformationEvent event)
      throws IOException {
    rrLock.lock();
    try {
      initFromEventInternal(event);
      LOG.info("Notifying on RecordReader Initialized");
      rrInited.signal();
    } finally {
      rrLock.unlock();
    }
  }

  void checkAndAwaitRecordReaderInitialization() throws IOException {
    assert rrLock.getHoldCount() == 1;
    rrLock.lock();
    try {
      LOG.info("Awaiting RecordReader initialization");
      rrInited.await();
    } catch (Exception e) {
      throw new IOException(
          "Interrupted waiting for RecordReader initiailization");
    } finally {
      rrLock.unlock();
    }
  }

  @Private
  void initFromEvent(InputDataInformationEvent initEvent)
      throws IOException {
    rrLock.lock();
    try {
      initFromEventInternal(initEvent);
    } finally {
      rrLock.unlock();
    }
  }

  private void initFromEventInternal(InputDataInformationEvent initEvent) throws IOException {
    LOG.info("Initializing RecordReader from event");
    Preconditions.checkState(initEvent != null, "InitEvent must be specified");
    MRSplitProto splitProto = MRSplitProto.parseFrom(ByteString.copyFrom(initEvent.getUserPayload()));
    Object split = null;
    if (useNewApi) {
      split = MRInputUtils.getNewSplitDetailsFromEvent(splitProto, jobConf);
      LOG.info("Split Details -> SplitClass: " + split.getClass().getName() + ", NewSplit: "
          + split);

    } else {
      split = MRInputUtils.getOldSplitDetailsFromEvent(splitProto, jobConf);
      LOG.info("Split Details -> SplitClass: " + split.getClass().getName() + ", OldSplit: "
          + split);
    }
    mrReader.setSplit(split);
    LOG.info("Initialized RecordReader from event");
  }

  private static class MRInputHelpersInternal extends MRInputHelpers {

    protected static UserPayload createMRInputPayloadWithGrouping(Configuration conf) throws
        IOException {
      return MRInputHelpers.createMRInputPayloadWithGrouping(conf);
    }

    protected static UserPayload createMRInputPayload(Configuration conf,
                                                 MRRuntimeProtos.MRSplitsProto mrSplitsProto) throws
        IOException {
      return MRInputHelpers.createMRInputPayload(conf, mrSplitsProto);
    }
  }

}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

return array(
     'controllers' => array(
         'invokables' => array(
             'Post\Controller\Post' => 'Post\Controller\PostController',
         ),
     ),

     // The following section is new and should be added to your file
     'router' => array(
         'routes' => array(
             'post' => array(
                 'type'    => 'segment',
                 'options' => array(
                     'route'    => '/post[/][:action][/:id]',
                     'constraints' => array(
                         'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                         'id'     => '[0-9]+',
                     ),
                     'defaults' => array(
                         'controller' => 'Post\Controller\Post',
                         'action'     => 'index',
                     ),
                 ),
             ),
         ),
     ),

     'view_manager' => array(
         'template_path_stack' => array(
             'post' => __DIR__ . '/../view',
         ),
     ),
 );


text:
<?php

//注册插件
RegisterPlugin("WhitePage", "ActivePlugin_WhitePage");

function ActivePlugin_WhitePage()
{
    global $zbp;
    $zbp->LoadLanguage('theme', 'WhitePage');

    Add_Filter_Plugin('Filter_Plugin_Cmd_Begin', 'WhitePage_CMT');
    Add_Filter_Plugin('Filter_Plugin_Admin_TopMenu', 'WhitePage_AddMenu');
    if ($zbp->Config('WhitePage')->SuperFast) {
        Add_Filter_Plugin('Filter_Plugin_Html_Js_Add', 'WhitePage_SuperFast_Pre');
    } else {
        Add_Filter_Plugin('Filter_Plugin_Html_Js_Add', 'WhitePage_AddJS');
    }
    if($zbp->HasConfig('WhitePage') && isset($zbp->html_js_hash)){
        $zbp->html_js_hash .= crc32((string)$zbp->Config('WhitePage'));
    }

    $s = '';
    if ($zbp->Config('WhitePage')->HasKey("custom_bgcolor")) {
        $s .= "body{background-color:#" . $zbp->Config('WhitePage')->custom_bgcolor . ";}div.post-body>p>code,div.post-body>pre.prism-highlight,div.post-body blockquote{background-color:#" . $zbp->Config('WhitePage')->custom_bgcolor . ";}";
    }
    if ($zbp->Config('WhitePage')->HasKey("custom_pagecolor")) {
        $s .= "textarea,input[type=text],input[type=password],#divNavBar li ul{background-color:#" . $zbp->Config('WhitePage')->custom_pagecolor . "}";
    }
    if ($zbp->Config('WhitePage')->HasKey("custom_fontcolor")) {
        $s .= "body{color:#" . $zbp->Config('WhitePage')->custom_fontcolor . ";}textarea,input[type=text],input[type=password]{color:#" . $zbp->Config('WhitePage')->custom_fontcolor . ";}";
    }
    if ($zbp->Config('WhitePage')->HasKey("custom_acolor")) {
        $s .= "a,span.now-page,#BlogTitle a{color:#" . $zbp->Config('WhitePage')->custom_acolor . ";}";
    }
    if ($zbp->Config('WhitePage')->HasKey("custom_ahovercolor")) {
        $s .= "a:hover,a:hover span.page,#BlogTitle a:hover,#divNavBar a:hover{color:#" . $zbp->Config('WhitePage')->custom_ahovercolor . ";}";
    }
    if ($zbp->Config('WhitePage')->HasKey("custom_blogtitlecolor")) {
        $s .= "#BlogTitle a{color:#" . $zbp->Config('WhitePage')->custom_blogtitlecolor . ";}";
    }
    if ($zbp->Config('WhitePage')->HasKey("text_indent")) {
        $s .= "div.post-body p{text-indent:" . (int) $zbp->Config('WhitePage')->text_indent . "em;}";
    }
    if ($zbp->Config('WhitePage')->HasKey("custom_pagetype")) {
        if ($zbp->Config('WhitePage')->custom_pagetype == 2) {
            $s .= "#divAll{box-shadow: 0 0 0.6em #333;border-radius: 0;}";
            $s .= "#divAll{background:#" . $zbp->Config('WhitePage')->custom_pagecolor . ";}#divMiddle{background:none;}";
        } elseif ($zbp->Config('WhitePage')->custom_pagetype == 3) {
            $s .= "#divAll{box-shadow: 0 0 0.6em #333;border-radius: 1em;}";
            $s .= "#divAll{background:#" . $zbp->Config('WhitePage')->custom_pagecolor . ";}#divMiddle{background:none;}";
        } elseif ($zbp->Config('WhitePage')->custom_pagetype == 4) {
            $s .= "#divAll{box-shadow: none;border-radius: 0;}";
            $s .= "#divAll{background:#" . $zbp->Config('WhitePage')->custom_pagecolor . ";}#divMiddle{background:none;}";
        } elseif ($zbp->Config('WhitePage')->custom_pagetype == 5) {
            $s .= "#divAll{box-shadow: none;border-radius: 1em;}";
            $s .= "#divAll{background:#" . $zbp->Config('WhitePage')->custom_pagecolor . ";}#divMiddle{background:none;}";
        } else {
            $s .= "#divAll{background:none;}#divMiddle{background:none;}";
        }
    }

    $zbp->header .= '    <style>' . $s . '</style>' . "\r\n";
    $zbp->lang['msg']['first_button'] = '<<';
    $zbp->lang['msg']['prev_button'] = '<';
    $zbp->lang['msg']['next_button'] = '>';
    $zbp->lang['msg']['last_button'] = '>>';
    Add_Filter_Plugin('Filter_Plugin_ViewSearch_Begin', 'WhitePage_ViewSearch_Begin');
}

function WhitePage_ViewSearch_Begin()
{
    global $zbp;
    $zbp->option['ZC_SEARCH_TYPE'] = 'list';
}

function InstallPlugin_WhitePage()
{
    global $zbp;
}

function UninstallPlugin_WhitePage()
{
    global $zbp;
}

function WhitePage_CMT()
{
    global $zbp, $action;

    if ($action == 'cmt') {
        if (empty($zbp->user->ID) == false) {
            $_POST['email'] = $zbp->user->Email;
            $_POST['homepage'] = $zbp->user->HomePage;
            $_POST['name'] = $zbp->user->Name;
        }
    }
}

function WhitePage_AddMenu(&$m)
{
    global $zbp;
    $m[] = MakeTopMenu("root", $zbp->lang['WhitePage']['theme_config'], $zbp->host . "zb_users/theme/WhitePage/main.php", "", "topmenu_WhitePage","icon-nut-fill");
}

function WhitePage_AddJS($echo = true)
{
    $s = <<<JS
$(function() {
    var s = document.location;
    $("#divNavBar a").each(function() {
        if (this.href == s.toString().split("#")[0]) {
            $(this).addClass("on");
            return false;
        }
    });
});

zbp.plugin.unbind("comment.reply.start", "system");
/*重写了common.js里的同名函数*/
zbp.plugin.on("comment.reply.start", "WhitePage", function(id) {
    var i = id;
    $("#inpRevID").val(i);
    var frm = $('#divCommentPost'),
        cancel = $("#cancel-reply"),
        temp = $('#temp-frm');

    var div = document.createElement('div');
    div.id = 'temp-frm';
    div.style.display = 'none';
    frm.before(div);

    $('#AjaxComment' + i).before(frm);

    frm.addClass("reply-frm");

    cancel.show();
    cancel.click(function() {
        $("#inpRevID").val(0);
        var temp = $('#temp-frm'),
            frm = $('#divCommentPost');
        if (!temp.length || !frm.length) return;
        temp.before(frm);
        temp.remove();
        $(this).hide();
        frm.removeClass("reply-frm");
        return false;
    });
    try {
        $('#txaArticle').focus();
    } catch (e) {}
    return false;
});

/*重写GetComments,防止评论框消失*/
zbp.plugin.on("comment.get", "WhitePage", function (logid, page) {
    $('span.commentspage').html("Waiting...");
    $.get(bloghost + "zb_system/cmd.php?act=getcmt&postid=" + logid + "&page=" + page, function(data) {
        $('#AjaxCommentBegin').nextUntil('#AjaxCommentEnd').remove();
        $('#AjaxCommentEnd').before(data);
        $("#cancel-reply").click();
    });
});

zbp.plugin.on("comment.post.success", "WhitePage", function () {
    $("#cancel-reply").click();
});
JS;

    if ($echo) {
        echo $s;
    }

    return $s;
}

function WhitePage_SuperFast_Pre()
{
    Add_Filter_Plugin('Filter_Plugin_Html_Js_Add', 'WhitePage_SuperFast');
}

function WhitePage_SuperFast()
{
    $s = ob_get_clean();
    $zbpjs = file_get_contents(ZBP_PATH . 'zb_system/script/zblogphp.js');
    $jqjs = file_get_contents(ZBP_PATH . 'zb_system/script/jquery-2.2.4.min.js');
    $js = WhitePage_AddJS(false);
    $s = $jqjs . PHP_EOL . $zbpjs . PHP_EOL . $s . PHP_EOL . $js;
    //$s = str_replace(array("\n", "\r"), '', $s);
    $m = 'W/' . md5($s);

    header('Content-Type: application/x-javascript; charset=utf-8');
    header('Etag: ' . $m);

    if (isset($_SERVER["HTTP_IF_NONE_MATCH"]) && $_SERVER["HTTP_IF_NONE_MATCH"] == $m) {
        SetHttpStatusCode(304);
        die;
    }

    echo $s;
    die;
}


text:
<?xml version="1.0" ?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements. See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License. You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<template encoding-version="1.1">
  <description></description>
  <groupId>27b7b6b8-015f-1000-0d31-197ae42bab34</groupId>
  <name>S2STransfer</name>
  <snippet>
    <connections>
      <id>157c6a56-3753-304d-0000-000000000000</id>
      <parentGroupId>c81f8a46-4aa3-313e-0000-000000000000</parentGroupId>
      <backPressureDataSizeThreshold>1 GB</backPressureDataSizeThreshold>
      <backPressureObjectThreshold>10000</backPressureObjectThreshold>
      <destination>
        <groupId>c81f8a46-4aa3-313e-0000-000000000000</groupId>
        <id>392e7343-3950-329b-0000-000000000000</id>
        <type>OUTPUT_PORT</type>
      </destination>
      <flowFileExpiration>0 sec</flowFileExpiration>
      <labelIndex>1</labelIndex>
      <name></name>
      <selectedRelationships>success</selectedRelationships>
      <source>
        <groupId>c81f8a46-4aa3-313e-0000-000000000000</groupId>
        <id>1b9f81db-a0fd-389a-0000-000000000000</id>
        <type>PROCESSOR</type>
      </source>
      <zIndex>0</zIndex>
    </connections>
    <outputPorts>
      <id>392e7343-3950-329b-0000-000000000000</id>
      <parentGroupId>c81f8a46-4aa3-313e-0000-000000000000</parentGroupId>
      <position>
        <x>53.43126270299064</x>
        <y>267.91819788476437</y>
      </position>
      <concurrentlySchedulableTaskCount>1</concurrentlySchedulableTaskCount>
      <name>output</name>
      <state>RUNNING</state>
      <transmitting>false</transmitting>
      <type>OUTPUT_PORT</type>
    </outputPorts>
    <processors>
      <id>1b9f81db-a0fd-389a-0000-000000000000</id>
      <parentGroupId>c81f8a46-4aa3-313e-0000-000000000000</parentGroupId>
      <position>
        <x>0.0</x>
        <y>0.0</y>
      </position>
      <bundle>
        <artifact>nifi-standard-nar</artifact>
        <group>org.apache.nifi</group>
        <version>1.5.0-SNAPSHOT</version>
      </bundle>
      <config>
        <bulletinLevel>WARN</bulletinLevel>
        <comments></comments>
        <concurrentlySchedulableTaskCount>1</concurrentlySchedulableTaskCount>
        <descriptors>
          <entry>
            <key>File Size</key>
            <value>
              <name>File Size</name>
            </value>
          </entry>
          <entry>
            <key>Batch Size</key>
            <value>
              <name>Batch Size</name>
            </value>
          </entry>
          <entry>
            <key>Data Format</key>
            <value>
              <name>Data Format</name>
            </value>
          </entry>
          <entry>
            <key>Unique FlowFiles</key>
            <value>
              <name>Unique FlowFiles</name>
            </value>
          </entry>
          <entry>
            <key>generate-ff-custom-text</key>
            <value>
              <name>generate-ff-custom-text</name>
            </value>
          </entry>
          <entry>
            <key>character-set</key>
            <value>
              <name>character-set</name>
            </value>
          </entry>
        </descriptors>
        <executionNode>ALL</executionNode>
        <lossTolerant>false</lossTolerant>
        <penaltyDuration>30 sec</penaltyDuration>
        <properties>
          <entry>
            <key>File Size</key>
            <value>0B</value>
          </entry>
          <entry>
            <key>Batch Size</key>
            <value>1</value>
          </entry>
          <entry>
            <key>Data Format</key>
            <value>Text</value>
          </entry>
          <entry>
            <key>Unique FlowFiles</key>
            <value>false</value>
          </entry>
          <entry>
            <key>generate-ff-custom-text</key>
          </entry>
          <entry>
            <key>character-set</key>
            <value>UTF-8</value>
          </entry>
        </properties>
        <runDurationMillis>0</runDurationMillis>
        <schedulingPeriod>1d</schedulingPeriod>
        <schedulingStrategy>TIMER_DRIVEN</schedulingStrategy>
        <yieldDuration>1 sec</yieldDuration>
      </config>
      <name>GenerateFlowFile</name>
      <relationships>
        <autoTerminate>false</autoTerminate>
        <name>success</name>
      </relationships>
      <state>RUNNING</state>
      <style></style>
      <type>org.apache.nifi.processors.standard.GenerateFlowFile</type>
    </processors>
  </snippet>
  <timestamp>10/20/2017 17:48:34 JST</timestamp>
</template>


text:
package apiutil

import (
	"net/http"
	"net/url"
	"time"

	"github.com/juju/errors"
	"github.com/pingcap/kvproto/pkg/metapb"
	"github.com/pingcap/kvproto/pkg/pdpb"
)

const (
	apiPrefix = "/pd/api/v1"
)

// Client is a client to access PD APIs.
type Client struct {
	hc  *http.Client
	url string
}

// NewClient returns a client to access PD APIs.
func NewClient(addr string, timeout time.Duration) (*Client, error) {
	u, err := url.Parse(addr)
	if err != nil {
		return nil, errors.Trace(err)
	}
	u.Path = apiPrefix

	scheme := u.Scheme
	if u.Scheme == "unix" || u.Scheme == "unixs" {
		u.Scheme = "http"
	}

	client := &Client{
		hc:  NewHTTPClient(scheme, timeout),
		url: u.String(),
	}
	return client, nil
}

// GetLeader returns the PD leader info.
func (c *Client) GetLeader() (*pdpb.Member, error) {
	leaderURL := c.url + "/leader"
	resp, err := c.hc.Get(leaderURL)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if resp.StatusCode != http.StatusOK {
		return nil, errors.Errorf("GET %s: %s", leaderURL, resp.Status)
	}
	leader := &pdpb.Member{}
	if err := ReadJSON(resp.Body, leader); err != nil {
		return nil, errors.Trace(err)
	}
	return leader, nil
}

// GetClusterID returns the Cluster ID.
func (c *Client) GetClusterID() (uint64, error) {
	clusterURL := c.url + "/cluster"
	resp, err := c.hc.Get(clusterURL)
	if err != nil {
		return 0, errors.Trace(err)
	}
	if resp.StatusCode != http.StatusOK {
		return 0, errors.Errorf("GET %s: %s", clusterURL, resp.Status)
	}
	cluster := &metapb.Cluster{}
	if err := ReadJSON(resp.Body, cluster); err != nil {
		return 0, errors.Trace(err)
	}
	return cluster.GetId(), nil
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Encycl. 1:49, t. 356. 1783

#### Original name
null

### Remarks
null