text:
package elastic

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"github.com/olivere/elastic/v7/uritemplates"
)

// ExistsService checks for the existence of a document using HEAD.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-get.html
// for details.
type ExistsService struct {
	client *Client

	pretty     *bool       // pretty format the returned JSON response
	human      *bool       // return human readable values for statistics
	errorTrace *bool       // include the stack trace of returned errors
	filterPath []string    // list of filters used to reduce the response
	headers    http.Header // custom request-level HTTP headers

	id         string
	index      string
	typ        string
	preference string
	realtime   *bool
	refresh    string
	routing    string
	parent     string
}

// NewExistsService creates a new ExistsService.
func NewExistsService(client *Client) *ExistsService {
	return &ExistsService{
		client: client,
		typ:    "_doc",
	}
}

// Pretty tells Elasticsearch whether to return a formatted JSON response.
func (s *ExistsService) Pretty(pretty bool) *ExistsService {
	s.pretty = &pretty
	return s
}

// Human specifies whether human readable values should be returned in
// the JSON response, e.g. "7.5mb".
func (s *ExistsService) Human(human bool) *ExistsService {
	s.human = &human
	return s
}

// ErrorTrace specifies whether to include the stack trace of returned errors.
func (s *ExistsService) ErrorTrace(errorTrace bool) *ExistsService {
	s.errorTrace = &errorTrace
	return s
}

// FilterPath specifies a list of filters used to reduce the response.
func (s *ExistsService) FilterPath(filterPath ...string) *ExistsService {
	s.filterPath = filterPath
	return s
}

// Header adds a header to the request.
func (s *ExistsService) Header(name string, value string) *ExistsService {
	if s.headers == nil {
		s.headers = http.Header{}
	}
	s.headers.Add(name, value)
	return s
}

// Headers specifies the headers of the request.
func (s *ExistsService) Headers(headers http.Header) *ExistsService {
	s.headers = headers
	return s
}

// Id is the document ID.
func (s *ExistsService) Id(id string) *ExistsService {
	s.id = id
	return s
}

// Index is the name of the index.
func (s *ExistsService) Index(index string) *ExistsService {
	s.index = index
	return s
}

// Type is the type of the document (use `_all` to fetch the first document
// matching the ID across all types).
func (s *ExistsService) Type(typ string) *ExistsService {
	s.typ = typ
	return s
}

// Preference specifies the node or shard the operation should be performed on (default: random).
func (s *ExistsService) Preference(preference string) *ExistsService {
	s.preference = preference
	return s
}

// Realtime specifies whether to perform the operation in realtime or search mode.
func (s *ExistsService) Realtime(realtime bool) *ExistsService {
	s.realtime = &realtime
	return s
}

// Refresh the shard containing the document before performing the operation.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html
// for details.
func (s *ExistsService) Refresh(refresh string) *ExistsService {
	s.refresh = refresh
	return s
}

// Routing is a specific routing value.
func (s *ExistsService) Routing(routing string) *ExistsService {
	s.routing = routing
	return s
}

// Parent is the ID of the parent document.
func (s *ExistsService) Parent(parent string) *ExistsService {
	s.parent = parent
	return s
}

// buildURL builds the URL for the operation.
func (s *ExistsService) buildURL() (string, url.Values, error) {
	// Build URL
	path, err := uritemplates.Expand("/{index}/{type}/{id}", map[string]string{
		"id":    s.id,
		"index": s.index,
		"type":  s.typ,
	})
	if err != nil {
		return "", url.Values{}, err
	}

	// Add query string parameters
	params := url.Values{}
	if v := s.pretty; v != nil {
		params.Set("pretty", fmt.Sprint(*v))
	}
	if v := s.human; v != nil {
		params.Set("human", fmt.Sprint(*v))
	}
	if v := s.errorTrace; v != nil {
		params.Set("error_trace", fmt.Sprint(*v))
	}
	if len(s.filterPath) > 0 {
		params.Set("filter_path", strings.Join(s.filterPath, ","))
	}
	if s.realtime != nil {
		params.Set("realtime", fmt.Sprint(*s.realtime))
	}
	if s.refresh != "" {
		params.Set("refresh", s.refresh)
	}
	if s.routing != "" {
		params.Set("routing", s.routing)
	}
	if s.parent != "" {
		params.Set("parent", s.parent)
	}
	if s.preference != "" {
		params.Set("preference", s.preference)
	}
	return path, params, nil
}

// Validate checks if the operation is valid.
func (s *ExistsService) Validate() error {
	var invalid []string
	if s.id == "" {
		invalid = append(invalid, "Id")
	}
	if s.index == "" {
		invalid = append(invalid, "Index")
	}
	if s.typ == "" {
		invalid = append(invalid, "Type")
	}
	if len(invalid) > 0 {
		return fmt.Errorf("missing required fields: %v", invalid)
	}
	return nil
}

// Do executes the operation.
func (s *ExistsService) Do(ctx context.Context) (bool, error) {
	// Check pre-conditions
	if err := s.Validate(); err != nil {
		return false, err
	}

	// Get URL for request
	path, params, err := s.buildURL()
	if err != nil {
		return false, err
	}

	// Get HTTP response
	res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
		Method:       "HEAD",
		Path:         path,
		Params:       params,
		IgnoreErrors: []int{404},
		Headers:      s.headers,
	})
	if err != nil {
		return false, err
	}

	// Return operation response
	switch res.StatusCode {
	case http.StatusOK:
		return true, nil
	case http.StatusNotFound:
		return false, nil
	default:
		return false, fmt.Errorf("elastic: got HTTP code %d when it should have been either 200 or 404", res.StatusCode)
	}
}


text:
package udf;
import java.io.IOException;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;

public class LEAP extends EvalFunc<Boolean>
{
    public Boolean exec(Tuple input) throws IOException {
        if (input == null || input.size() == 0 || input.get(0) == null)
            return null;
        try{
            int number = ((Integer)input.get(0)).intValue();
            return new Boolean(number%4==0 && number%100!=0);
        }catch(Exception e){
            throw new IOException("Caught exception processing input row ", e);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package java.awt.image;

/**
 * This class extends DataBuffer and stores data internally
 * in float form.
 *
 * @see DataBuffer
 * @since 1.4
 */

public final class DataBufferFloat extends DataBuffer {

    /** The array of data banks. */
    float bankdata[][];

    /** A reference to the default data bank. */
    float data[];

    /**
     * Constructs a float-based DataBuffer
     * with a specified size.
     *
     * @param size The number of elements in the DataBuffer.
     */
    public DataBufferFloat(int size) {
        super(TYPE_FLOAT, size);
        data = new float[size];
        bankdata = new float[1][];
        bankdata[0] = data;
    }

    /**
     * Constructs a float-based DataBuffer
     * with a specified number of banks, all of which are of a
     * specified size.
     *
     * @param size The number of elements in each bank of the
     * DataBuffer.
     * @param numBanks The number of banks in the
     *        DataBuffer.
     */
    public DataBufferFloat(int size, int numBanks) {
        super(TYPE_FLOAT, size, numBanks);
        bankdata = new float[numBanks][];
        for (int i= 0; i < numBanks; i++) {
            bankdata[i] = new float[size];
        }
        data = bankdata[0];
    }

    /**
     * Constructs a float-based DataBuffer
     * with the specified data array.  Only the first
     * size elements are available for use by this
     * DataBuffer.  The array must be large enough to
     * hold size elements.
     *
     * @param dataArray An array of floats to be used as the
     *                  first and only bank of this DataBuffer.
     * @param size The number of elements of the array to be used.
     */
    public DataBufferFloat(float dataArray[], int size) {
        super(TYPE_FLOAT, size);
        data = dataArray;
        bankdata = new float[1][];
        bankdata[0] = data;
    }

    /**
     * Constructs a float-based DataBuffer
     * with the specified data array.  Only the elements between
     * offset and offset + size - 1 are
     * available for use by this DataBuffer.  The array
     * must be large enough to hold offset + size
     * elements.
     *
     * @param dataArray An array of floats to be used as the
     *                  first and only bank of this DataBuffer.
     * @param size The number of elements of the array to be used.
     * @param offset The offset of the first element of the array
     *               that will be used.
     */
    public DataBufferFloat(float dataArray[], int size, int offset) {
        super(TYPE_FLOAT, size, 1, offset);
        data = dataArray;
        bankdata = new float[1][];
        bankdata[0] = data;
    }

    /**
     * Constructs a float-based DataBuffer
     * with the specified data arrays.  Only the first
     * size elements of each array are available for use
     * by this DataBuffer.  The number of banks will be
     * equal to dataArray.length.
     *
     * @param dataArray An array of arrays of floats to be
     *                  used as the banks of this DataBuffer.
     * @param size The number of elements of each array to be used.
     */
    public DataBufferFloat(float dataArray[][], int size) {
        super(TYPE_FLOAT, size, dataArray.length);
        bankdata = (float[][]) dataArray.clone();
        data = bankdata[0];
    }

    /**
     * Constructs a float-based DataBuffer
     * with the specified data arrays, size, and per-bank offsets.
     * The number of banks is equal to dataArray.length.
     * Each array must be at least as large as size plus the
     * corresponding offset.  There must be an entry in the offsets
     * array for each data array.
     *
     * @param dataArray An array of arrays of floats to be
     *                  used as the banks of this DataBuffer.
     * @param size The number of elements of each array to be used.
     * @param offsets An array of integer offsets, one for each bank.
     */
    public DataBufferFloat(float dataArray[][], int size, int offsets[]) {
        super(TYPE_FLOAT, size,dataArray.length, offsets);
        bankdata = (float[][]) dataArray.clone();
        data = bankdata[0];
    }

    /**
     * Returns the default (first) float data array.
     * @return the first float data array.
     */
    public float[] getData() {
        return data;
    }

    /**
     * Returns the data array for the specified bank.
     * @param bank the data array
     * @return the data array specified by bank.
     */
    public float[] getData(int bank) {
        return bankdata[bank];
    }

    /**
     * Returns the data array for all banks.
     * @return all data arrays for this data buffer.
     */
    public float[][] getBankData() {
        return (float[][]) bankdata.clone();
    }

    /**
     * Returns the requested data array element from the first
     * (default) bank as an int.
     *
     * @param i The desired data array element.
     *
     * @return The data entry as an int.
     * @see #setElem(int, int)
     * @see #setElem(int, int, int)
     */
    public int getElem(int i) {
        return (int)(data[i+offset]);
    }

    /**
     * Returns the requested data array element from the specified
     * bank as an int.
     *
     * @param bank The bank number.
     * @param i The desired data array element.
     *
     * @return The data entry as an int.
     * @see #setElem(int, int)
     * @see #setElem(int, int, int)
     */
    public int getElem(int bank, int i) {
        return (int)(bankdata[bank][i+offsets[bank]]);
    }

    /**
     * Sets the requested data array element in the first (default)
     * bank to the given int.
     *
     * @param i The desired data array element.
     * @param val The value to be set.
     * @see #getElem(int)
     * @see #getElem(int, int)
     */
    public void setElem(int i, int val) {
        data[i+offset] = (float)val;
    }

    /**
     * Sets the requested data array element in the specified bank to
     * the given int.
     *
     * @param bank The bank number.
     * @param i The desired data array element.
     * @param val The value to be set.
     * @see #getElem(int)
     * @see #getElem(int, int)
     */
    public void setElem(int bank, int i, int val) {
        bankdata[bank][i+offsets[bank]] = (float)val;
    }

    /**
     * Returns the requested data array element from the first
     * (default) bank as a float.
     *
     * @param i The desired data array element.
     *
     * @return The data entry as a float.
     * @see #setElemFloat(int, float)
     * @see #setElemFloat(int, int, float)
     */
    public float getElemFloat(int i) {
        return data[i+offset];
    }

    /**
     * Returns the requested data array element from the specified
     * bank as a float.
     *
     * @param bank The bank number.
     * @param i The desired data array element.
     *
     * @return The data entry as a float.
     * @see #setElemFloat(int, float)
     * @see #setElemFloat(int, int, float)
     */
    public float getElemFloat(int bank, int i) {
        return bankdata[bank][i+offsets[bank]];
    }

    /**
     * Sets the requested data array element in the first (default)
     * bank to the given float.
     *
     * @param i The desired data array element.
     * @param val The value to be set.
     * @see #getElemFloat(int)
     * @see #getElemFloat(int, int)
     */
    public void setElemFloat(int i, float val) {
        data[i+offset] = val;
    }

    /**
     * Sets the requested data array element in the specified bank to
     * the given float.
     *
     * @param bank The bank number.
     * @param i The desired data array element.
     * @param val The value to be set.
     * @see #getElemFloat(int)
     * @see #getElemFloat(int, int)
     */
    public void setElemFloat(int bank, int i, float val) {
        bankdata[bank][i+offsets[bank]] = val;
    }

    /**
     * Returns the requested data array element from the first
     * (default) bank as a double.
     *
     * @param i The desired data array element.
     *
     * @return The data entry as a double.
     * @see #setElemDouble(int, double)
     * @see #setElemDouble(int, int, double)
     */
    public double getElemDouble(int i) {
        return (double)data[i+offset];
    }

    /**
     * Returns the requested data array element from the specified
     * bank as a double.
     *
     * @param bank The bank number.
     * @param i The desired data array element.
     *
     * @return The data entry as a double.
     * @see #setElemDouble(int, double)
     * @see #setElemDouble(int, int, double)
     */
    public double getElemDouble(int bank, int i) {
        return (double)bankdata[bank][i+offsets[bank]];
    }

    /**
     * Sets the requested data array element in the first (default)
     * bank to the given double.
     *
     * @param i The desired data array element.
     * @param val The value to be set.
     * @see #getElemDouble(int)
     * @see #getElemDouble(int, int)
     */
    public void setElemDouble(int i, double val) {
        data[i+offset] = (float)val;
    }

    /**
     * Sets the requested data array element in the specified bank to
     * the given double.
     *
     * @param bank The bank number.
     * @param i The desired data array element.
     * @param val The value to be set.
     * @see #getElemDouble(int)
     * @see #getElemDouble(int, int)
     */
    public void setElemDouble(int bank, int i, double val) {
        bankdata[bank][i+offsets[bank]] = (float)val;
    }
}


text:
import os
import csv
import codecs

class Source:
    params = {}
    reader = None

    def __init__(self, params):
        if 'encoding' not in params:
            params['encoding'] = 'utf-8'
        self.params = params

        if not os.path.isfile(params['filename']):
            raise Exception('%s 文件不存在' % params['filename'])

        self.csvfile = open(params['filename'], 'r', encoding=params['encoding'])
        if 'delimiter' not in params:
            params['delimiter'] = ','

        self.reader = csv.DictReader(
            self.csvfile, delimiter=params['delimiter'])

    def next(self):
        for row in self.reader:
            yield row

    def __del__(self):
        self.csvfile.close()


text:
package ru.sfedu.mmcs.portfolio;

import ru.sfedu.mmcs.portfolio.frontier.Frontier;
import ru.sfedu.mmcs.portfolio.frontier.FrontierValue;
import ru.sfedu.mmcs.portfolio.loaders.DataLoader;

public class AnalyzerData extends Analyzer {

	@Override
	public void loadData(DataLoader loader) {
		super.loadData(loader);
	}

	public Frontier getResult()
	{
		return _frontier;
	}

	private FrontierValue _frontier;
	@Override
	protected void calculate() {
		_frontier = new FrontierValue(this._data);
	}
}


text:
package com.gmail.trentech.EKcore.core.utils;

public class Resource {

	public final static String NAME = "EKcore";
	public final static String VERSION = "0.6.4";
	public final static String ID = "EKcore";
}


text:
var spawn = require('child_process').spawn;

module.exports = function(opts, cb) {
  // path to GAP executable
  var GAP_PATH = opts.path;
  // path to a generate workspace
  var WORKSPACE_PATH = opts.workspace;
  // executable args
  // -q silent mode
  // -L workspace path flag
  var args = ['-q', '-L', WORKSPACE_PATH];
  // spawn a new GAP process.
  var gap = spawn(GAP_PATH, args);
  // TODO: find a better solution
  var called = false;
  var errored = false;
  var openMath = opts.input.om;
  // useful digits after . in the result, GAP does simple rounding
  var digits = 3;

  if (typeof opts.input.digits === "number") {
    digits = opts.input.digits + 1;
  }

  // assign a new variable
  gap.stdin.write('FLOAT.VIEW_DIG:=' + digits + ';; s:="' + openMath + '";;\n');

  // evaluate OpenMath string
  var run = 'r:=EvalOMString(s);;\n Float(r); \n';
  gap.stdin.write(run);

  // GAP error output
  gap.stderr.on('data', function (data) {
    if (!errored) {
      errored = true;
      var err = data.toString().replace(/(\r\n|\n|\r)/gm,'');
      cb(err, null);
      gap.stdin.write('quit;;\n');
      gap.kill('SIGHUP');
    }
  });

  // GAP evaluation output
  gap.stdout.on('data', function (data) {
    if (data && !called && !errored) {
      // trims \r and \n
      var out = data.toString().trim();
      if (out.length > 0) {
        called = true;
        cb(null, out);
        gap.kill('SIGHUP');
      }
    }
  });
};


text:
gunzip   *.txt.gz

#
#  Aggregate them into a single file
#
cat 20*.txt  >  ITKUsers.txt


text:
"use strict";

var path = require("path");
var fs = require("fs");

var pkg = fs.readFileSync(path.join(__dirname, "../package.json"), {
    encoding: "utf8"
});
var tpl = fs.readFileSync(path.join(__dirname, "../doc/yeti/project.json.tpl"), {
    encoding: "utf8"
});

pkg = JSON.parse(pkg);

fs.writeFileSync(path.join(__dirname, "../doc/yeti/project.json"), tpl.replace(/@VERSION@/g, pkg.version));


text:
require 'spec_helper'

describe Switch do

  let(:command) { Switch.new(['other-branch']) }
  before do
    command.stub(:current_branch).and_return('test-br')
    command.stub(:other_branch).and_return('other-branch')
  end
  subject { command }

  its(:cmd) { should match /git checkout #{command.other_branch}/ }

  describe "command-line command" do
    subject { `bin/git-switch example --debug` }
    it { should match /git checkout/ }
  end
end


text:
"use strict";

var virtualbox = require('../lib/virtualbox'),
    args = process.argv.slice(2);

virtualbox.acpipowerbutton(args[0], function(error){
  if(error) {
    throw error;
  }
});


text:
require_recipe "postgresql::repo"

# NOTE: Doesn't support non-RedHat distros yet.
# TODO: Support Ubuntu/Debian.

package node.services.postgresql.package_names.odbc do
  action :install
end


text:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace WebApplication2
{
	/// <summary>
	/// Summary description for frmResourcesInfo.
	/// </summary>
	public partial class frmProfileStepsAll: System.Web.UI.Page
	{
		/*SqlConnection epsDbConn=new SqlConnection("Server=cp2693-a\\eps1;database=eps1;"+
			"uid=tauheed;pwd=tauheed;");*/
		private static string strURL =
			System.Configuration.ConfigurationSettings.AppSettings["local_url"];
		private static string strDB =
			System.Configuration.ConfigurationSettings.AppSettings["local_db"];
		public SqlConnection epsDbConn=new SqlConnection(strDB);
		protected void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			loadEvents();
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{

		}
		#endregion
		private void loadEvents()
		{
			if (!IsPostBack)
			{
				lblOrg.Text=Session["OrgName"].ToString();
				lblContent1.Text=Session["ProfileName"].ToString();
				lblContent2.Text="Emergency Procedures";
				loadData();
			}
		}
		private void loadData()
		{
				SqlCommand cmd=new SqlCommand();
				cmd.CommandType=CommandType.StoredProcedure;
				cmd.CommandText="eps_RetrieveStepsAll";
				cmd.Connection=this.epsDbConn;
				cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
				cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
				DataSet ds=new DataSet();
				SqlDataAdapter da=new SqlDataAdapter(cmd);
				da.Fill(ds,"EventSteps");
				Session["ds"] = ds;
				DataGrid1.DataSource=ds;
				DataGrid1.DataBind();
				refreshGrid();
				//assignSequence();
		}

		protected void btnOK_Click(object sender, System.EventArgs e)
		{
				SqlCommand cmd=new SqlCommand();
				cmd.CommandType=CommandType.StoredProcedure;
				cmd.CommandText="eps_DeleteProfileSteps";
				cmd.Connection=this.epsDbConn;
				cmd.Parameters.Add ("@ProfileId",SqlDbType.Int);
				cmd.Parameters["@ProfileId"].Value=Session["ProfileId"].ToString();
				cmd.Connection.Open();
				cmd.ExecuteNonQuery();
				cmd.Connection.Close();
				updateGrid();
				Exit();
		}
		private void updateGrid()
		{
				foreach (DataGridItem i in DataGrid1.Items)
				{
					CheckBox cb = (CheckBox)(i.Cells[2].FindControl("cbxSel"));
					//TextBox tb = (TextBox) (i.Cells[5].FindControl("txtSeq"));
					//if (tb.Text != "")
					if (cb.Checked)
					{
						SqlCommand cmd=new SqlCommand();
						cmd.CommandType=CommandType.StoredProcedure;
						cmd.CommandText="eps_UpdateProfileSteps";
						cmd.Connection=this.epsDbConn;
						cmd.Parameters.Add("@ProfileId", SqlDbType.Int);
						cmd.Parameters ["@ProfileId"].Value=Session["ProfileId"].ToString();
						cmd.Parameters.Add("@StepId", SqlDbType.Int);
						cmd.Parameters ["@StepId"].Value=i.Cells[0].Text;
						//cmd.Parameters.Add("@Seq", SqlDbType.Int);
						//cmd.Parameters ["@Seq"].Value=Int32.Parse(tb.Text);
						cmd.Connection.Open();
						cmd.ExecuteNonQuery();
						cmd.Connection.Close();
					}
				}
		}
		private void refreshGrid()
		{
			foreach (DataGridItem i in DataGrid1.Items)
			{
				CheckBox cb = (CheckBox)(i.Cells[3].FindControl("cbxSel"));
				SqlCommand cmd=new SqlCommand();
				cmd.Connection=this.epsDbConn;
				cmd.CommandType=CommandType.Text;
				cmd.CommandText="Select Id from ProfileSteps"
					+ " Where ProfileId = " + Session["ProfileId"].ToString()
					+ " and StepId = " + i.Cells[0].Text;
				cmd.Connection.Open();
				if (cmd.ExecuteScalar() != null) cb.Checked = true;
				cmd.Connection.Close();
			}
		}
		private void assignSequence()
		{
			foreach (DataGridItem i in DataGrid1.Items)
			{
				Object tmp = new object();
				TextBox tb = (TextBox)(i.Cells[3].FindControl("txtSeq"));
				SqlCommand cmd = new SqlCommand();
				cmd.Connection = this.epsDbConn;
				cmd.CommandType = CommandType.Text;
				cmd.CommandText = "Select Seq from ProfileSteps"
					+ " Where ProfileId = " + Session["ProfileId"].ToString()
					+ " and StepId = " + i.Cells[0].Text;
				cmd.Connection.Open();
				tmp = cmd.ExecuteScalar();
				if (tmp != null) tb.Text = tmp.ToString();
				if (tb.Text == "0") tb.Text = "";
				cmd.Connection.Close();
			}
		}

		private void Exit()
		{
			Response.Redirect (strURL + Session["CallerStepsAll"].ToString() + ".aspx?");
		}
		protected void btnCancel_Click(object sender, System.EventArgs e)
		{
			Response.Redirect (strURL + Session["CallerStepsAll"].ToString() + ".aspx?");
		}
	}

}


text:
package org.apache.juddi.samples;

import java.util.concurrent.atomic.AtomicReference;
import org.apache.juddi.v3.client.config.UDDIClient;
import org.apache.juddi.v3.client.config.UDDIClientContainer;
import org.apache.juddi.v3.client.cryptor.DigSigUtil;
import org.apache.juddi.v3.client.transport.Transport;
import org.uddi.api_v3.*;
import org.uddi.v3_service.UDDIInquiryPortType;
import org.uddi.v3_service.UDDIPublicationPortType;
import org.uddi.v3_service.UDDISecurityPortType;

/**
 * This class shows you how to digitally sign a tmodel and verify the signature
 *
 * @author Alex O'Ree
 */
public class UddiDigitalSignatureTmodel {

        private static UDDISecurityPortType security = null;
        private static UDDIInquiryPortType inquiry = null;
        private static UDDIPublicationPortType publish = null;
        private static UDDIClient clerkManager = null;

        /**
         * This sets up the ws proxies using uddi.xml in META-INF
         */
        public UddiDigitalSignatureTmodel() {
                try {
                        // create a manager and read the config in the archive;
                        // you can use your config file name
                        clerkManager = new UDDIClient("META-INF/simple-publish-uddi.xml");
                        Transport transport = clerkManager.getTransport();
                        // Now you create a reference to the UDDI API
                        security = transport.getUDDISecurityService();
                        inquiry = transport.getUDDIInquiryService();
                        publish = transport.getUDDIPublishService();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }

        /**
         * Main entry point
         *
         * @param args
         */
        public static void main(String args[]) {
                UddiDigitalSignatureTmodel sp = new UddiDigitalSignatureTmodel();
                sp.Fire(null, null);
        }

        public void Fire(String token, String key) {
                try {
                        DigSigUtil ds = null;

                        //option 1), set everything manually
                        ds = new DigSigUtil();
                        ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE, "keystore.jks");
                        ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILETYPE, "JKS");
                        ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE_PASSWORD, "Test");
                        ds.put(DigSigUtil.SIGNATURE_KEYSTORE_KEY_ALIAS, "Test");
                        ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_BASE64, "true");

                        ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_SERIAL, "true");
                        ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_SUBJECTDN, "true");
                        ds.put(DigSigUtil.TRUSTSTORE_FILE, "truststore.jks");
                        ds.put(DigSigUtil.TRUSTSTORE_FILETYPE, "JKS");
                        ds.put(DigSigUtil.TRUSTSTORE_FILE_PASSWORD, "Test");

                        //option 2), load it from the juddi config file
                        //ds = new DigSigUtil(clerkManager.getClientConfig().getDigitalSignatureConfiguration());
                        //login
                        if (token == null) //option, load from juddi config
                        {
                                token = GetAuthKey(clerkManager.getClerk("default").getPublisher(),
                                        clerkManager.getClerk("default").getPassword());
                        }
                        if (key==null){
                                SaveTModel stm = new SaveTModel();
                                stm.setAuthInfo(token);
                                TModel tm = new TModel();
                                tm.setName(new Name("my cool signed tmodel", null));
                                stm.getTModel().add(tm);
                                TModelDetail saveTModel = publish.saveTModel(stm);
                                key = saveTModel.getTModel().get(0).getTModelKey();
                        }

                        TModel be = GetTmodelDetails(key);
                        if (!be.getSignature().isEmpty())
                        {
                                System.out.println("WARN, the entity with the key " + key + " is already signed! aborting");
                                return;
                        }

                        //DigSigUtil.JAXB_ToStdOut(be);
                        System.out.println("signing");
                        TModel signUDDI_JAXBObject = ds.signUddiEntity(be);
                        DigSigUtil.JAXB_ToStdOut(signUDDI_JAXBObject);
                        System.out.println("signed, saving");

                        SaveTModel sb = new SaveTModel();
                        sb.setAuthInfo(token);
                        sb.getTModel().add(signUDDI_JAXBObject);
                        publish.saveTModel(sb);
                        System.out.println("saved, fetching");

                        be = GetTmodelDetails(key);
                        DigSigUtil.JAXB_ToStdOut(be);
                        System.out.println("verifing");
                        AtomicReference<String> msg = new AtomicReference<String>();
                        boolean verifySigned_UDDI_JAXB_Object = ds.verifySignedUddiEntity(be, msg);
                        if (verifySigned_UDDI_JAXB_Object) {
                                System.out.println("signature validation passed (expected)");
                        } else {
                                System.out.println("signature validation failed (not expected)");
                        }
                        System.out.println(msg.get());

                } catch (Exception e) {
                        e.printStackTrace();
                }
        }

        private TModel GetTmodelDetails(String key) throws Exception {
                //   BusinessInfo get
                GetTModelDetail r = new GetTModelDetail();
                r.getTModelKey().add(key);
                return inquiry.getTModelDetail(r).getTModel().get(0);
        }

        /**
         * Gets a UDDI style auth token, otherwise, appends credentials to the
         * ws proxies (not yet implemented)
         *
         * @param username
         * @param password
         * @param style
         * @return
         */
        private String GetAuthKey(String username, String password) {
                try {

                        GetAuthToken getAuthTokenRoot = new GetAuthToken();
                        getAuthTokenRoot.setUserID(username);
                        getAuthTokenRoot.setCred(password);

                        // Making API call that retrieves the authentication token for the 'root' user.
                        AuthToken rootAuthToken = security.getAuthToken(getAuthTokenRoot);
                        System.out.println("root AUTHTOKEN = " + "don't log auth tokens!");
                        return rootAuthToken.getAuthInfo();
                } catch (Exception ex) {
                        System.out.println("Could not authenticate with the provided credentials " + ex.getMessage());
                }
                return null;
        }
}


text:
import psycopg2

class PostgresGIS_GTFSDB:

    #
    # initializer method for connecting to PostgreSQL database
    #
    def __init__(self, db_connect_string):

        # store the connection string
        self.db_connect_string = db_connect_string

    #
    # method to create a database connection
    #
    def create_pggtfsdb_connection(self):

        # create a database connection
        conn = psycopg2.connect(self.db_connect_string)

        # grab a database cursor
        cur = conn.cursor()

        # prepare query for get_board/alight_event_data
        prepare_stop_data_query = "PREPARE get_board_alight_event_data_stop_data (text) AS SELECT stop_name, stop_lat, stop_lon, parent_station FROM stops WHERE stop_id=$1"

        # create prepared statement for get_board/alight_event_data
        cur.execute(prepare_stop_data_query)

        # prepare queries for get_board_event_data
        prepare_route_data_query = "PREPARE get_board_event_data_route_data (text) AS SELECT routes.agency_id, routes.route_id, routes.route_long_name, routes.route_short_name, routes.route_type FROM routes, trips WHERE routes.route_id=trips.route_id AND trip_id=$1"
        prepare_stop_headsign_query = "PREPARE get_board_event_data_stop_headsign (text, text) AS SELECT stop_headsign FROM stop_times WHERE trip_id=$1 AND stop_id=$2"

        # create prepared statements for get_board_event_data
        cur.execute(prepare_route_data_query)
        cur.execute(prepare_stop_headsign_query)

        # prepare query for get_station_vertex_from_coords
        prepare_dist_query = "PREPARE get_station_vertex_from_coords (text, text) AS SELECT stop_id, ST_distance_sphere(ST_SetSRID(ST_GeomFromText($1),4326),location) as dist from stops where location && ST_SetSRID($2::box3d,4326) ORDER BY dist ASC LIMIT 1"

        # create prepared statement for get_station_vertex_from_coords
        cur.execute(prepare_dist_query)

        # prepare query for get_coords_for_station_vertex
        prepare_vertex_query = "PREPARE get_coords_for_station_vertex (text) AS SELECT ST_AsText(location) FROM stops WHERE stop_id=$1"

        # create prepared statement for get_coords_for_station_vertex
        cur.execute(prepare_vertex_query)

        # return database connection
        return conn

    #
    # method to create a database connection for get_transit_path_points function
    #
    def create_transit_path_pggtfsdb_connection(self):

        # create a database connection
        conn = psycopg2.connect(self.db_connect_string)

        # grab a database cursor
        cur = conn.cursor()

        # prepare queries for get_transit_path_points
        prepare_stop_data_query = "PREPARE get_transit_path_points_stop_data (text) AS SELECT stop_lat, stop_lon FROM stops WHERE stop_id=$1"
        prepare_shape_pt_sequence_query = "PREPARE get_transit_path_points_shape_pt_sequence (text) AS SELECT shapes.shape_pt_sequence, ST_Distance(shapes.location, stops.location) AS distance FROM shapes, stops WHERE shapes.shape_id=$1 AND stops.stop_id=$2 ORDER BY distance ASC LIMIT 1"

        # create prepared statements for get_transit_path_points
        cur.execute(prepare_stop_data_query)
        cur.execute(prepare_shape_pt_sequence_query)

        # return database connection
        return conn

    #
    # method to close a database connection
    #
    def close_pggtfsdb_connection(self, conn):

        # close database connection
        conn.close()

    #
    # method for returning the data for a transit board event
    #
    def get_board_event_data(self, conn, trip_id, stop_id):

        # grab database cursor
        cur = conn.cursor()

        # execute route data prepared statement
        cur.execute("EXECUTE get_board_event_data_route_data ('" + trip_id + "')")

        # grab the route data
        agency_id, route_id, route_long_name, route_short_name, route_type = cur.fetchone()

        # execute stop data prepared statement
        cur.execute("EXECUTE get_board_alight_event_data_stop_data ('" + stop_id + "')")

        # grab the stop data
        stop_name, stop_lat, stop_lon, parent_station = cur.fetchone()

        # execute stop headsign prepared statement
        cur.execute("EXECUTE get_board_event_data_stop_headsign ('" + trip_id + "','" + stop_id + "')")

        # grab the stop headsign data
        stop_headsign = cur.fetchone()[0]

        return (agency_id, route_id, route_long_name, route_short_name, route_type, stop_name, stop_lat, stop_lon, parent_station, stop_headsign)

    #
    # method for returning the data for a transit alight event
    #
    def get_alight_event_data(self, conn, stop_id):

        # grab database cursor
        cur = conn.cursor()

        # execute stop data prepared statement
        cur.execute("EXECUTE get_board_alight_event_data_stop_data ('" + stop_id + "')")

        # grab the stop data
        stop_name, stop_lat, stop_lon, parent_station = cur.fetchone()

        return (stop_name, stop_lat, stop_lon, parent_station)

    #
    # method for returning the closest station vertex to a coordinate pair
    #
    def get_station_vertex_from_coords(self, conn, longitude, latitude):

        # grab database cursor
        cur = conn.cursor()

        # place coordinates in POINT GIS object
        geom_point = "'POINT(" + str(longitude) + ' ' + str(latitude) + ")'"

        # longitude/latitude offset
        offset = 0.05

        # created BOX3D object for search space
        box3d_coords = "'BOX3D(" + str(longitude - offset) + ' ' + str(latitude - offset) + ',' + str(longitude + offset) + ' ' + str(latitude + offset) + ")'"

        # execute the box3d-enhanced prepared statement
        cur.execute("EXECUTE get_station_vertex_from_coords (" + geom_point + "," + box3d_coords + ")")

        # fetch the first row from the results
        first_row = cur.fetchone()

        # if the first row contains no results
        if (first_row is None):

            # execute the non-box3d-enhanced query
            cur.execute("SELECT stop_id, ST_distance_sphere(ST_SetSRID(ST_GeomFromText(" + geom_point + "),4326),location) AS dist FROM stops ORDER BY dist ASC LIMIT 1")

            # fetch the first row from the results
            first_row = cur.fetchone()

        # return osm vertex id
        return ('sta-' + first_row[0], first_row[1])

    #
    # method for returning the coordinates (lat, lon) for a station vertex
    #
    def get_coords_for_station_vertex(self, conn, vertex_id):

        # grab database cursor
        cur = conn.cursor()

        # strip 'osm-' prefix from vertex_id
        vertex_id = vertex_id.replace('sta-','')

        # execute the prepared statement
        cur.execute("EXECUTE get_coords_for_station_vertex ('" + vertex_id + "')")

        # fetch the first row from the results
        first_row = cur.fetchone()

        # grab raw coordinates
        vertex_coords = first_row[0].replace('POINT(','').replace(')','')

        # return coordinates (lat, lon)
        return (float(vertex_coords[vertex_coords.index(' ')+1:]), float(vertex_coords[0:vertex_coords.index(' ')]))

    #
    # method for returning the points along a transit path between board_stop_id and alight_stop_id
    #
    def get_transit_path_points(self, conn, trip_id, board_stop_id, alight_stop_id):

        # grab database cursor
        cur = conn.cursor()

        # execute stop data prepared statement
        cur.execute("EXECUTE get_transit_path_points_stop_data ('" + board_stop_id + "')")

        # grab the board stop data
        board_stop_lat, board_stop_lon = cur.fetchone()

        # execute stop data prepared statement
        cur.execute("EXECUTE get_transit_path_points_stop_data ('" + alight_stop_id + "')")

        # grab the alight stop data
        alight_stop_lat, alight_stop_lon = cur.fetchone()

        # execute query to get trip shape id
        cur.execute("select shape_id from trips where trip_id='" + str(trip_id) + "'")

        # grab the shape id
        shape_id = cur.fetchone()[0]

        # create list for storing points along the the shape between the stops
        path_points = []

        if (shape_id is not None):

            # check the shape id
            if (shape_id.strip() == ''):
                return [str(board_stop_lat) + ',' + str(board_stop_lon), str(alight_stop_lat) + ',' + str(alight_stop_lon)]

            # execute prepared statement to get shape point sequence value for the board stop
            cur.execute("EXECUTE get_transit_path_points_shape_pt_sequence ('" + shape_id + "','" + board_stop_id + "')")

            # grab the shape point sequence value for the board stop
            board_shape_pt_sequence = cur.fetchone()[0]

            # execute prepared statement to get shape point sequence value for the alight stop
            cur.execute("EXECUTE get_transit_path_points_shape_pt_sequence ('" + shape_id + "','" + alight_stop_id + "')")

            # grab the shape point sequence value for the alight stop
            alight_shape_pt_sequence = cur.fetchone()[0]

            # determine which point sequence value is greater
            if (board_shape_pt_sequence < alight_shape_pt_sequence):

                # execute query to get the list of points along the shape between the board and alight stops
                cur.execute("select ST_AsText(location) from shapes where shape_id='" + shape_id + "' and shape_pt_sequence >= " + str(board_shape_pt_sequence) + " and shape_pt_sequence <= " + str(alight_shape_pt_sequence) + " order by shape_pt_sequence asc")
            else:

                # execute query to get the list of points along the shape between the alight and board stops
                cur.execute("select ST_AsText(location) from shapes where shape_id='" + shape_id + "' and shape_pt_sequence >= " + str(alight_shape_pt_sequence) + " and shape_pt_sequence <= " + str(board_shape_pt_sequence) + " order by shape_pt_sequence desc")

            # grab list of points along the the shape between the stops
            path_points = cur.fetchall()

            # iterate through points
            for i in range(len(path_points)):
                mod_point = path_points[i][0].replace('POINT(','').replace(')','').replace(' ',',')
                point_lat = mod_point[mod_point.index(',')+1:]
                point_lon = mod_point[0:mod_point.index(',')]
                path_points[i] = point_lat + ',' + point_lon

        # insert board stop location to front of path points list
        path_points.insert(0, str(board_stop_lat) + ',' + str(board_stop_lon))

        # append alight stop location to end of path points list
        path_points.append(str(alight_stop_lat) + ',' + str(alight_stop_lon))

        # return transit path points
        return path_points


text:
<!doctype html>

    <meta charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="../../../support/css/physcomp.css" />
    <title>Exercise: Stepper Motor Knob</title>

Exercise: Stepper Motor Knob

Objective

WARNING: this exercise has been known to have bugs in the circuit and the code.
       If you would like extra credit, submit a bug fix to some or all of the issues you
       find.

Control a stepper motor using a driver module.

A stepper motor
      uses a toothed rotor and multiple drive coils to create motion in discrete
      steps.  The fundamental angular size of the steps is determined by the
      physical spacing of the internal magnetic teeth.  Steppers motors
      are open-loop since there is no sensor involved in controlling
      position, the driver simply cycles the coil currents and assumes the motor
      moves synchronously.  If the motor encounters too high a torque, the
      magnetic forces can be overcome and the rotor will slip to a different
      position.  The microcontroller has have no means of detecting this
      error.

This exercise uses
      an
      stepper motor driver module which takes care of cycling the currents
      appropriately through the two coils of a bipolar stepper motor.  The
      primary inputs to the driver are direction and step.
      The additional inputs control fractional stepping and the overall driver
      power state.

As a simple one-in one-out demonstration, the exercise uses a
      potentiometer as an analog position command control input.

Steps and observations

Use a DMM to measure the winding resistance of the stepper motor.  A
	bipolar stepper motor will have two independent windings which should be
	clearly observable as a low resistance between two separate wire
	pairs.

The lab stocks several different kinds of stepper motors and stepper
	motor drivers.  Please check the motor type; it should have a rated
	voltage lower than your supply voltage.  These drivers control the
	current by chopping the power supply, so the supply voltage can be
	higher than the motor rating.  If the chosen supply voltage is less than
	8V (e.g. 2.7V), you will need to use
	the low-voltage DRV8834
	stepper motor driver.  If the supply voltage is more than 8V
	(e.g. 10-12V), you should use
	the A4988 stepper motor
	driver, which is a newer replacement for the
	A4983.

Load and run the KnobToStepper sketch from the course materials,
	located in the same folder as this file if you have cloned the github distribution.  If not, it is
	directly
	downloadable. (Note: there is a MotorKnob
	sketch included in the Arduino IDE which assumes the stepper motor is
	directly driven from the Arduino; instead we will use a modular driver
	for this exercise.)

Observe the stepper motor motion.

Try moving the MS1 pull-up resistor between 5V and GND and observing
	the resulting change in step rate.  The driver is capable
	of microstepping in which the coils can be driven using PWM
	rather simply on or off in order to divide the fundamental step into
	smaller angles.

Read the data sheet for the driver and configure the driver for even
	finer steps.

Comments

Stepper motors can move relatively fast but at too high a rate can lose count.

Note: The following diagrams were tested with a polulu DRV8834 Low-Voltage Stepper Motor Driver Carrier. There may be some different versions of this, or other, stepper motor drivers from polulu in the lab. If the code in these diagrams do not work, you may need to float some of the pins high, as shown in this diagram and schematic.

Other Files

stepper-motor-knob.fzz

Sub-Folders

KnobToStepperMotor


text:
#ifndef __LISAINFERENCE_H__
#define __LISAINFERENCE_H__ 1

#ifdef PARALLEL
#include "mpi.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <float.h>
#include <stdbool.h>

#include "LISAutils.h"
#include "bambi.h"

#include "LISAinference_common.h"

#ifdef __INTEL_COMPILER 			/* if the MultiNest library was compiled with ifort */
       #define NESTRUN nested_mp_nestrun_
#elif defined __GNUC__ 				/* if the MultiNest library was compiled with gfortran */
       #define NESTRUN __nested_MOD_nestrun
#else
       #error Do not know how to link to Fortran libraries, check symbol table for your platform (nm libnest3.a | grep nestrun) & edit example_eggbox_C++/eggbox.cc
#endif

/***************************************** BAMBI declarations **************************************************/

extern float *omicron,tol,thL[3],logLRange;
extern double *maxsigma,logZero;
extern int nNN,nNNerr,totpar,loglcalls,ncheck,myid,nproc;
extern char root[1000],networkinputs[1000];
extern bool likenetinit,converged,lastconverged,netres,firstrun,discardpts;
extern int ignoredbambicalls,counter;
extern size_t nlayers,nnodes[10];
extern int doBAMBI,useNN,whitenin,whitenout,resume;

/***************************************** C Interface to BAMBI **************************************************/

/*extern void NESTRUN(int *, int *, int *, double *, double *, int *, int *, int *, int *, int *, double *,
char *, int *, int *, int *, int *, int *, int *, double *, int *, void (*Loglike)(double *, int *, int *,
double *, void *), void (*dumper)(int *, int *, int *, double **, double **, double **, double *,
double *, double *, void *), void *context);*/

void BAMBIrun(int mmodal, int ceff, int nlive, double tol, double efr, int ndims, int nPar, int nClsPar,
	int maxModes, int updInt, double Ztol, char root[], int seed, int *pWrap, int fb, int resume, int outfile,
	int initMPI, double logZero, int maxiter, void (*LogLike)(double *, int *, int *, double *, void *),
	void (*dumper)(int *, int *, int *, double **, double **, double **, double *, double *, double *, void *),
	void (*bambi)(int *, int *, double **, double *), void *context)
{
	int i;
	char rootformn[1000];
	strcpy(rootformn, root);
	for (i = strlen(rootformn); i < 1000; i++) rootformn[i] = ' ';

        NESTRUN(&mmodal, &ceff, &nlive, &tol, &efr, &ndims, &nPar, &nClsPar, &maxModes, &updInt, &Ztol,
        rootformn, &seed, pWrap, &fb, &resume, &outfile, &initMPI, &logZero, &maxiter, LogLike, dumper, bambi, context);
}

void BAMBIfctn(int *ndata, int *ndim, double **BAMBIData, double *lowlike)
{
	 /* Do "nm bambi.o | grep bambi" to find the name of the function to put here. */
	 /* "c++filt <fctn name>" should return "bambi(...)" */
	 /* Remove one leading underscore for the name here. */

	_Z5bambiPiS_PPdS0_(ndata, ndim, BAMBIData, lowlike);
}

void LogLikeFctn(double *Cube, int *ndim, int *npars, double *lnew, void *context)
{
	 /* Do "nm bambi.o | grep LogLike" to find the name of the function to put here. */
	 /* "c++filt <fctn name>" should return "LogLike(...)" */
	 /* Remove one leading underscore for the name here. */

	_Z7LogLikePdPiS0_S_Pv(Cube, ndim, npars, lnew, context);
}

/***********************************************************************************************************************/

#endif


text:
package com.picas.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.picas.util.SpringUtil;

/**
 * @author rocky.hu
 * @date Mar 2, 2017 12:38:10 PM
 */
public class ApplicationListener implements ServletContextListener {

	public void contextInitialized(ServletContextEvent event) {
		ServletContext context = event.getServletContext();
		try{
			initContextUtil(context);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void contextDestroyed(ServletContextEvent sce) {
	}

	private void initContextUtil(ServletContext context) throws Exception {
		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
		SpringUtil.setApplicationContext(ctx);
	}
}


text:
package Google::Ads::GoogleAds::V11::Enums::RealEstatePlaceholderFieldEnum;

use strict;
use warnings;

use Const::Exporter enums => [
  UNSPECIFIED         => "UNSPECIFIED",
  UNKNOWN             => "UNKNOWN",
  LISTING_ID          => "LISTING_ID",
  LISTING_NAME        => "LISTING_NAME",
  CITY_NAME           => "CITY_NAME",
  DESCRIPTION         => "DESCRIPTION",
  ADDRESS             => "ADDRESS",
  PRICE               => "PRICE",
  FORMATTED_PRICE     => "FORMATTED_PRICE",
  IMAGE_URL           => "IMAGE_URL",
  PROPERTY_TYPE       => "PROPERTY_TYPE",
  LISTING_TYPE        => "LISTING_TYPE",
  CONTEXTUAL_KEYWORDS => "CONTEXTUAL_KEYWORDS",
  FINAL_URLS          => "FINAL_URLS",
  FINAL_MOBILE_URLS   => "FINAL_MOBILE_URLS",
  TRACKING_URL        => "TRACKING_URL",
  ANDROID_APP_LINK    => "ANDROID_APP_LINK",
  SIMILAR_LISTING_IDS => "SIMILAR_LISTING_IDS",
  IOS_APP_LINK        => "IOS_APP_LINK",
  IOS_APP_STORE_ID    => "IOS_APP_STORE_ID"
];

1;


text:
(function($) {
	/*
    ======== A Handy Little QUnit Reference ========
    http://api.qunitjs.com/

    Test methods:
      module(name, {[setup][ ,teardown]})
      test(name, callback)
      expect(numberOfAssertions)
      stop(increment)
      start(decrement)
    Test assertions:
      ok(value, [message])
      equal(actual, expected, [message])
      notEqual(actual, expected, [message])
      deepEqual(actual, expected, [message])
      notDeepEqual(actual, expected, [message])
      strictEqual(actual, expected, [message])
      notStrictEqual(actual, expected, [message])
      throws(block, [expected], [message])
	 */

	var config1 = {
		apiKey: testApiKey,
		address: testUsers[0].address,
		password: testUsers[0].password,
		displayName: 'Unit Tester #1',
		features: ['audio', 'transfer']
	};
	var config1NoRegister = {
		apiKey: testApiKey,
		address: testUsers[0].address,
		password: testUsers[0].password,
		displayName: 'Unit Tester #1',
		features: ['audio', 'transfer'],
		register: false
	};
	var config2 = {
		apiKey: testApiKey,
		address: testUsers[1].address,
		password: testUsers[1].password,
		displayName: 'Unit Tester #2'
	};
	var config3 = {
		apiKey: testApiKey,
		address: testUsers[2].address,
		password: testUsers[2].password,
		displayName: 'Unit Tester #3',
		onDisconnected: function (event) {
			if (event.status === 'normal') {
				QUnit.start();
			}
			// Otherwise wait for the hung test timeout
		}
	};

	QUnit.module("Transfer");

	QUnit.asyncTest("Successful blind transfer", 16, function(assert) {
		var croc1 = $.croc(config1);
		var croc2 = $.croc(config2);
		var croc3 = $.croc(config3);
		// Give up if the test has hung for too long
		var hungTimerId = setTimeout(function() {
			assert.ok(false, 'Aborting hung test');
			croc1.stop();
			croc2.stop();
			croc3.stop();
			hungTimerId = null;
		}, 90000);

		// Initial callee
		croc2.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'callee onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - transferring session');
					var feedback = session.transfer(config3.address);
					feedback.onAccepted = function() {
						assert.ok(true, 'Transfer accepted');
						// Close the old session
						session.close();
					};
					feedback.onRejected = function() {
						assert.ok(false, 'Transfer rejected');
					};
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'callee onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Transfer target
		croc3.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'croc3.media.onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'transfer target onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - closing session');
					session.close();
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'transfer target onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Wait for receiver to register before sending the data
		croc2.onRegistered = function () {
			var session = croc1.media.connect(config2.address);

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'caller session.onConnect fired');
			};
			session.onTransferRequest = function(event) {
				assert.ok(true, 'caller onTransferRequest fired');
				assert.strictEqual(event.address, config3.address, 'Expected refer URI');

				var newSession = event.accept();
				assert.strictEqual(newSession.address, config3.address, 'Expected session address');
				newSession.onConnect = function() {
					assert.ok(true, 'caller newSession.onConnect fired');
				};

				// Clean up the croc objects when the new session closes
				newSession.onClose = function () {
					assert.ok(true, 'caller newSession.onClose event fired');
					if (hungTimerId !== null) {
						clearTimeout(hungTimerId);
						hungTimerId = null;
					}
					croc1.stop();
					croc2.stop();
					croc3.stop();
				};
			};

			session.onClose = function () {
				assert.ok(true, 'caller session.onClose event fired');
			};
		};

		// QUnit will restart once the third croc object has disconnected
	});

	QUnit.asyncTest("Remote party lacks REFER support", 6, function(assert) {
		var croc1 = $.croc(config1);
		var croc2 = $.croc(config2);
		// Give up if the test has hung for too long
		var hungTimerId = setTimeout(function() {
			assert.ok(false, 'Aborting hung test');
			croc1.stop();
			croc2.stop();
			hungTimerId = null;
		}, 60000);

		// Initial callee
		croc2.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'callee onConnect fired');
			};
			session.onClose = function () {
				assert.ok(true, 'callee onClose event fired');
				if (hungTimerId !== null) {
					clearTimeout(hungTimerId);
					hungTimerId = null;
				}
				croc1.stop();
				croc2.stop();
			};

			// Accept the session
			session.accept();
		};

		// Wait for callee to register before attempting to connect
		croc2.onRegistered = function () {
			var session = croc1.media.connect(config2.address);

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'caller session.onConnect fired');
				// Transfer shortly after connecting
				assert.throws(function () {
					session.transfer(config3.address);
				}, CrocSDK.Exceptions.UnsupportedError, 'Threw UnsupportedError');
				session.close();
			};

			session.onClose = function () {
				assert.ok(true, 'caller session.onClose event fired');
			};
		};

		croc2.onDisconnected = function(event) {
			if (event.status === 'normal') {
				QUnit.start();
			}
			// Otherwise wait for the hung test timeout
		};
	});

	QUnit.asyncTest("Rejected transfer", 9, function(assert) {
		var croc1 = $.croc(config1);
		var croc2 = $.croc(config2);
		// Give up if the test has hung for too long
		var hungTimerId = setTimeout(function() {
			assert.ok(false, 'Aborting hung test');
			croc1.stop();
			croc2.stop();
			hungTimerId = null;
		}, 60000);

		// Initial callee
		croc2.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'callee onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - transferring session');
					var feedback = session.transfer(config3.address);
					feedback.onAccepted = function() {
						assert.ok(false, 'Transfer accepted');
						session.close();
					};
					feedback.onRejected = function() {
						assert.ok(true, 'Transfer rejected');
						session.close();
					};
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'callee onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Wait for receiver to register before sending the data
		croc2.onRegistered = function () {
			var session = croc1.media.connect(config2.address);

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'caller session.onConnect fired');
			};
			session.onTransferRequest = function(event) {
				assert.ok(true, 'caller onTransferRequest fired');
				assert.strictEqual(event.address, config3.address, 'Expected refer URI');

				event.reject();
			};

			session.onClose = function () {
				assert.ok(true, 'caller session.onClose event fired');
				if (hungTimerId !== null) {
					clearTimeout(hungTimerId);
					hungTimerId = null;
				}
				croc1.stop();
				croc2.stop();
			};
		};

		croc2.onDisconnected = function(event) {
			if (event.status === 'normal') {
				QUnit.start();
			}
			// Otherwise wait for the hung test timeout
		};
	});

	QUnit.asyncTest("Successful transfer", 17, function(assert) {
		var croc1 = $.croc(config1);
		var croc2 = $.croc(config2);
		var croc3 = $.croc(config3);
		// Give up if the test has hung for too long
		var hungTimerId = setTimeout(function() {
			assert.ok(false, 'Aborting hung test');
			croc1.stop();
			croc2.stop();
			croc3.stop();
			hungTimerId = null;
		}, 90000);

		// Initial callee
		croc2.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'callee onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - transferring session');
					var feedback = session.transfer(config3.address);
					feedback.onAccepted = function() {
						assert.ok(true, 'Transfer accepted');
					};
					feedback.onTransferSucceeded = function() {
						assert.ok(true, 'Transfer succeeded');
						// Close the old session
						session.close();
					};
					feedback.onRejected = function() {
						assert.ok(false, 'Transfer rejected');
					};
					feedback.onTransferFailed = function() {
						assert.ok(false, 'Transfer failed');
					};
					feedback.onTransferResultUnknown = function() {
						assert.ok(false, 'Transfer result unknown');
					};
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'callee onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Transfer target
		croc3.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'croc3.media.onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'transfer target onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - closing session');
					session.close();
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'transfer target onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Wait for receiver to register before sending the data
		croc2.onRegistered = function () {
			var session = croc1.media.connect(config2.address);

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'caller session.onConnect fired');
			};
			session.onTransferRequest = function(event) {
				assert.ok(true, 'caller onTransferRequest fired');
				assert.strictEqual(event.address, config3.address, 'Expected refer URI');

				var newSession = event.accept();
				assert.strictEqual(newSession.address, config3.address, 'Expected session address');
				newSession.onConnect = function() {
					assert.ok(true, 'caller newSession.onConnect fired');
				};

				// Clean up the croc objects when the new session closes
				newSession.onClose = function () {
					assert.ok(true, 'caller newSession.onClose event fired');
					if (hungTimerId !== null) {
						clearTimeout(hungTimerId);
						hungTimerId = null;
					}
					croc1.stop();
					croc2.stop();
					croc3.stop();
				};
			};

			session.onClose = function () {
				assert.ok(true, 'caller session.onClose event fired');
			};
		};

		// QUnit will restart once the third croc object has disconnected
	});

	QUnit.asyncTest("Failed transfer", 13, function(assert) {
		var croc1 = $.croc(config1);
		var croc2 = $.croc(config2);
		var croc3 = $.croc(config3);
		// Give up if the test has hung for too long
		var hungTimerId = setTimeout(function() {
			assert.ok(false, 'Aborting hung test');
			croc1.stop();
			croc2.stop();
			croc3.stop();
			hungTimerId = null;
		}, 90000);

		// Initial callee
		croc2.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'callee onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - transferring session');
					var feedback = session.transfer(config3.address);
					feedback.onAccepted = function() {
						assert.ok(true, 'Transfer accepted');
					};
					feedback.onTransferSucceeded = function() {
						assert.ok(false, 'Transfer succeeded');
					};
					feedback.onRejected = function() {
						assert.ok(false, 'Transfer rejected');
					};
					feedback.onTransferFailed = function() {
						assert.ok(true, 'Transfer failed');
						// Proceed with existing session a while longer
						setTimeout(function() {
							session.close();
						}, 5000);
					};
					feedback.onTransferResultUnknown = function() {
						assert.ok(false, 'Transfer result unknown');
					};
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'callee onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Transfer target
		croc3.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'croc3.media.onMediaSession fired');

			// Reject the session
			session.close();
		};

		// Wait for receiver to register before sending the data
		croc2.onRegistered = function () {
			var session = croc1.media.connect(config2.address);

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'caller session.onConnect fired');
			};
			session.onTransferRequest = function(event) {
				assert.ok(true, 'caller onTransferRequest fired');
				assert.strictEqual(event.address, config3.address, 'Expected refer URI');

				var newSession = event.accept();
				assert.strictEqual(newSession.address, config3.address, 'Expected session address');

				newSession.onClose = function () {
					assert.ok(true, 'caller newSession.onClose event fired');
				};
			};

			session.onClose = function () {
				assert.ok(true, 'caller session.onClose event fired');
				if (hungTimerId !== null) {
					clearTimeout(hungTimerId);
					hungTimerId = null;
				}
				croc1.stop();
				croc2.stop();
				croc3.stop();
			};
		};

		// QUnit will restart once the third croc object has disconnected
	});

	QUnit.asyncTest("In-dialog successful blind transfer", 16, function(assert) {
		var croc1 = $.croc(config1NoRegister);
		var croc2 = $.croc(config2);
		var croc3 = $.croc(config3);
		// Give up if the test has hung for too long
		var hungTimerId = setTimeout(function() {
			assert.ok(false, 'Aborting hung test');
			croc1.stop();
			croc2.stop();
			croc3.stop();
			hungTimerId = null;
		}, 90000);

		// Initial callee
		croc2.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'callee onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - transferring session');
					var feedback = session.transfer(config3.address);
					feedback.onAccepted = function() {
						assert.ok(true, 'Transfer accepted');
						// Close the old session
						session.close();
					};
					feedback.onRejected = function() {
						assert.ok(false, 'Transfer rejected');
					};
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'callee onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Transfer target
		croc3.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'croc3.media.onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'transfer target onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - closing session');
					session.close();
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'transfer target onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Wait for receiver to register before sending the data
		croc2.onRegistered = function () {
			var session = croc1.media.connect(config2.address);

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'caller session.onConnect fired');
			};
			session.onTransferRequest = function(event) {
				assert.ok(true, 'caller onTransferRequest fired');
				assert.strictEqual(event.address, config3.address, 'Expected refer URI');

				var newSession = event.accept();
				assert.strictEqual(newSession.address, config3.address, 'Expected session address');
				newSession.onConnect = function() {
					assert.ok(true, 'caller newSession.onConnect fired');
				};

				// Clean up the croc objects when the new session closes
				newSession.onClose = function () {
					assert.ok(true, 'caller newSession.onClose event fired');
					if (hungTimerId !== null) {
						clearTimeout(hungTimerId);
						hungTimerId = null;
					}
					croc1.stop();
					croc2.stop();
					croc3.stop();
				};
			};

			session.onClose = function () {
				assert.ok(true, 'caller session.onClose event fired');
			};
		};

		// QUnit will restart once the third croc object has disconnected
	});

	QUnit.asyncTest("In-dialog rejected transfer", 9, function(assert) {
		var croc1 = $.croc(config1NoRegister);
		var croc2 = $.croc(config2);
		// Give up if the test has hung for too long
		var hungTimerId = setTimeout(function() {
			assert.ok(false, 'Aborting hung test');
			croc1.stop();
			croc2.stop();
			hungTimerId = null;
		}, 60000);

		// Initial callee
		croc2.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'callee onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - transferring session');
					var feedback = session.transfer(config3.address);
					feedback.onAccepted = function() {
						assert.ok(false, 'Transfer accepted');
						session.close();
					};
					feedback.onRejected = function() {
						assert.ok(true, 'Transfer rejected');
						session.close();
					};
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'callee onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Wait for receiver to register before sending the data
		croc2.onRegistered = function () {
			var session = croc1.media.connect(config2.address);

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'caller session.onConnect fired');
			};
			session.onTransferRequest = function(event) {
				assert.ok(true, 'caller onTransferRequest fired');
				assert.strictEqual(event.address, config3.address, 'Expected refer URI');

				event.reject();
			};

			session.onClose = function () {
				assert.ok(true, 'caller session.onClose event fired');
				if (hungTimerId !== null) {
					clearTimeout(hungTimerId);
					hungTimerId = null;
				}
				croc1.stop();
				croc2.stop();
			};
		};

		croc2.onDisconnected = function(event) {
			if (event.status === 'normal') {
				QUnit.start();
			}
			// Otherwise wait for the hung test timeout
		};
	});

	QUnit.asyncTest("In-dialog successful transfer", 17, function(assert) {
		var croc1 = $.croc(config1NoRegister);
		var croc2 = $.croc(config2);
		var croc3 = $.croc(config3);
		// Give up if the test has hung for too long
		var hungTimerId = setTimeout(function() {
			assert.ok(false, 'Aborting hung test');
			croc1.stop();
			croc2.stop();
			croc3.stop();
			hungTimerId = null;
		}, 90000);

		// Initial callee
		croc2.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'callee onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - transferring session');
					var feedback = session.transfer(config3.address);
					feedback.onAccepted = function() {
						assert.ok(true, 'Transfer accepted');
					};
					feedback.onTransferSucceeded = function() {
						assert.ok(true, 'Transfer succeeded');
						// Close the old session
						session.close();
					};
					feedback.onRejected = function() {
						assert.ok(false, 'Transfer rejected');
					};
					feedback.onTransferFailed = function() {
						assert.ok(false, 'Transfer failed');
					};
					feedback.onTransferResultUnknown = function() {
						assert.ok(false, 'Transfer result unknown');
					};
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'callee onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Transfer target
		croc3.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'croc3.media.onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'transfer target onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - closing session');
					session.close();
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'transfer target onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Wait for receiver to register before sending the data
		croc2.onRegistered = function () {
			var session = croc1.media.connect(config2.address);

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'caller session.onConnect fired');
			};
			session.onTransferRequest = function(event) {
				assert.ok(true, 'caller onTransferRequest fired');
				assert.strictEqual(event.address, config3.address, 'Expected refer URI');

				var newSession = event.accept();
				assert.strictEqual(newSession.address, config3.address, 'Expected session address');
				newSession.onConnect = function() {
					assert.ok(true, 'caller newSession.onConnect fired');
				};

				// Clean up the croc objects when the new session closes
				newSession.onClose = function () {
					assert.ok(true, 'caller newSession.onClose event fired');
					if (hungTimerId !== null) {
						clearTimeout(hungTimerId);
						hungTimerId = null;
					}
					croc1.stop();
					croc2.stop();
					croc3.stop();
				};
			};

			session.onClose = function () {
				assert.ok(true, 'caller session.onClose event fired');
			};
		};

		// QUnit will restart once the third croc object has disconnected
	});

	QUnit.asyncTest("In-dialog failed transfer", 13, function(assert) {
		var croc1 = $.croc(config1NoRegister);
		var croc2 = $.croc(config2);
		var croc3 = $.croc(config3);
		// Give up if the test has hung for too long
		var hungTimerId = setTimeout(function() {
			assert.ok(false, 'Aborting hung test');
			croc1.stop();
			croc2.stop();
			croc3.stop();
			hungTimerId = null;
		}, 90000);

		// Initial callee
		croc2.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'onMediaSession fired');

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'callee onConnect fired');
				// Transfer shortly after connecting
				setTimeout(function () {
					assert.ok(true, 'Timer fired - transferring session');
					var feedback = session.transfer(config3.address);
					feedback.onAccepted = function() {
						assert.ok(true, 'Transfer accepted');
					};
					feedback.onTransferSucceeded = function() {
						assert.ok(false, 'Transfer succeeded');
					};
					feedback.onRejected = function() {
						assert.ok(false, 'Transfer rejected');
					};
					feedback.onTransferFailed = function() {
						assert.ok(true, 'Transfer failed');
						// Proceed with existing session a while longer
						setTimeout(function() {
							session.close();
						}, 5000);
					};
					feedback.onTransferResultUnknown = function() {
						assert.ok(false, 'Transfer result unknown');
					};
				}, 5000);
			};
			session.onClose = function () {
				assert.ok(true, 'callee onClose event fired');
			};

			// Accept the session
			session.accept();
		};

		// Transfer target
		croc3.media.onMediaSession = function (event) {
			var session = event.session;
			assert.ok(true, 'croc3.media.onMediaSession fired');

			// Reject the session
			session.close();
		};

		// Wait for receiver to register before sending the data
		croc2.onRegistered = function () {
			var session = croc1.media.connect(config2.address);

			// Check that expected events fire
			session.onConnect = function () {
				assert.ok(true, 'caller session.onConnect fired');
			};
			session.onTransferRequest = function(event) {
				assert.ok(true, 'caller onTransferRequest fired');
				assert.strictEqual(event.address, config3.address, 'Expected refer URI');

				var newSession = event.accept();
				assert.strictEqual(newSession.address, config3.address, 'Expected session address');

				newSession.onClose = function () {
					assert.ok(true, 'caller newSession.onClose event fired');
				};
			};

			session.onClose = function () {
				assert.ok(true, 'caller session.onClose event fired');
				if (hungTimerId !== null) {
					clearTimeout(hungTimerId);
					hungTimerId = null;
				}
				croc1.stop();
				croc2.stop();
				croc3.stop();
			};
		};

		// QUnit will restart once the third croc object has disconnected
	});

}(jQuery));


text:
//
//  BLCImagesTableViewController.m
//  Blocstagram
//
//  Created by Jean Ro on 11/23/14.
//  Copyright (c) 2014 Jean Ro. All rights reserved.
//

#import "BLCImagesTableViewController.h"
#import "BLCDatasource.h"
#import "BLCMedia.h"
#import "BLCUser.h"
#import "BLCComment.h"
#import "BLCMediaTableViewCell.h"
#import "BLCMediaFullScreenViewController.h"
#import "BLCMediaFullScreenAnimator.h"
#import "BLCCameraViewController.h"
#import "BLCImageLibraryViewController.h"
#import "BLCPostToInstagramViewController.h"

@interface BLCImagesTableViewController () <BLCMediaTableViewCellDelegate, UIViewControllerTransitioningDelegate, BLCCameraViewControllerDelegate, BLCImageLibraryViewControllerDelegate>
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGesture;
@property (nonatomic, weak) UIImageView *lastTappedImageView;
@property (nonatomic, weak) UIView *lastSelectedCommentView;
@property (nonatomic, assign) CGFloat lastKeyboardAdjustment;
@property (nonatomic, strong) UIPopoverController *cameraPopover;
@property (nonatomic, strong) UIPopoverController *sharePopover;
@end

@implementation BLCImagesTableViewController {
    CGPoint lastOffset;
    NSTimeInterval lastOffsetCapture;
    BOOL startDecelerationCapture;
}

-(id)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:style];
    if(self) {
        self.longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tableLongPressed:)];
        [self.tableView addGestureRecognizer:self.longPressGesture];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [[BLCDatasource sharedInstance] addObserver:self forKeyPath:@"mediaItems" options:0 context:nil];

    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.refreshControl addTarget:self action:@selector(refreshControlDidFire:) forControlEvents:UIControlEventValueChanged];

    [self.tableView registerClass:[BLCMediaTableViewCell class] forCellReuseIdentifier:@"mediaCell"];

    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ||
        [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        UIBarButtonItem *cameraButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(cameraPressed:)];
        self.navigationItem.rightBarButtonItem = cameraButton;
    }

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(imageDidFinish:)
                                                 name:BLCImageFinishedNotification
                                               object:nil];

    //self.tableView.contentInset = UIEdgeInsetsMake(66, 0, 0, 0);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
    if(indexPath) {
        [self.tableView deselectRowAtIndexPath:indexPath animated:animated];
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self downloadImageForVisibleRows];
}

-(void) dealloc {
    [[BLCDatasource sharedInstance] removeObserver:self forKeyPath:@"mediaItems"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if(object == [BLCDatasource sharedInstance] && [keyPath isEqualToString:@"mediaItems"]) {
        int kindOfChange = [change[NSKeyValueChangeKindKey] intValue];
        if(kindOfChange == NSKeyValueChangeSetting) {
            [self.tableView reloadData];
        }else if( kindOfChange == NSKeyValueChangeInsertion ||
                 kindOfChange == NSKeyValueChangeRemoval ||
                 kindOfChange == NSKeyValueChangeReplacement) {
            NSIndexSet *indexSetOfChanges = change[NSKeyValueChangeIndexesKey];
            NSMutableArray *indexPathsThatChanged = [NSMutableArray array];
            [indexSetOfChanges enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
                NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:idx inSection:0];
                [indexPathsThatChanged addObject:newIndexPath];
            }];

            [self.tableView beginUpdates];

            if(kindOfChange == NSKeyValueChangeInsertion) {
                [self.tableView insertRowsAtIndexPaths:indexPathsThatChanged withRowAnimation:UITableViewRowAnimationAutomatic];
            }else if(kindOfChange == NSKeyValueChangeRemoval) {
                [self.tableView deleteRowsAtIndexPaths:indexPathsThatChanged withRowAnimation:UITableViewRowAnimationAutomatic];
            }else if (kindOfChange == NSKeyValueChangeReplacement) {
                [self.tableView reloadRowsAtIndexPaths:indexPathsThatChanged withRowAnimation:UITableViewRowAnimationAutomatic];
            }

            [self.tableView endUpdates];
        }
    }
}

-(void) refreshControlDidFire:(UIRefreshControl *)sender {
    [[BLCDatasource sharedInstance] requestNewItemsWithCompletionHandler:^(NSError *error) {
        [sender endRefreshing];
    }];
}

-(NSArray *) items {
    return [BLCDatasource sharedInstance].mediaItems;
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:YES];
}

-(void)tableLongPressed:(UILongPressGestureRecognizer *)recognizer {
    if(recognizer.state == UIGestureRecognizerStateRecognized) {

        [self setEditing:(!self.editing) animated:YES];
    }
}

 #pragma mark - Camera, BLCCameraViewControllerDelegate, and BLCImageLibraryViewControllerDelegate

- (void) cameraPressed:(UIBarButtonItem *) sender {
    UIViewController *imageVC;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        BLCCameraViewController *cameraVC = [[BLCCameraViewController alloc] init];
        cameraVC.delegate = self;
        imageVC = cameraVC;
    }else if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        BLCImageLibraryViewController *imageLibraryVC = [[BLCImageLibraryViewController alloc] init];
        imageLibraryVC.delegate = self;
        imageVC = imageLibraryVC;
    }

    if(imageVC) {
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:imageVC];
        if (isPhone) {
            [self presentViewController:nav animated:YES completion:nil];
        } else {
            self.cameraPopover = [[UIPopoverController alloc] initWithContentViewController:nav];
            self.cameraPopover.popoverContentSize = CGSizeMake(320, 568);
            [self.cameraPopover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        }
    }

    return;
}

- (void) cameraViewController:(BLCCameraViewController *)cameraViewController didCompleteWithImage:(UIImage *)image {
    /*
    [cameraViewController dismissViewControllerAnimated:YES completion:^{
        if (image) {
            NSLog(@"Got an image!");
        } else {
            NSLog(@"Closed without an image.");
        }
    }];
     */
    [self handleImage:image withNavigationController:cameraViewController.navigationController];
}

-(void) imageLibraryViewController:(BLCImageLibraryViewController *)imageLibraryViewController didCompleteWithImage:(UIImage *)image {
    [self handleImage:image withNavigationController:imageLibraryViewController.navigationController];
}

-(void) handleImage:(UIImage *)image withNavigationController:(UINavigationController *)nav {
    if(image) {
        BLCPostToInstagramViewController *postVC = [[BLCPostToInstagramViewController alloc] initWithImage:image];
        [nav pushViewController:postVC animated:YES];

    }else{
        if (isPhone) {
            [nav dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self.cameraPopover dismissPopoverAnimated:YES];
            self.cameraPopover = nil;
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self items].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    BLCMediaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mediaCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.mediaItem = [BLCDatasource sharedInstance].mediaItems[indexPath.row];

    return cell;
}

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    BLCMedia *mediaItem = [BLCDatasource sharedInstance].mediaItems[indexPath.row];
    if (mediaItem.downloadState == BLCMediaDownloadStateNeedsImage) {
        [[BLCDatasource sharedInstance] downloadImageForMediaItem:mediaItem];
    }
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BLCMedia *item = [self items][indexPath.row];
    CGFloat newHeight = [BLCMediaTableViewCell heightForMediaItem:item width:CGRectGetWidth(self.view.frame)];
    return newHeight;
}

-(CGFloat) tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BLCMedia *item = [self items][indexPath.row];
    if(item.image) {
        return 450;
    }else {
        return 250;
    }
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BLCMediaTableViewCell *cell = (BLCMediaTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    [cell stopComposingComment];
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        BLCMedia *item = self.items[indexPath.row];
        [[BLCDatasource sharedInstance] deleteMediaItem:item];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

#pragma mark - BLCMediaTableViewCellDelegate

-(void) cell:(BLCMediaTableViewCell *)cell didTapImageView:(UIImageView *)imageView {
    self.lastTappedImageView = imageView;
    BLCMediaFullScreenViewController *fullScreenVC = [[BLCMediaFullScreenViewController alloc] initWithMedia:cell.mediaItem];

    if (isPhone) {
        fullScreenVC.transitioningDelegate = self;
        fullScreenVC.modalPresentationStyle = UIModalPresentationCustom;
    } else {
        fullScreenVC.modalPresentationStyle = UIModalPresentationFormSheet;
    }

    [self presentViewController:fullScreenVC animated:YES completion:nil];
}

- (void) cell:(BLCMediaTableViewCell *)cell didLongPressImageView:(UIImageView *)imageView {
    NSMutableArray *itemsToShare = [NSMutableArray array];

    if (cell.mediaItem.caption.length > 0) {
        [itemsToShare addObject:cell.mediaItem.caption];
    }

    if (cell.mediaItem.image) {
        [itemsToShare addObject:cell.mediaItem.image];
    }

    if (itemsToShare.count > 0) {
        UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:itemsToShare applicationActivities:nil];
        if(isPhone) {
            [self presentViewController:activityVC animated:YES completion:nil];
        }else{
            //iPad
            self.sharePopover = [[UIPopoverController alloc] initWithContentViewController:activityVC];
            self.sharePopover.popoverContentSize = CGSizeMake(320, 568);
            [self.sharePopover presentPopoverFromRect:CGRectMake(0, 0, 320, 568) inView:cell permittedArrowDirections:UIPopoverArrowDirectionUnknown animated:YES];
        }
    }
}

-(void) cell:(BLCMediaTableViewCell *)cell didTapToDownloadImage:(BLCMedia *)media {
    [[BLCDatasource sharedInstance] requestToDownloadImageForMedia:media];
}

- (void) cellDidPressLikeButton:(BLCMediaTableViewCell *)cell {
    [[BLCDatasource sharedInstance] toggleLikeOnMediaItem:cell.mediaItem];
}

-(void) cellWillStartComposingComment:(BLCMediaTableViewCell *)cell {
    self.lastSelectedCommentView = (UIView *)cell.commentView;
}

-(void) cell:(BLCMediaTableViewCell *)cell didComposeComment:(NSString *)comment {
    [[BLCDatasource sharedInstance] commentOnMediaItem:cell.mediaItem withCommentText:comment];
}

#pragma mark - UIViewControllerTransitioningDelegate

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented
                                                                  presentingController:(UIViewController *)presenting
                                                                      sourceController:(UIViewController *)source {

    BLCMediaFullScreenAnimator *animator = [BLCMediaFullScreenAnimator new];
    animator.presenting = YES;
    animator.cellImageView = self.lastTappedImageView;
    return animator;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    BLCMediaFullScreenAnimator *animator = [BLCMediaFullScreenAnimator new];
    animator.cellImageView = self.lastTappedImageView;
    return animator;
}

#pragma mark - UIScrollViewDelegate

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    startDecelerationCapture = YES;
    lastOffset = CGPointMake(0, 0);
    lastOffsetCapture = 0;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if(startDecelerationCapture) {
        CGPoint currentOffset = scrollView.contentOffset;
        NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];

        NSTimeInterval timeDiff = currentTime - lastOffsetCapture;
        if(timeDiff > 0.1) {
            CGFloat distance = currentOffset.y - lastOffset.y;
            //The multiply by 10, / 1000 isn't really necessary.......
            CGFloat scrollSpeedNotAbs = (distance * 10) / 1000; //in pixels per millisecond

            CGFloat scrollSpeed = fabsf(scrollSpeedNotAbs);
            //NSLog(@"speed: %f", scrollSpeed);
            if (scrollSpeed < 0.8) {
                [self downloadImageForVisibleRows];
            }

            lastOffset = currentOffset;
            lastOffsetCapture = currentTime;
        }
    }

}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    //if(!decelerate) {
        //[self downloadImageForVisibleRows];
    //}
    startDecelerationCapture = NO;
}

-(void)downloadImageForVisibleRows {
    NSArray *visibleIndexPaths = [self.tableView indexPathsForVisibleRows];
    for (NSIndexPath *path in visibleIndexPaths) {
        BLCMedia *mediaItem = [[self items] objectAtIndex:path.row];
        if(mediaItem.downloadState == BLCMediaDownloadStateNeedsImage) {
            [[BLCDatasource sharedInstance] downloadImageForMediaItem:[[self items] objectAtIndex:path.row]];
        }
    };
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    startDecelerationCapture = NO;
    [self infiniteScrollIfNecessary];
}

- (void) infiniteScrollIfNecessary {
    NSIndexPath *bottomIndexPath = [[self.tableView indexPathsForVisibleRows] lastObject];

    if (bottomIndexPath && bottomIndexPath.row == [BLCDatasource sharedInstance].mediaItems.count - 1) {
        // The very last cell is on screen
        [[BLCDatasource sharedInstance] requestOldItemsWithCompletionHandler:nil];
    }
}

#pragma mark - Keyboard Handling

- (void)keyboardWillShow:(NSNotification *)notification
{
    // Get the frame of the keyboard within self.view's coordinate system
    NSValue *frameValue = notification.userInfo[UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrameInScreenCoordinates = frameValue.CGRectValue;
    CGRect keyboardFrameInViewCoordinates = [self.navigationController.view convertRect:keyboardFrameInScreenCoordinates fromView:nil];

    // Get the frame of the comment view in the same coordinate system
    CGRect commentViewFrameInViewCoordinates = [self.navigationController.view convertRect:self.lastSelectedCommentView.bounds fromView:self.lastSelectedCommentView];

    CGPoint contentOffset = self.tableView.contentOffset;
    UIEdgeInsets contentInsets = self.tableView.contentInset;
    UIEdgeInsets scrollIndicatorInsets = self.tableView.scrollIndicatorInsets;
    CGFloat heightToScroll = 0;

    CGFloat keyboardY = CGRectGetMinY(keyboardFrameInViewCoordinates);
    CGFloat commentViewY = CGRectGetMinY(commentViewFrameInViewCoordinates);
    CGFloat difference = commentViewY - keyboardY;

    if (difference > 0) {
        heightToScroll += difference;
    }

    if (CGRectIntersectsRect(keyboardFrameInViewCoordinates, commentViewFrameInViewCoordinates)) {
        // The two frames intersect (the keyboard would block the view)
        CGRect intersectionRect = CGRectIntersection(keyboardFrameInViewCoordinates, commentViewFrameInViewCoordinates);
        heightToScroll += CGRectGetHeight(intersectionRect);
    }

    if (heightToScroll > 0) {
        contentInsets.bottom += heightToScroll;
        scrollIndicatorInsets.bottom += heightToScroll;
        contentOffset.y += heightToScroll;

        NSNumber *durationNumber = notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];
        NSNumber *curveNumber = notification.userInfo[UIKeyboardAnimationCurveUserInfoKey];

        NSTimeInterval duration = durationNumber.doubleValue;
        UIViewAnimationCurve curve = curveNumber.unsignedIntegerValue;
        UIViewAnimationOptions options = curve << 16;

        [UIView animateWithDuration:duration delay:0 options:options animations:^{
            self.tableView.contentInset = contentInsets;
            self.tableView.scrollIndicatorInsets = scrollIndicatorInsets;
            self.tableView.contentOffset = contentOffset;
        } completion:nil];
    }

    self.lastKeyboardAdjustment = heightToScroll;
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    UIEdgeInsets contentInsets = self.tableView.contentInset;
    contentInsets.bottom -= self.lastKeyboardAdjustment;

    UIEdgeInsets scrollIndicatorInsets = self.tableView.scrollIndicatorInsets;
    scrollIndicatorInsets.bottom -= self.lastKeyboardAdjustment;

    NSNumber *durationNumber = notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curveNumber = notification.userInfo[UIKeyboardAnimationCurveUserInfoKey];

    NSTimeInterval duration = durationNumber.doubleValue;
    UIViewAnimationCurve curve = curveNumber.unsignedIntegerValue;
    UIViewAnimationOptions options = curve << 16;

    [UIView animateWithDuration:duration delay:0 options:options animations:^{
        self.tableView.contentInset = contentInsets;
        self.tableView.scrollIndicatorInsets = scrollIndicatorInsets;
    } completion:nil];
}

#pragma mark - Popover Handling

- (void) imageDidFinish:(NSNotification *)notification {
    if (isPhone) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.cameraPopover dismissPopoverAnimated:YES];
        self.cameraPopover = nil;
    }
}

@end