text:
* [Added] Update HTTP config spec templates. See [#12890](https://github.com/DataDog/integrations-core/pull/12890).

## 3.2.1 / 2022-05-18 / Agent 7.37.0

* [Fixed] Fix extra metrics description example. See [#12043](https://github.com/DataDog/integrations-core/pull/12043).

## 3.2.0 / 2022-05-15

* [Added] Support dynamic bearer tokens (Bound Service Account Token Volume). See [#11915](https://github.com/DataDog/integrations-core/pull/11915).

## 3.1.0 / 2022-04-05 / Agent 7.36.0

* [Added] Add metric_patterns options to filter all metric submission by a list of regexes. See [#11695](https://github.com/DataDog/integrations-core/pull/11695).
* [Fixed] Remove outdated warning in the description for the `tls_ignore_warning` option. See [#11591](https://github.com/DataDog/integrations-core/pull/11591).

## 3.0.0 / 2022-02-19 / Agent 7.35.0

* [Added] Add `pyproject.toml` file. See [#11390](https://github.com/DataDog/integrations-core/pull/11390).
* [Fixed] Fix namespace packaging on Python 2. See [#11532](https://github.com/DataDog/integrations-core/pull/11532).
* [Changed] Add tls_protocols_allowed option documentation. See [#11251](https://github.com/DataDog/integrations-core/pull/11251).

## 2.11.4 / 2022-01-21 / Agent 7.34.0

* [Fixed] Fix license header dates in autogenerated files. See [#11187](https://github.com/DataDog/integrations-core/pull/11187).

## 2.11.3 / 2022-01-18

* [Fixed] Fix the type of `bearer_token_auth`. See [#11144](https://github.com/DataDog/integrations-core/pull/11144).

## 2.11.2 / 2022-01-08

* [Fixed] Add comment to autogenerated model files. See [#10945](https://github.com/DataDog/integrations-core/pull/10945).

## 2.11.1 / 2021-11-16 / Agent 7.33.0

* [Fixed] Validate use of legacy openmetrics config. See [#10636](https://github.com/DataDog/integrations-core/pull/10636).

## 2.11.0 / 2021-11-13

* [Added] Document new include_labels option. See [#10617](https://github.com/DataDog/integrations-core/pull/10617).
* [Added] Document new use_process_start_time option. See [#10601](https://github.com/DataDog/integrations-core/pull/10601).
* [Added] Add runtime configuration validation. See [#8948](https://github.com/DataDog/integrations-core/pull/8948).

## 2.10.0 / 2021-10-04 / Agent 7.32.0

* [Added] Add HTTP option to control the size of streaming responses. See [#10183](https://github.com/DataDog/integrations-core/pull/10183).
* [Added] Add allow_redirect option. See [#10160](https://github.com/DataDog/integrations-core/pull/10160).
* [Added] Allow Kubernetes port forwarding to support any resource. See [#10127](https://github.com/DataDog/integrations-core/pull/10127).
* [Fixed] Fix the description of the `allow_redirects` HTTP option. See [#10195](https://github.com/DataDog/integrations-core/pull/10195).

## 2.9.1 / 2021-07-12 / Agent 7.30.0

* [Fixed] Raise exception if attempting to use new style openmetrics with py2. See [#9613](https://github.com/DataDog/integrations-core/pull/9613).

## 2.9.0 / 2021-05-28 / Agent 7.29.0

* [Added] Support "ignore_tags" configuration. See [#9392](https://github.com/DataDog/integrations-core/pull/9392).

## 2.8.0 / 2021-03-07 / Agent 7.27.0

* [Added] Add support for legacy config to OpenMetricsCompatibilityScraper. See [#8507](https://github.com/DataDog/integrations-core/pull/8507).
* [Fixed] Bump base package requirement. See [#8572](https://github.com/DataDog/integrations-core/pull/8572).

## 2.7.0 / 2021-01-25 / Agent 7.26.0

* [Added] Allow the use of the new OpenMetrics implementation. See [#8438](https://github.com/DataDog/integrations-core/pull/8438).
* [Fixed] Update prometheus_metrics_prefix documentation. See [#8236](https://github.com/DataDog/integrations-core/pull/8236).

## 2.6.0 / 2020-10-31 / Agent 7.24.0

* [Added] Add configuration spec. See [#7872](https://github.com/DataDog/integrations-core/pull/7872).

## 2.5.0 / 2020-05-17 / Agent 7.20.0

* [Added] Allow optional dependency installation for all checks. See [#6589](https://github.com/DataDog/integrations-core/pull/6589).

## 2.4.1 / 2020-04-04 / Agent 7.19.0

* [Fixed] Update deprecated imports. See [#6088](https://github.com/DataDog/integrations-core/pull/6088).

## 2.4.0 / 2020-01-13 / Agent 7.17.0

* [Added] Make OpenMetrics use the RequestsWrapper. See [#5414](https://github.com/DataDog/integrations-core/pull/5414).
* [Fixed] Raise exception to report when openmetrics process fails. See [#5392](https://github.com/DataDog/integrations-core/pull/5392).

## 2.3.0 / 2019-06-24 / Agent 6.13.0

* [Added] Support v2. See [#3911](https://github.com/DataDog/integrations-core/pull/3911).

## 2.2.0 / 2019-05-14 / Agent 6.12.0

* [Added] Adhere to code style. See [#3533](https://github.com/DataDog/integrations-core/pull/3533).

## 2.1.0 / 2019-02-18 / Agent 6.10.0

* [Added] Support Python 3. See [#3032](https://github.com/DataDog/integrations-core/pull/3032).

## 2.0.0 / 2018-10-12 / Agent 6.6.0

* [Changed] Update linkerd to use the new OpenMetricsBaseCheck. See [#1984][1].

## 1.2.0 / 2018-09-04 / Agent 6.5.0

* [Added] Limit Prometheus/OpenMetrics checks to 2000 metrics per run by default. See [#2093][2].
* [Added] Make HTTP request timeout configurable in prometheus checks. See [#1790][3].
* [Fixed] Add data files to the wheel package. See [#1727][4].

## 1.1.0 / 2018-06-07

* [Added] Support for gathering metrics from prometheus endpoint for the kubelet itself.. See [#1581][5].

## 1.0.0/ 2018-03-23

* [FEATURE] adds linkerd integration.
[1]: https://github.com/DataDog/integrations-core/pull/1984
[2]: https://github.com/DataDog/integrations-core/pull/2093
[3]: https://github.com/DataDog/integrations-core/pull/1790
[4]: https://github.com/DataDog/integrations-core/pull/1727
[5]: https://github.com/DataDog/integrations-core/pull/1581


text:
namespace ui {
class InputMethod;

class UI_BASE_IME_EXPORT MockIMEInputContextHandler
    : public IMEInputContextHandlerInterface {
 public:
  struct UpdateCompositionTextArg {
    CompositionText composition_text;
    uint32_t cursor_pos;
    bool is_visible;
  };

  struct DeleteSurroundingTextArg {
    int32_t offset;
    uint32_t length;
  };

  MockIMEInputContextHandler();
  virtual ~MockIMEInputContextHandler();

  void CommitText(const std::string& text) override;
  void UpdateCompositionText(const CompositionText& text,
                             uint32_t cursor_pos,
                             bool visible) override;
  void DeleteSurroundingText(int32_t offset, uint32_t length) override;
  void SendKeyEvent(KeyEvent* event) override;
  InputMethod* GetInputMethod() override;

  int commit_text_call_count() const { return commit_text_call_count_; }

  int update_preedit_text_call_count() const {
    return update_preedit_text_call_count_;
  }

  int delete_surrounding_text_call_count() const {
    return delete_surrounding_text_call_count_;
  }

  const std::string& last_commit_text() const { return last_commit_text_; };

  const UpdateCompositionTextArg& last_update_composition_arg() const {
    return last_update_composition_arg_;
  }

  const DeleteSurroundingTextArg& last_delete_surrounding_text_arg() const {
    return last_delete_surrounding_text_arg_;
  }

  // Resets all call count.
  void Reset();

 private:
  int commit_text_call_count_;
  int update_preedit_text_call_count_;
  int delete_surrounding_text_call_count_;
  std::string last_commit_text_;
  UpdateCompositionTextArg last_update_composition_arg_;
  DeleteSurroundingTextArg last_delete_surrounding_text_arg_;
};
}  // ui

#endif  // UI_BASE_IME_MOCK_IME_INPUT_CONTEXT_HANDLER_H_

redpajama_set_name: RedPajamaGithub


text:
package com.netsteadfast.greenstep.po.hbm;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import com.netsteadfast.greenstep.base.model.BaseEntity;
import com.netsteadfast.greenstep.base.model.EntityPK;
import com.netsteadfast.greenstep.base.model.EntityUK;

@Entity
@Table(
		name="bb_organization",
		uniqueConstraints = {
				@UniqueConstraint( columnNames = {"ORG_ID"} )
		}
)
public class BbOrganization extends BaseEntity<String> implements java.io.Serializable {
	private static final long serialVersionUID = 130728118214213245L;
	private String oid;
	private String orgId;
	private String name;
	private String address;
	private String lat;
	private String lng;
	private String description;
	private String cuserid;
	private Date cdate;
	private String uuserid;
	private Date udate;

	@Override
	@Id
	@EntityPK(name="oid")
	@Column(name="OID")
	public String getOid() {
		return oid;
	}
	@Override
	public void setOid(String oid) {
		this.oid = oid;
	}

	@EntityUK(name="orgId")
	@Column(name="ORG_ID")
	public String getOrgId() {
		return orgId;
	}

	public void setOrgId(String orgId) {
		this.orgId = orgId;
	}

	@Column(name="NAME")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Column(name="ADDRESS")
	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Column(name="LAT")
	public String getLat() {
		return lat;
	}

	public void setLat(String lat) {
		this.lat = lat;
	}

	@Column(name="LNG")
	public String getLng() {
		return lng;
	}

	public void setLng(String lng) {
		this.lng = lng;
	}

	@Column(name="DESCRIPTION")
	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@Override
	@Column(name="CUSERID")
	public String getCuserid() {
		return this.cuserid;
	}
	@Override
	public void setCuserid(String cuserid) {
		this.cuserid = cuserid;
	}
	@Override
	@Column(name="CDATE")
	public Date getCdate() {
		return this.cdate;
	}
	@Override
	public void setCdate(Date cdate) {
		this.cdate = cdate;
	}
	@Override
	@Column(name="UUSERID")
	public String getUuserid() {
		return this.uuserid;
	}
	@Override
	public void setUuserid(String uuserid) {
		this.uuserid = uuserid;
	}
	@Override
	@Column(name="UDATE")
	public Date getUdate() {
		return this.udate;
	}
	@Override
	public void setUdate(Date udate) {
		this.udate = udate;
	}

}


text:
void KeyStatsComputer::computeEHH_and_resetCloneList(PopGenData& data, std::deque<std::deque<size_t>>& cloneList, double& sumEHH, size_t& SNPi)
{
	// Reset all clone sets
	for (size_t cloneSet = 0 ; cloneSet < cloneList.size() ; )
	{
		// Split clone set
		std::deque<size_t> newCloneSet;
		for (size_t cloneIndex = 0 ; cloneIndex < cloneList[cloneSet].size() ; ++cloneIndex)
		{
			auto haplo = cloneList[cloneSet][cloneIndex];
			if (data.get(haplo, SNPi))
			{
				newCloneSet.push_back(haplo);
				cloneList[cloneSet].erase(cloneIndex);
			}
		}

		sumEHH += (double)(data.SNPposition(SNPi) - data.previousSNPposition(SNPi))/2 * pow((double) cloneList[cloneSet].size() / (double) data.nbHaplos(), 2) + pow((double) newCloneSet.size() / (double) data.nbHaplos(), 2);

		// Modify clone set
		if (cloneList[cloneSet].size() < 2 && newCloneSet.size() > 1)
		{
			// Switch clone set
			cloneList[cloneSet].swap(newCloneSet);
			++cloneSet
		} else
		{
			// Remove clone set if needed
			if (cloneList[cloneSet].size() < 2)
				cloneList.erase(cloneSet);
			else
				++cloneSet

			// Add clone set if needed
			if (newCloneSet.size() > 1)
				cloneList.push_back(newCloneSet);
		}
	}
}

std::pair<std::vector<double>, std::vector<double>> KeyStatsComputer::compute_iHS(PopGenData& data)
{
	std::vector<double> unstandard_iHS(data.nbSNPs());

	for (size_t SNPfocal = 0 ; SNPfocal < data.nbSNPs() ; ++SNPfocal)
	{
		double sumEHH_wt = 0.0;
		double sumEHH_mut = 0.0;

		std::deque<std::deque<size_t>> refCloneList_wt;
		std::deque<std::deque<size_t>> refCloneList_mut;
		for (size_t haplo = 0 ; haplo < data.nbHaplos() ; ++haplo)
		{
			if (data.get(haplo, SNPfocal))
				refCloneList_mut.push_back(haplo);
			else
				refCloneList_wt.push_back(haplo);
		}
		assert(refCloneList_wt.size());
		assert(refCloneList_mut.size());

		// left side
		if (SNPfocal > 1)
		{
			auto cloneLists_wt = refCloneList_wt;
			auto cloneLists_mut = refCloneList_mut;

			for (size_t SNPi = 0 ; SNPi < SNPfocal - 1 ; ++SNPi)
			{
				if (cloneLists_wt.size())computeEHH_and_resetCloneList(data, cloneLists_mut, sumEHH_mut, SNPi);
				if (cloneLists_mut.size())computeEHH_and_resetCloneList(data, cloneLists_wt, sumEHH_wt, SNPi);
				if (cloneLists_wt.size() == 0 && cloneLists_mut.size() == 0) break;
			}
		}

		// right side
		if (SNPfocal < data.nbHaplos()-1)
		{
			auto cloneLists_wt = refCloneList_wt;
			auto cloneLists_mut = refCloneList_mut;

			for (size_t SNPi = SNPfocal+1 ; SNPi < data.nbHaplos() ; ++SNPi)
			{
				if (cloneLists_wt.size())computeEHH_and_resetCloneList(data, cloneLists_mut, sumEHH_mut, SNPi);
				if (cloneLists_mut.size())computeEHH_and_resetCloneList(data, cloneLists_wt, sumEHH_wt, SNPi);
				if (cloneLists_wt.size() == 0 && cloneLists_mut.size() == 0) break;
			}
		}

		// Compute iHS
		unstandard_iHS[SNPfocal] = log(sumEHH_wt / sumEHH_mut);
	}

	// Standardize
	double mean_iHS = std::accumulate(unstandard_iHS.begin(), unstandard_iHS.end()) / unstandard_iHS.size();
	double var_iHS = 0.0;
	for (auto& uns_iHS : unstandard_iHS)
		var_iHS += pow(uns_iHS - mean_iHS, 2);
	var_iHS /= unstandard_iHS.size();

	std::vector<double> standard_iHS(data.nbSNPs());
	for (size_t SNPfocal = 0 ; SNPfocal < data.nbSNPs() ; ++SNPfocal)
		standard_iHS[SNPfocal] = (unstandard_iHS[SNPfocal] - mean_iHS) / var_iHS;

	return {unstandard_iHS, standard_iHS};
}

std::array<std::vector<double>, 3> KeyStatsComputer::compute_Hxy(PopGenData& data)
{
	for (size_t SNP = 0 ; SNP < data.nbSNPs() ; ++SNP)
	{
		double freq = 0.0;
		for (size_t haplo = 0 ; haplo < data.nbHaplos(); ++haplo)
		{
			freq += data.get(haplo, SNP);
		}
		freq /= data.nbHaplos();
		if (freq > 0.5)
		{
			H1 = freq * freq;
			H2 = (1-freq) * (1-freq);
		} else
		{
			H2 = freq * freq;
			H1 = (1-freq) * (1-freq);
		}
		H12 = ..

		Size of window??
		H1 = freq
	}
}

void KeyStatsComputer::computeAndWrite(PopGenData& data, std::string& outFilename)
{
	iHSData = compute_iHS(data);
	HxyData = compute_Hxy(data);
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.contentwarehouse.v1.model;

/**
 * Model definition for HtmlrenderWebkitHeadlessProtoRenderEvent.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class HtmlrenderWebkitHeadlessProtoRenderEvent extends com.google.api.client.json.GenericJson {

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private HtmlrenderWebkitHeadlessProtoFrameResizeEvent frameResize;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private HtmlrenderWebkitHeadlessProtoInitialLoadEvent initialLoad;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private HtmlrenderWebkitHeadlessProtoModalDialogEvent modalDialog;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private HtmlrenderWebkitHeadlessProtoRedirectEvent redirect;

  /**
   * The URL of the script which caused this event, if any. Analogous to origin_url in DOMTreeNode.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String scriptOriginUrl;

  /**
   * Virtual time of the event, as an offset from the beginning of the render in seconds.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Double virtualTimeOffset;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private HtmlrenderWebkitHeadlessProtoWindowOpenEvent windowOpen;

  /**
   * @return value or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoFrameResizeEvent getFrameResize() {
    return frameResize;
  }

  /**
   * @param frameResize frameResize or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoRenderEvent setFrameResize(HtmlrenderWebkitHeadlessProtoFrameResizeEvent frameResize) {
    this.frameResize = frameResize;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoInitialLoadEvent getInitialLoad() {
    return initialLoad;
  }

  /**
   * @param initialLoad initialLoad or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoRenderEvent setInitialLoad(HtmlrenderWebkitHeadlessProtoInitialLoadEvent initialLoad) {
    this.initialLoad = initialLoad;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoModalDialogEvent getModalDialog() {
    return modalDialog;
  }

  /**
   * @param modalDialog modalDialog or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoRenderEvent setModalDialog(HtmlrenderWebkitHeadlessProtoModalDialogEvent modalDialog) {
    this.modalDialog = modalDialog;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoRedirectEvent getRedirect() {
    return redirect;
  }

  /**
   * @param redirect redirect or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoRenderEvent setRedirect(HtmlrenderWebkitHeadlessProtoRedirectEvent redirect) {
    this.redirect = redirect;
    return this;
  }

  /**
   * The URL of the script which caused this event, if any. Analogous to origin_url in DOMTreeNode.
   * @return value or {@code null} for none
   */
  public java.lang.String getScriptOriginUrl() {
    return scriptOriginUrl;
  }

  /**
   * The URL of the script which caused this event, if any. Analogous to origin_url in DOMTreeNode.
   * @param scriptOriginUrl scriptOriginUrl or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoRenderEvent setScriptOriginUrl(java.lang.String scriptOriginUrl) {
    this.scriptOriginUrl = scriptOriginUrl;
    return this;
  }

  /**
   * Virtual time of the event, as an offset from the beginning of the render in seconds.
   * @return value or {@code null} for none
   */
  public java.lang.Double getVirtualTimeOffset() {
    return virtualTimeOffset;
  }

  /**
   * Virtual time of the event, as an offset from the beginning of the render in seconds.
   * @param virtualTimeOffset virtualTimeOffset or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoRenderEvent setVirtualTimeOffset(java.lang.Double virtualTimeOffset) {
    this.virtualTimeOffset = virtualTimeOffset;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoWindowOpenEvent getWindowOpen() {
    return windowOpen;
  }

  /**
   * @param windowOpen windowOpen or {@code null} for none
   */
  public HtmlrenderWebkitHeadlessProtoRenderEvent setWindowOpen(HtmlrenderWebkitHeadlessProtoWindowOpenEvent windowOpen) {
    this.windowOpen = windowOpen;
    return this;
  }

  @Override
  public HtmlrenderWebkitHeadlessProtoRenderEvent set(String fieldName, Object value) {
    return (HtmlrenderWebkitHeadlessProtoRenderEvent) super.set(fieldName, value);
  }

  @Override
  public HtmlrenderWebkitHeadlessProtoRenderEvent clone() {
    return (HtmlrenderWebkitHeadlessProtoRenderEvent) super.clone();
  }

}


text:
package ParticleSystem;

import java.awt.Rectangle;
import java.awt.Point;

/**
 * Object which manages where the viewable area is, in relation to world coordinates.
 * Used to determine if objects are "onscreen" and to determine what to draw to the screen.
 */
public class ViewScreen {
    private Rectangle screen;

    public ViewScreen(Rectangle viewableArea) {
        screen = viewableArea;
    }

    public void CenterOnCoords(Point new_coords) {
        screen.x = (new_coords.x -(screen.width / 2));
        screen.y = (new_coords.y -(screen.height / 2));
    }
    public void CenterOnObject(Rectangle objectBoundingBox) {
        screen.x = (objectBoundingBox.x - (screen.width / 2) - (objectBoundingBox.width / 2));
        screen.y = (objectBoundingBox.y - (screen.height / 2) - (objectBoundingBox.height / 2));
    }
    public void Move(Point movementVector) {
        screen.x = screen.x + movementVector.x;
        screen.y = screen.y + movementVector.y;
    }
    public void resize(Rectangle new_size) {
        screen = new_size;
    }
    public Rectangle getScreenBounds() {
        return screen;
    }

    public boolean isOnscreen(Point objectOrigin) {
        if (objectOrigin.x < screen.x || objectOrigin.x > (screen.x + screen.width)) {
            return false;
        } else if (objectOrigin.y < screen.y || objectOrigin.y > (screen.y + screen.height)) {
            return false;
        } else {
            return true;
        }
    }
    public boolean isOnscreen(Rectangle objectBoundingBox) {
        if ((objectBoundingBox.x + objectBoundingBox.width) < screen.x || objectBoundingBox.x > (screen.x + screen.width)) {
            return false;
        } else if ((objectBoundingBox.y + objectBoundingBox.height) < screen.y || objectBoundingBox.y > (screen.y + screen.height)) {
            return false;
        } else {
            return true;
        }
    }
}


text:
<?php
use _2UpMedia\Scout\DataPoint,
	_2UpMedia\Scout\QueryHandler\Xpath,
	_2UpMedia\Scout\QueryHandler\QueryHandlerInterface,
	_2UpMedia\Scout\Document\Html,
	_2UpMedia\Scout\Document\Xml,
	_2UpMedia\Scout\Exception\SkipException,
	_2UpMedia\Scout\Exception\StopException,
	_2UpMedia\Scout\Exception\CancelException;

class UseCaseTest extends PHPUnit_Framework_TestCase {
	/**
	 * @var QueryHandlerInterface
	 */
	protected $queryHandler;

	public function setUp()
	{
		$this->queryHandler = new Xpath(
			Html::parseDocument(file_get_contents('fixtures/testing-ground.scraping.pro.html'))
		);
	}

	public function testOneSimpleValue()
	{
		$queryHandler = $this->queryHandler;

		$headerDp = new DataPoint();
		$headerDp->set('id("title")/text()');
		$headerDp->setQueryHandler($queryHandler);
		$header = $headerDp->getData();

		$this->assertEquals('WEB SCRAPER TESTING GROUND', $header);
	}

	public function testCollectionOfSimpleValues()
	{
		$queryHandler = $this->queryHandler;

		$computerNamesDp = new DataPoint();
		$computerNamesDp->set('.//*[@id="case1"]//div[@class="name"]/text()', null, true);
		$computerNamesDp->setQueryHandler($queryHandler);
		$computerNames = $computerNamesDp->getData();

		$expect = array (
			0 => 'Dell Latitude D610-1.73 Laptop Wireless Computer',
			1 => 'Samsung Chromebook (Wi-Fi, 11.6-Inch)',
			2 => 'Apple MacBook Pro MD101LL/A 13.3-Inch Laptop (NEWEST VERSION)',
			3 => 'Acer Aspire AS5750Z-4835 15.6-Inch Laptop (Black)',
			4 => 'HP Pavilion g7-2010nr 17.3-Inch Laptop (Black)',
			5 => 'ASUS A53Z-AS61 15.6-Inch Laptop (Mocha)',
		);

		$this->assertEquals($expect, $computerNames);
	}

	public function testCollectionOfCompositeValues()
	{
		$queryHandler = $this->queryHandler;

		$computersDetailsDp = new DataPoint();
		$computersDetailsDp->setQueryHandler($queryHandler);
		$computersDetailsDp->setCollection("id('case1')/div[@class='prod1' or @class='prod2']");
		$computersDetailsDp('name')->set('.//div[@class="name"]/text()');
		$computersDetailsDp('price')->set('.//span[2]/text()');

		$computerDetails = $computersDetailsDp->getData();

		$expect = array (
			0 =>
				array (
					'name' => 'Dell Latitude D610-1.73 Laptop Wireless Computer',
					'price' => '$239.95',
				),
			1 =>
				array (
					'name' => 'Samsung Chromebook (Wi-Fi, 11.6-Inch)',
					'price' => '$249.00',
				),
			2 =>
				array (
					'name' => 'Apple MacBook Pro MD101LL/A 13.3-Inch Laptop (NEWEST VERSION)',
					'price' => '$1,099.99',
				),
			3 =>
				array (
					'name' => 'Acer Aspire AS5750Z-4835 15.6-Inch Laptop (Black)',
					'price' => '$385.72',
				),
			4 =>
				array (
					'name' => 'HP Pavilion g7-2010nr 17.3-Inch Laptop (Black)',
					'price' => '$549.99',
				),
			5 =>
				array (
					'name' => 'ASUS A53Z-AS61 15.6-Inch Laptop (Mocha)',
					'price' => '$399.99',
				),
		);

		$this->assertEquals($expect, $computerDetails);
	}

    public function testCollectionOfCompositeValuesWithForKey()
	{
		$queryHandler = $this->queryHandler;

		$computersDetailsDp = new DataPoint();
		$computersDetailsDp->setQueryHandler($queryHandler);
		$computersDetailsDp->setCollection("id('case1')/div[@class='prod1' or @class='prod2']");
		$computersDetailsDp->forKey('name')->set('.//div[@class="name"]/text()');
		$computersDetailsDp->forKey('price')->set('.//span[2]/text()');

		$computerDetails = $computersDetailsDp->getData();

		$expect = array (
			0 =>
				array (
					'name' => 'Dell Latitude D610-1.73 Laptop Wireless Computer',
					'price' => '$239.95',
				),
			1 =>
				array (
					'name' => 'Samsung Chromebook (Wi-Fi, 11.6-Inch)',
					'price' => '$249.00',
				),
			2 =>
				array (
					'name' => 'Apple MacBook Pro MD101LL/A 13.3-Inch Laptop (NEWEST VERSION)',
					'price' => '$1,099.99',
				),
			3 =>
				array (
					'name' => 'Acer Aspire AS5750Z-4835 15.6-Inch Laptop (Black)',
					'price' => '$385.72',
				),
			4 =>
				array (
					'name' => 'HP Pavilion g7-2010nr 17.3-Inch Laptop (Black)',
					'price' => '$549.99',
				),
			5 =>
				array (
					'name' => 'ASUS A53Z-AS61 15.6-Inch Laptop (Mocha)',
					'price' => '$399.99',
				),
		);

		$this->assertEquals($expect, $computerDetails);
	}

	public function testCollectionOfDataPoints()
	{
		$queryHandler = $this->queryHandler;

		$rootDp = new DataPoint();
		$rootDp->setQueryHandler($queryHandler);

		$headerDp = new DataPoint('header');
		$headerDp->set('id("title")/text()');

		$computersDetailsDp = new DataPoint('computers');
		$computersDetailsDp->setCollection("id('case1')/div[@class='prod1' or @class='prod2']");
		$computersDetailsDp('name')->set('.//div[@class="name"]/text()');
		$computersDetailsDp('price')->set('.//span[2]/text()');

		$discount = new DataPoint('discount');
		$discount->set('.//span[2]/div');

		$computersDetailsDp->add($discount);

		$rootDp->add($headerDp);
		$rootDp->add($computersDetailsDp);

		$result = $rootDp->getData();

		$expected = array (
			'header' => 'WEB SCRAPER TESTING GROUND',
			'computers' =>
				array (
					0 =>
						array (
							'discount' => NULL,
							'name' => 'Dell Latitude D610-1.73 Laptop Wireless Computer',
							'price' => '$239.95',
						),
					1 =>
						array (
							'discount' => NULL,
							'name' => 'Samsung Chromebook (Wi-Fi, 11.6-Inch)',
							'price' => '$249.00',
						),
					2 =>
						array (
							'discount' => NULL,
							'name' => 'Apple MacBook Pro MD101LL/A 13.3-Inch Laptop (NEWEST VERSION)',
							'price' => '$1,099.99',
						),
					3 =>
						array (
							'discount' => NULL,
							'name' => 'Acer Aspire AS5750Z-4835 15.6-Inch Laptop (Black)',
							'price' => '$385.72',
						),
					4 =>
						array (
							'discount' => 'discount 7%',
							'name' => 'HP Pavilion g7-2010nr 17.3-Inch Laptop (Black)',
							'price' => '$549.99',
						),
					5 =>
						array (
							'discount' => NULL,
							'name' => 'ASUS A53Z-AS61 15.6-Inch Laptop (Mocha)',
							'price' => '$399.99',
						),
				),
		);

		$this->assertEquals($expected, $result);
	}

	public function testCollectionOfSimpleDataPoints()
	{
		$queryHandler = $this->queryHandler;

		$rootDp = new DataPoint();
		$rootDp->setQueryHandler($queryHandler);

		$caseHeaderDp = new DataPoint();
		$caseHeaderDp->setRoot('id("case1")');

		$firstComputerDp = new DataPoint();
		$firstComputerDp->set('.//div[1]/span[1]/div');

		$secondComputerDp = new DataPoint();
		$secondComputerDp->set('.//div[2]/span[1]/div');

		$caseHeaderDp->add($firstComputerDp);
		$caseHeaderDp->add($secondComputerDp);

		$rootDp->add($caseHeaderDp);

		$return = $rootDp->getData();

		$expect = array (
			0 =>
				array (
					0 => 'Dell Latitude D610-1.73 Laptop Wireless Computer',
					1 => 'Samsung Chromebook (Wi-Fi, 11.6-Inch)',
				),
		);

		$this->assertEquals($expect, $return);
	}

	public function testSimpleValueWithCallable()
	{
		$self = $this;

		$queryHandler = $this->queryHandler;

		$headerDp = new DataPoint();
		$headerDp->set('id("title")/text()', function ($value, $queryHandler, $item) use ($self) {
			$self->assertInstanceOf('_2UpMedia\Scout\QueryHandler\QueryHandlerInterface', $queryHandler);
			$self->assertInstanceOf('DOMNode', $item);

			return $value.'1';
		});
		$headerDp->setQueryHandler($queryHandler);
		$header = $headerDp->getData();

		$this->assertEquals('WEB SCRAPER TESTING GROUND1', $header);
	}

	public function testCollectionOfSimpleValuesWithCallable()
	{
		$self = $this;

		$queryHandler = $this->queryHandler;

		$computerNamesDp = new DataPoint();

		$computerNamesDp->set(
			'.//*[@id="case1"]//div[@class="name"]/text()',
			function ($value, $queryHandler, $item, $index) use ($self) {
				$self->assertInstanceOf('_2UpMedia\Scout\QueryHandler\QueryHandlerInterface', $queryHandler);
				$self->assertInstanceOf('DOMNode', $item);
				$self->assertTrue(is_int($index));

				return $value.' 1';
			},
			true
		);

		$computerNamesDp->setQueryHandler($queryHandler);
		$computerNames = $computerNamesDp->getData();

		$expect = array (
			0 => 'Dell Latitude D610-1.73 Laptop Wireless Computer 1',
			1 => 'Samsung Chromebook (Wi-Fi, 11.6-Inch) 1',
			2 => 'Apple MacBook Pro MD101LL/A 13.3-Inch Laptop (NEWEST VERSION) 1',
			3 => 'Acer Aspire AS5750Z-4835 15.6-Inch Laptop (Black) 1',
			4 => 'HP Pavilion g7-2010nr 17.3-Inch Laptop (Black) 1',
			5 => 'ASUS A53Z-AS61 15.6-Inch Laptop (Mocha) 1',
		);

		$this->assertEquals($expect, $computerNames);
	}

	public function testCollectionOfCompositeValuesWithCallable()
	{
		$self = $this;

		$queryHandler = $this->queryHandler;

		$computersDetailsDp = new DataPoint();
		$computersDetailsDp->setCollection("id('case1')/div[@class='prod1' or @class='prod2']");
		$computersDetailsDp('name')->set(
			'.//div[@class="name"]/text()',
			function ($value, $queryHandler, $item, $index) use ($self) {
				$self->assertInstanceOf('_2UpMedia\Scout\QueryHandler\QueryHandlerInterface', $queryHandler);
				$self->assertInstanceOf('DOMNode', $item);
				$self->assertTrue(is_int($index));

				return $value.' 1';
			}
		);

		$computersDetailsDp('price')->set(
			'.//span[2]/text()',
			function ($value, $queryHandler, $item) use ($self) {
				$self->assertInstanceOf('_2UpMedia\Scout\QueryHandler\QueryHandlerInterface', $queryHandler);
				$self->assertInstanceOf('DOMNode', $item);

				return (float) number_format(preg_replace("/[^0-9\.]/", "", $value), 2, '.', '');
			}
		)
		;
		$computersDetailsDp->setQueryHandler($queryHandler);

		$computerDetails = $computersDetailsDp->getData();

		$expect = array (
			0 =>
				array (
					'name' => 'Dell Latitude D610-1.73 Laptop Wireless Computer 1',
					'price' => 239.95,
				),
			1 =>
				array (
					'name' => 'Samsung Chromebook (Wi-Fi, 11.6-Inch) 1',
					'price' => 249,
				),
			2 =>
				array (
					'name' => 'Apple MacBook Pro MD101LL/A 13.3-Inch Laptop (NEWEST VERSION) 1',
					'price' => 1099.99,
				),
			3 =>
				array (
					'name' => 'Acer Aspire AS5750Z-4835 15.6-Inch Laptop (Black) 1',
					'price' => 385.72,
				),
			4 =>
				array (
					'name' => 'HP Pavilion g7-2010nr 17.3-Inch Laptop (Black) 1',
					'price' => 549.99,
				),
			5 =>
				array (
					'name' => 'ASUS A53Z-AS61 15.6-Inch Laptop (Mocha) 1',
					'price' => 399.99,
				),
		);

		$this->assertEquals($expect, $computerDetails);
	}

	public function testSimpleValueWithCancelExceptionInCallable()
	{
		$self = $this;

		$queryHandler = $this->queryHandler;

		$headerDp = new DataPoint();
		$headerDp->set('id("title")/text()', function ($value) use ($self) {
			if (stripos($value, 'scraper') !== false) {
				throw new CancelException();
			}

			return $value.'1';
		});
		$headerDp->setQueryHandler($queryHandler);
		$header = $headerDp->getData();

		$this->assertNull($header);
	}

	public function testSimpleValueWithSkipExceptionInCallable()
	{
		$self = $this;

		$queryHandler = $this->queryHandler;

		$headerDp = new DataPoint();
		$headerDp->set('id("title")/text()', function ($value) use ($self) {
			if (stripos($value, 'scraper') !== false) {
				throw new SkipException();
			}

			return $value.'1';
		});
		$headerDp->setQueryHandler($queryHandler);
		$header = $headerDp->getData();

		$this->assertNull($header);
	}

	public function testSimpleValueWithStopExceptionInCallable()
	{
		$self = $this;

		$queryHandler = $this->queryHandler;

		$headerDp = new DataPoint();
		$headerDp->set('id("title")/text()', function ($value) use ($self) {
			if (stripos($value, 'scraper') !== false) {
				throw new StopException();
			}

			return $value.'1';
		});
		$headerDp->setQueryHandler($queryHandler);
		$header = $headerDp->getData();

		$this->assertEquals('WEB SCRAPER TESTING GROUND', $header);
	}

	public function testCollectionOfSimpleValuesWithCancelExceptionInCallable()
	{
		$queryHandler = $this->queryHandler;

		$computerNamesDp = new DataPoint();
		$computerNamesDp->set(
			'//*[@id="case1"]//div[@class="name"]/text()',
			function ($computerTitle) {
				if (strpos($computerTitle, 'ASUS') !== false) {
					throw new CancelException();
				}

				return $computerTitle;
			},
			true);
		$computerNamesDp->setQueryHandler($queryHandler);
		$computerNames = $computerNamesDp->getData();

		$this->assertEmpty($computerNames);
	}

	public function testCollectionOfSimpleValuesWithSkipExceptionInCallable()
	{
		$queryHandler = $this->queryHandler;

		$computerNamesDp = new DataPoint();
		$computerNamesDp->set(
			'//*[@id="case1"]//div[@class="name"]/text()',
			function ($computerTitle) {
				if (strpos($computerTitle, '15.') === false) { // filter out non-15 inch laptops
					throw new SkipException();
				}

				return $computerTitle;
			},
			true);
		$computerNamesDp->setQueryHandler($queryHandler);
		$computerNames = $computerNamesDp->getData();

		$expect = array (
			'Acer Aspire AS5750Z-4835 15.6-Inch Laptop (Black)',
			'ASUS A53Z-AS61 15.6-Inch Laptop (Mocha)',
		);

		$this->assertEquals($expect, $computerNames);
	}

	public function testCollectionOfSimpleValuesWithStopExceptionInCallable()
	{
		$queryHandler = $this->queryHandler;

		$computerNamesDp = new DataPoint();
		$computerNamesDp->set(
			'//*[@id="case1"]//div[@class="name"]/text()',
			function ($computerTitle) {
				if (strpos($computerTitle, 'Apple') !== false) {
					throw new StopException();
				}

				return $computerTitle;
			},
			true);
		$computerNamesDp->setQueryHandler($queryHandler);
		$computerNames = $computerNamesDp->getData();

		$expect = array (
			'Dell Latitude D610-1.73 Laptop Wireless Computer',
			'Samsung Chromebook (Wi-Fi, 11.6-Inch)',
			'Apple MacBook Pro MD101LL/A 13.3-Inch Laptop (NEWEST VERSION)'
		);

		$this->assertEquals($expect, $computerNames);
	}

	public function testCollectionOfCompositeValuesWithCancelExceptionInCallable()
	{
		$self = $this;

		$queryHandler = $this->queryHandler;

		$computersDetailsDp = new DataPoint();
		$computersDetailsDp->setCollection("id('case1')/div[@class='prod1' or @class='prod2']");

		$computersDetailsDp('name')->set(
			'.//div[@class="name"]/text()',
			function ($value) {
				if (strpos($value, 'Apple') !== false) {
					throw new CancelException();
				}

				return $value;
			}
		);
		$computersDetailsDp('price')->set(
			'.//span[2]/text()',
			function ($value) use ($self) {
				$value = (float) number_format(preg_replace("/[^0-9\.]/", "", $value), 2, '.', '');

				return $value;
			}
		);

		$computersDetailsDp->setQueryHandler($queryHandler);
		$computerDetails = $computersDetailsDp->getData();

		$this->assertEmpty($computerDetails);
	}

	public function testCollectionOfCompositeValuesWithSkipExceptionInCallable()
	{
		$self = $this;

		$queryHandler = $this->queryHandler;

		$computersDetailsDp = new DataPoint();
		$computersDetailsDp->setCollection("id('case1')/div[@class='prod1' or @class='prod2']");

		$computersDetailsDp('name')->set('.//div[@class="name"]/text()');
		$computersDetailsDp('price')->set(
			'.//span[2]/text()',
			function ($value) use ($self) {
				$value = (float) number_format(preg_replace("/[^0-9\.]/", "", $value), 2, '.', '');

				if ($value > 399) {
					throw new SkipException();
				}

				return $value;
			}
		);

		$computersDetailsDp->setQueryHandler($queryHandler);
		$computerDetails = $computersDetailsDp->getData();

		$expect = array (
			0 =>
				array (
					'name' => 'Dell Latitude D610-1.73 Laptop Wireless Computer',
					'price' => 239.95,
				),
			1 =>
				array (
					'name' => 'Samsung Chromebook (Wi-Fi, 11.6-Inch)',
					'price' => 249,
				),
			3 =>
				array (
					'name' => 'Acer Aspire AS5750Z-4835 15.6-Inch Laptop (Black)',
					'price' => 385.72,
				),
		);

		$this->assertEquals($expect, $computerDetails);
	}

	public function testCollectionOfCompositeValuesWithStopExceptionInCallable()
	{
		$self = $this;

		$queryHandler = $this->queryHandler;

		$computersDetailsDp = new DataPoint();
		$computersDetailsDp->setCollection("id('case1')/div[@class='prod1' or @class='prod2']");

		$computersDetailsDp('name')->set(
			'.//div[@class="name"]/text()',
			function ($value) {
				if (strpos($value, 'Apple') !== false) {
					throw new StopException();
				}

				return $value;
			}
		);
		$computersDetailsDp('price')->set(
			'.//span[2]/text()',
			function ($value) use ($self) {
				$value = (float) number_format(preg_replace("/[^0-9\.]/", "", $value), 2, '.', '');

				return $value;
			}
		);

		$computersDetailsDp->setQueryHandler($queryHandler);
		$computerDetails = $computersDetailsDp->getData();

		$expect = array (
			0 =>
				array (
					'name' => 'Dell Latitude D610-1.73 Laptop Wireless Computer',
					'price' => 239.95,
				),
			1 =>
				array (
					'name' => 'Samsung Chromebook (Wi-Fi, 11.6-Inch)',
					'price' => 249,
				),
			2 =>
				array (
					'name' => 'Apple MacBook Pro MD101LL/A 13.3-Inch Laptop (NEWEST VERSION)',
					'price' => 1099.99,
				),
		);

		$this->assertEquals($expect, $computerDetails);
	}

	/**
	 * @expectedException \Exception
	 */
	public function testNotSettingQueryHandlerThrowsException()
	{
		$dp = new DataPoint();
		$dp->getData();
	}

	/**
	 * @expectedException \Exception
	 */
	public function testBadXpathThrowsException()
	{
		$this->queryHandler->setSelector('asdioihw(&$&(');
		$this->queryHandler->getData();
	}

	/**
	 * @expectedException \Exception
	 */
	public function testBadXMLThrowsException()
	{
		$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
	<CD>
		<TITLE>Empire Burlesque</TITLE>
		<ARTIST>Bob Dylan</ARTIST>
		<COUNTRY>USA</COUNTRY>
		<COMPANY>Columbia</COMPANY>
		<PRICE>10.90</PRICE>
		<YEAR>1985</YEAR>
	</CD>
XML;

		$queryHandler = new Xpath(Xml::parseDocument($xml));
	}
}


text:
This is the source code for the edX mobile Android app. It is changing rapidly
and its structure should not be relied upon. See http://code.edx.org for other
parts of the edX code base.

It requires the "Dogwood" release of open edX or newer. See
https://openedx.atlassian.net/wiki/display/COMM/Open+edX+Releases for more
information.

License
=======
This software is licensed under version 2 of the Apache License unless
otherwise noted. Please see ``LICENSE.txt`` for details.

Building
========

This project is meant to be built using Android Studio. It can also be built from the ``gradle`` command line.

1. Check out the source code: ::

	git clone https://github.com/edx/edx-app-android

2. Open Android Studio and choose **Open an Existing Android Studio Project**

3. Choose ``edx-app-android``.

4. Click the **Run** button.

Configuration
=============
The edX mobile Android app is designed to connect to an Open edX instance. You
must configure the app with the correct server address and supply appropriate
OAuth credentials. We use a configuration file mechanism similar to that of the
Open edX platform. This mechanism is also used to make other values available
to the app at runtime and store secret keys for third party services.

There is a default configuration that points to an edX devstack instance
running on localhost. See the ``default_config`` directory. For the default
configuration to work, you must add OAuth credentials specific to your
installation.

Setup
-----
To use a custom configuration in place of the default configuration, you will need to complete these tasks:

1. Create your own configuration directory somewhere else on the file system. For example, create ``my_config`` as a sibling of the ``edx-app-android`` repository.

2. Create an ``edx.properties`` file inside the ``OpenEdXMobile`` directory of ``edx-app-android``. In this ``edx.properties`` file, set the ``edx.dir`` property to the path to your configuration directory relative to the ``OpenEdXMobile`` directory. For example, if I stored my configuration side by side with the ``edx-app-android`` repository at `my_config`` then I'd have the following ``edx.properties``:

::

    edx.dir = '../../my_config'

3.  In the configuration directory that you added in step 1, create another
``edx.properties`` file. This properties file contains a list of filenames. The files should be in YAML format and are for storing specific keys. These files are specified relative to the configuration directory. Keys in files earlier in the list will be overridden by keys from files later in the list. For example, if I had two files, one shared between ios and android called ``shared.yaml`` and one with Android specific keys called ``android.yaml``, I would have the following ``edx.properties``:

::

    edx.android {
        configFiles = ['shared.yaml', 'android.yaml']
    }

The full set of known keys can be found in the
``org/edx/mobile/util/Config.java`` file or see `additional documentation <https://openedx.atlassian.net/wiki/display/MA/App+Configuration+Flags>`_.

Building For Release
--------------------
To build an APK for release, you must specify an application ID and signing key. Create or edit the ``gradle.properties`` file inside the ``OpenEdXMobile`` directory of ``edx-app-android``. For example:

::

    APPLICATION_ID=com.example.yourapp
    RELEASE_STORE_FILE=../../path/to/your.keystore
    RELEASE_STORE_PASSWORD=your store password here
    RELEASE_KEY_PASSWORD=your key password here
    RELEASE_KEY_ALIAS=your key alias here

Now you can build a release build from Android Studio. Or, in the directory of ``edx-app-android`` you can build a release build with this gradle command:

::

    ./gradlew assembleProdRelease

Customization
-------------
To customize images, colors, and layouts, you can specify a custom resource directory. Create or edit the ``gradle.properties`` file inside the ``OpenEdXMobile`` directory of ``edx-app-android``. For example:

::

    RES_DIR = ../../path/to/your/res

Any resources placed here will override resources of the same name in the ``OpenEdXMobile/res`` directory.

To remove all edX branding, override the drawables for: ``edx_logo``, ``edx_logo_login``, ``ic_launcher``, ``ic_new_cert``, and ``profile_photo_placeholder``. These come in a number of resolutions, be sure to replace them all.

If you need to make more in depth UI changes, most of the user interface is specified in standard Android XML files, which you can also override by placing new versions in your ``RES_DIR``.

Third Party Services
--------------------
The app relies on the presence of several third party services: Facebook, NewRelic, Google+, SegmentIO, and Crashlytics. You may need to remove services you choose not to use. You can comment out the lines of code that mention these services.

We're working on making it easier for Open edX installations to apply customizations and select third party services without modifying the repository itself.

Frequently Asked Questions
==========================
Q: I see an error that mentions "Unsupported major.minor version 51.0". How do I fix this?

A: Our build system requires Java 7 or later. If you see this error, install Java 7 or later.

	 You will also need to specify the new JDK version in Android Studio. Refer to this Stack Overflow entry for help doing so:

	 http://stackoverflow.com/questions/30631286/how-to-specify-the-jdk-version-in-android-studio


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

package com.anaplan.client;

import com.anaplan.client.dto.ImportData;
import com.anaplan.client.dto.TaskParametersData;
import com.anaplan.client.dto.responses.ChunksResponse;
import com.anaplan.client.dto.responses.TaskResponse;
import com.anaplan.client.dto.responses.TaskStatusResponse;
import com.anaplan.client.dto.responses.TasksResponse;
import com.anaplan.client.ex.AnaplanAPIException;

/**
 * An import object within an Anaplan model.
 */
public class Import extends TaskFactory {

    /**
     * The set of types of import definition.
     * This enumerates possible import types available at the release of this
     * version of Anaplan Connect. It may be the case that other types have
     * added to Anaplan in the intervening period. Clients should be aware of,
     * and handle, this potential condition gracefully.
     */
    public enum ImportType {
        /**
         * An import into a list.
         */
        HIERARCHY_DATA("List data"),
        /**
         * An import into a module (data) view.
         */
        MODULE_DATA("Module data"),
        /**
         * An import into a module blueprint view.
         */
        LINE_ITEM_DEFINITION("Module blueprint"),
        /**
         * An import into the Users view.
         */
        USERS("Users"),
        /**
         * An import into the Versions view.
         */
        VERSIONS("Versions");
        private String description;

        ImportType(String description) {
            this.description = description;
        }

        @Override
        public String toString() {
            return description;
        }
    }

    Import(Model model, ImportData data) {
        super(model, data);
    }

    @Override
    TaskResponse createActionTask(TaskParametersData taskParametersData) {
        return getApi().createImportTask(
                getWorkspace().getId(),
                getModel().getId(),
                getId(),
                getData().merge(taskParametersData, ImportData.class));
    }

    @Override
    TasksResponse getTasks(int offset) {
        return getApi().getImportTasks(
                getWorkspace().getId(),
                getModel().getId(),
                getId(),
                offset);
    }

    @Override
    TaskStatusResponse cancelTask(String taskId) {
        return getApi().cancelImportTask(
                getWorkspace().getId(),
                getModel().getId(),
                getId(),
                taskId);
    }

    @Override
    TaskStatusResponse getTaskStatus(String taskId) {
        return getApi().getImportTaskStatus(
                getWorkspace().getId(),
                getModel().getId(),
                getId(),
                taskId);
    }

    @Override
    ChunksResponse getDumpFileChunks(String taskId) {
        return getApi().getImportDumpFileChunks(
                getWorkspace().getId(),
                getModel().getId(),
                getId(),
                taskId);
    }

    @Override
    byte[] getDumpFileChunkContent(String taskId, String chunkId) {
        return getApi().getImportDumpFileChunkContent(
                getWorkspace().getId(),
                getModel().getId(),
                getId(),
                taskId,
                chunkId);
    }

    @Override
    ChunksResponse getNestedDumpFileChunks(String taskId, String nestedObjectId) {
        return getApi().getImportNestedDumpFileChunks(
                getWorkspace().getId(),
                getModel().getId(),
                getId(),
                taskId,
                nestedObjectId);
    }

    @Override
    byte[] getNestedDumpFileChunkContent(String taskId, String nestedObjectId, String chunkId) {
        return getApi().getImportNestedDumpFileChunkContent(
                getWorkspace().getId(),
                getModel().getId(),
                getId(),
                taskId,
                nestedObjectId,
                chunkId);
    }

    /**
     * Get the ID of the data source associated with the import, if it is an uploaded file.
     *
     * @return the ID for the data source if it is a file; otherwise the empty
     * string ("") is returned.
     * @since 1.2
     */
    public String getSourceFileId() throws AnaplanAPIException {
        return ((ImportData) getData()).getImportDataSourceId();
    }

    /**
     * Get the type of import.
     *
     * @return The import type; null if the type is not recognized by this
     * version of Anaplan Connect.
     * @since 1.3
     */
    public ImportType getImportType() {
        try {
            return ImportType.valueOf(((ImportData) getData()).getImportType());
        } catch (Exception e) {
            return null;
        }
    }
}


text:
<?php

namespace Respect\Validation\Rules\SubdivisionCode;

use Respect\Validation\Rules\AbstractSearcher;

/**
 * Validator for Martinique subdivision code.
 *
 * ISO 3166-1 alpha-2: MQ
 *
 * @link http://www.geonames.org/MQ/administrative-division-martinique.html
 */
class MqSubdivisionCode extends AbstractSearcher
{
    public $haystack = array(null, '');

    public $compareIdentical = true;
}


text:
<?php declare(strict_types=1);

namespace JBR\Advini\Interfaces {

    /**
     *
     *
     */
    interface Setter
    {
        /**
         * @param string $methodName
         * @param callable|string $value
         *
         * @return mixed
         */
        public function execute(string $methodName, $value);
    }
}


text:
title: '**Amor Towles** -  *A Gentleman in Moscow*'
published: true
start_at: 2016-09-07T19:00:00.000Z
image_path:
book_category:
program: '-writers-and-readers'
ticketed: false
test:
book_isbn:
  - '9780670026197'
---

With his breakout debut novel, *Rules of Civility*, Amor Towles established himself as a master of absorbing, historical fiction. *A Gentleman in Moscow* immerses us in another elegantly drawn era with the story of Count Alexander Rostov. When, in 1922, he is deemed an unrepentant aristocrat by a Bolshevik tribunal, the count is sentenced to house arrest in a hotel across the street from the Kremlin. Unexpectedly, his reduced circumstances provide him a doorway into a much larger world of emotional discovery.


text:
namespace MoHEmotionPilot
{
    using System;
    using System.Collections.Generic;

    public partial class Emotion
    {
        public int Emo_ID { get; set; }
        public string Emo_Title { get; set; }
        public string Emo_Score { get; set; }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cetraria lanosa f. lanosa

### Remarks
null


text:
using Microsoft.Practices.Prism.Events;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using TeamProjectManager.Common;
using TeamProjectManager.Common.Events;
using TeamProjectManager.Common.Infrastructure;
using TeamProjectManager.Common.ObjectModel;

namespace TeamProjectManager.Modules.WorkItemConfiguration.Categories
{
    [Export]
    public class WorkItemCategoriesViewModel : ViewModelBase
    {
        #region Properties

        public RelayCommand GetWorkItemCategoriesCommand { get; private set; }
        public RelayCommand DeleteSelectedWorkItemCategoriesCommand { get; private set; }
        public RelayCommand GetWorkItemCategoriesXmlCommand { get; private set; }
        public RelayCommand ExportSelectedWorkItemCategoriesXmlCommand { get; private set; }
        public RelayCommand EditSelectedWorkItemCategoriesXmlCommand { get; private set; }
        public RelayCommand TransformSelectedWorkItemCategoriesXmlCommand { get; private set; }
        public RelayCommand LoadWorkItemCategoryListCommand { get; private set; }
        public RelayCommand AddWorkItemCategoryCommand { get; private set; }
        public RelayCommand RemoveSelectedWorkItemCategoryCommand { get; private set; }
        public RelayCommand ImportWorkItemCategoryListCommand { get; private set; }

        #endregion

        #region Observable Properties

        public ICollection<WorkItemCategoryInfo> WorkItemCategories
        {
            get { return this.GetValue(WorkItemCategoriesProperty); }
            set { this.SetValue(WorkItemCategoriesProperty, value); }
        }

        public static ObservableProperty<ICollection<WorkItemCategoryInfo>> WorkItemCategoriesProperty = new ObservableProperty<ICollection<WorkItemCategoryInfo>, WorkItemCategoriesViewModel>(o => o.WorkItemCategories);

        public ICollection<WorkItemCategoryInfo> SelectedWorkItemCategories
        {
            get { return this.GetValue(SelectedWorkItemCategoriesProperty); }
            set { this.SetValue(SelectedWorkItemCategoriesProperty, value); }
        }

        public static ObservableProperty<ICollection<WorkItemCategoryInfo>> SelectedWorkItemCategoriesProperty = new ObservableProperty<ICollection<WorkItemCategoryInfo>, WorkItemCategoriesViewModel>(o => o.SelectedWorkItemCategories);

        public ICollection<WorkItemConfigurationItemExport> WorkItemCategoriesXml
        {
            get { return this.GetValue(WorkItemCategoriesXmlProperty); }
            set { this.SetValue(WorkItemCategoriesXmlProperty, value); }
        }

        public static readonly ObservableProperty<ICollection<WorkItemConfigurationItemExport>> WorkItemCategoriesXmlProperty = new ObservableProperty<ICollection<WorkItemConfigurationItemExport>, WorkItemCategoriesViewModel>(o => o.WorkItemCategoriesXml);

        public ICollection<WorkItemConfigurationItemExport> SelectedWorkItemCategoriesXml
        {
            get { return this.GetValue(SelectedWorkItemCategoriesXmlProperty); }
            set { this.SetValue(SelectedWorkItemCategoriesXmlProperty, value); }
        }

        public static readonly ObservableProperty<ICollection<WorkItemConfigurationItemExport>> SelectedWorkItemCategoriesXmlProperty = new ObservableProperty<ICollection<WorkItemConfigurationItemExport>, WorkItemCategoriesViewModel>(o => o.SelectedWorkItemCategoriesXml);

        public WorkItemCategoryList SelectedWorkItemCategoryList
        {
            get { return this.GetValue(SelectedWorkItemCategoryListProperty); }
            set { this.SetValue(SelectedWorkItemCategoryListProperty, value); }
        }

        public static ObservableProperty<WorkItemCategoryList> SelectedWorkItemCategoryListProperty = new ObservableProperty<WorkItemCategoryList, WorkItemCategoriesViewModel>(o => o.SelectedWorkItemCategoryList);

        public WorkItemCategory SelectedWorkItemCategory
        {
            get { return this.GetValue(SelectedWorkItemCategoryProperty); }
            set { this.SetValue(SelectedWorkItemCategoryProperty, value); }
        }

        public static ObservableProperty<WorkItemCategory> SelectedWorkItemCategoryProperty = new ObservableProperty<WorkItemCategory, WorkItemCategoriesViewModel>(o => o.SelectedWorkItemCategory);

        public ICollection<WorkItemTypeReference> AvailableWorkItemTypeReferences
        {
            get { return this.GetValue(AvailableWorkItemTypeReferencesProperty); }
            set { this.SetValue(AvailableWorkItemTypeReferencesProperty, value); }
        }

        public static ObservableProperty<ICollection<WorkItemTypeReference>> AvailableWorkItemTypeReferencesProperty = new ObservableProperty<ICollection<WorkItemTypeReference>, WorkItemCategoriesViewModel>(o => o.AvailableWorkItemTypeReferences);

        #endregion

        #region Constructors

        [ImportingConstructor]
        public WorkItemCategoriesViewModel(IEventAggregator eventAggregator, ILogger logger)
            : base(eventAggregator, logger, "Work Item Categories", "Allows you to manage work item categories.")
        {
            this.GetWorkItemCategoriesCommand = new RelayCommand(GetWorkItemCategories, CanGetWorkItemCategories);
            this.DeleteSelectedWorkItemCategoriesCommand = new RelayCommand(DeleteSelectedWorkItemCategories, CanDeleteSelectedWorkItemCategories);
            this.GetWorkItemCategoriesXmlCommand = new RelayCommand(GetWorkItemCategoriesXml, CanGetWorkItemCategoriesXml);
            this.ExportSelectedWorkItemCategoriesXmlCommand = new RelayCommand(ExportSelectedWorkItemCategoriesXml, CanExportSelectedWorkItemCategoriesXml);
            this.EditSelectedWorkItemCategoriesXmlCommand = new RelayCommand(EditSelectedWorkItemCategoriesXml, CanEditSelectedWorkItemCategoriesXml);
            this.TransformSelectedWorkItemCategoriesXmlCommand = new RelayCommand(TransformSelectedWorkItemCategoriesXml, CanTransformSelectedWorkItemCategoriesXml);
            this.LoadWorkItemCategoryListCommand = new RelayCommand(LoadWorkItemCategoryList, CanLoadWorkItemCategoryList);
            this.AddWorkItemCategoryCommand = new RelayCommand(AddWorkItemCategory, CanAddWorkItemCategory);
            this.RemoveSelectedWorkItemCategoryCommand = new RelayCommand(RemoveSelectedWorkItemCategory, CanRemoveSelectedWorkItemCategory);
            this.ImportWorkItemCategoryListCommand = new RelayCommand(ImportWorkItemCategoryList, CanImportWorkItemCategoryList);
        }

        #endregion

        #region Commands

        private bool CanGetWorkItemCategories(object argument)
        {
            return IsAnyTeamProjectSelected();
        }

        private void GetWorkItemCategories(object argument)
        {
            var teamProjectNames = this.SelectedTeamProjects.Select(p => p.Name).ToList();
            var task = new ApplicationTask("Retrieving work item categories", teamProjectNames.Count, true);
            PublishStatus(new StatusEventArgs(task));
            var step = 0;
            var worker = new BackgroundWorker();
            worker.DoWork += (sender, e) =>
            {
                var tfs = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService<WorkItemStore>();

                var results = new List<WorkItemCategoryInfo>();
                foreach (var teamProjectName in teamProjectNames)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProjectName));
                    try
                    {
                        var project = store.Projects[teamProjectName];
                        var categoriesXml = WorkItemConfigurationItemImportExport.GetCategoriesXml(project);
                        var categoryList = WorkItemCategoryList.Load(categoriesXml);
                        foreach (var category in categoryList.Categories)
                        {
                            results.Add(new WorkItemCategoryInfo(teamProjectName, categoryList, category));
                        }
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProjectName), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                e.Result = results;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving work item categories", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.WorkItemCategories = (ICollection<WorkItemCategoryInfo>)e.Result;
                    task.SetComplete("Retrieved " + this.WorkItemCategories.Count.ToCountString("work item category"));
                }
            };
            worker.RunWorkerAsync();
        }

        private bool CanDeleteSelectedWorkItemCategories(object argument)
        {
            return this.SelectedWorkItemCategories != null && this.SelectedWorkItemCategories.Count > 0;
        }

        private void DeleteSelectedWorkItemCategories(object argument)
        {
            var workItemCategoriesToDelete = this.SelectedWorkItemCategories;

            var result = MessageBox.Show("This will delete the selected work item categories. Certain applications like Microsoft Test Manager rely on categories so deleting them can reduce their functionality. Are you sure you want to continue?", "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            var task = new ApplicationTask("Deleting " + workItemCategoriesToDelete.Count.ToCountString("work item category"), workItemCategoriesToDelete.Count, true);
            PublishStatus(new StatusEventArgs(task));
            var step = 0;
            var worker = new BackgroundWorker();
            worker.DoWork += (sender, e) =>
            {
                var tfs = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService<WorkItemStore>();
                foreach (var categoriesByTeamProject in workItemCategoriesToDelete.GroupBy(c => c.TeamProject).ToList())
                {
                    var teamProjectName = categoriesByTeamProject.Key;
                    try
                    {
                        var project = store.Projects[teamProjectName];
                        var categoriesXml = WorkItemConfigurationItemImportExport.GetCategoriesXml(project);
                        var categoryList = WorkItemCategoryList.Load(categoriesXml);

                        foreach (var workItemCategoryToDelete in categoriesByTeamProject)
                        {
                            try
                            {
                                task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Deleting work item category \"{0}\" from Team Project \"{1}\"", workItemCategoryToDelete.WorkItemCategory.Name, workItemCategoryToDelete.TeamProject));
                                var category = categoryList.Categories.FirstOrDefault(c => string.Equals(c.RefName, workItemCategoryToDelete.WorkItemCategory.RefName, StringComparison.OrdinalIgnoreCase));
                                if (category != null)
                                {
                                    categoryList.Categories.Remove(category);
                                }
                            }
                            catch (Exception exc)
                            {
                                task.SetError(string.Format(CultureInfo.CurrentCulture, "An error occurred while deleting the work item category \"{0}\" for Team Project \"{1}\"", workItemCategoryToDelete.WorkItemCategory.Name, workItemCategoryToDelete.TeamProject), exc);
                            }
                        }

                        categoriesXml = categoryList.Save();
                        WorkItemConfigurationItemImportExport.SetCategories(project, categoriesXml);
                    }
                    catch (Exception exc)
                    {
                        task.SetError(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProjectName), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while deleting work item categories", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete("Deleted " + workItemCategoriesToDelete.Count.ToCountString("work item category"));
                }

                // Refresh the list.
                GetWorkItemCategories(null);
            };
            worker.RunWorkerAsync();
        }

        private bool CanGetWorkItemCategoriesXml(object argument)
        {
            return IsAnyTeamProjectSelected();
        }

        private void GetWorkItemCategoriesXml(object argument)
        {
            var teamProjects = this.SelectedTeamProjects.ToList();
            var task = new ApplicationTask("Retrieving work item categories", teamProjects.Count, true);
            PublishStatus(new StatusEventArgs(task));
            var step = 0;
            var worker = new BackgroundWorker();
            worker.DoWork += (sender, e) =>
            {
                var tfs = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService<WorkItemStore>();

                var results = new List<WorkItemConfigurationItemExport>();
                foreach (var teamProject in teamProjects)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProject.Name));
                    try
                    {
                        var project = store.Projects[teamProject.Name];
                        var categories = WorkItemConfigurationItemImportExport.GetCategories(project);
                        var categoriesInfo = new WorkItemConfigurationItemExport(teamProject, categories);
                        results.Add(categoriesInfo);
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                e.Result = results;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving work item categories", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.WorkItemCategoriesXml = (ICollection<WorkItemConfigurationItemExport>)e.Result;
                    task.SetComplete("Retrieved " + this.WorkItemCategoriesXml.Count.ToCountString("work item category file"));
                }
            };
            worker.RunWorkerAsync();
        }

        private bool CanExportSelectedWorkItemCategoriesXml(object argument)
        {
            return CanEditSelectedWorkItemCategoriesXml(argument);
        }

        private void ExportSelectedWorkItemCategoriesXml(object argument)
        {
            var categoriesToExport = new List<WorkItemConfigurationItemExport>();
            var categoriesExports = this.SelectedWorkItemCategoriesXml.ToList();
            if (categoriesExports.Count == 1)
            {
                // Export to single file.
                var categoriesExport = categoriesExports.Single();
                var dialog = new SaveFileDialog();
                dialog.FileName = categoriesExport.Item.DisplayName + ".xml";
                dialog.Filter = "XML Files (*.xml)|*.xml";
                var result = dialog.ShowDialog(Application.Current.MainWindow);
                if (result == true)
                {
                    categoriesToExport.Add(new WorkItemConfigurationItemExport(categoriesExport.TeamProject, categoriesExport.Item, dialog.FileName));
                }
            }
            else
            {
                // Export to a directory structure.
                var dialog = new System.Windows.Forms.FolderBrowserDialog();
                dialog.Description = "Please select the path where to export the Work Item Categories files (*.xml). They will be stored in a folder per Team Project.";
                var result = dialog.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    var rootFolder = dialog.SelectedPath;
                    foreach (var categoriesExport in categoriesExports)
                    {
                        var fileName = Path.Combine(rootFolder, categoriesExport.TeamProject.Name, categoriesExport.Item.DisplayName + ".xml");
                        categoriesToExport.Add(new WorkItemConfigurationItemExport(categoriesExport.TeamProject, categoriesExport.Item, fileName));
                    }
                }
            }

            var task = new ApplicationTask("Exporting work item categories", categoriesExports.Count, true);
            PublishStatus(new StatusEventArgs(task));
            var worker = new BackgroundWorker();
            worker.DoWork += (sender, e) =>
            {
                WorkItemConfigurationItemImportExport.Export(this.Logger, task, categoriesToExport);
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while exporting work item categories", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete("Exported " + categoriesToExport.Count.ToCountString("work item category file"));
                }
            };
            worker.RunWorkerAsync();
        }

        private bool CanEditSelectedWorkItemCategoriesXml(object argument)
        {
            return this.SelectedWorkItemCategoriesXml != null && this.SelectedWorkItemCategoriesXml.Any();
        }

        private void EditSelectedWorkItemCategoriesXml(object argument)
        {
            var categoriesToEdit = this.SelectedWorkItemCategoriesXml.ToList();
            var dialog = new WorkItemConfigurationItemEditorDialog(categoriesToEdit, "Work Item Category File");
            dialog.Owner = Application.Current.MainWindow;
            if (dialog.ShowDialog() == true)
            {
                var options = dialog.Options;
                var result = MessageBoxResult.Yes;
                if (!options.HasFlag(ImportOptions.Simulate))
                {
                    result = MessageBox.Show("This will import the edited work item categories. Are you sure you want to continue?", "Confirm Import", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                }
                if (result == MessageBoxResult.Yes)
                {
                    var teamProjectsWithCategories = categoriesToEdit.GroupBy(w => w.TeamProject).ToDictionary(g => g.Key, g => g.Select(w => w.Item).ToList());
                    PerformImport(teamProjectsWithCategories, options);
                }
            }
        }

        private bool CanTransformSelectedWorkItemCategoriesXml(object argument)
        {
            return CanEditSelectedWorkItemCategoriesXml(argument);
        }

        private void TransformSelectedWorkItemCategoriesXml(object argument)
        {
            var categoriesToTransform = this.SelectedWorkItemCategoriesXml.ToList();
            var dialog = new WorkItemConfigurationItemTransformationEditorDialog(categoriesToTransform, "Work Item Category File");
            dialog.Owner = Application.Current.MainWindow;
            if (dialog.ShowDialog() == true)
            {
                var options = dialog.Options;
                var result = MessageBoxResult.Yes;
                if (!options.HasFlag(ImportOptions.Simulate))
                {
                    result = MessageBox.Show("This will import the transformed work item categories. Are you sure you want to continue?", "Confirm Import", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                }
                if (result == MessageBoxResult.Yes)
                {
                    var teamProjectsWithCategories = categoriesToTransform.GroupBy(w => w.TeamProject).ToDictionary(g => g.Key, g => g.Select(w => w.Item).ToList());
                    PerformImport(teamProjectsWithCategories, options);
                }
            }
        }

        private bool CanLoadWorkItemCategoryList(object argument)
        {
            return true;
        }

        private void LoadWorkItemCategoryList(object argument)
        {
            using (var dialog = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false))
            {
                var result = dialog.ShowDialog(Application.Current.MainWindow.GetIWin32Window());
                if (result == System.Windows.Forms.DialogResult.OK && dialog.SelectedProjects != null && dialog.SelectedProjects.Length > 0)
                {
                    var teamProjectCollection = dialog.SelectedTeamProjectCollection;
                    var teamProject = dialog.SelectedProjects.First();

                    var task = new ApplicationTask("Loading work item category list");
                    PublishStatus(new StatusEventArgs(task));
                    var worker = new BackgroundWorker();
                    worker.DoWork += (sender, e) =>
                    {
                        var tfs = GetTfsTeamProjectCollection(teamProjectCollection.Uri);
                        var store = tfs.GetService<WorkItemStore>();
                        var project = store.Projects[teamProject.Name];
                        var categoriesXml = WorkItemConfigurationItemImportExport.GetCategoriesXml(project);
                        var selectedWorkItemCategoryList = WorkItemCategoryList.Load(categoriesXml);
                        var availableWorkItemTypeReferences = project.WorkItemTypes.Cast<WorkItemType>().Select(w => new WorkItemTypeReference { Name = w.Name }).ToList();
                        e.Result = new Tuple<WorkItemCategoryList, ICollection<WorkItemTypeReference>>(selectedWorkItemCategoryList, availableWorkItemTypeReferences);
                    };
                    worker.RunWorkerCompleted += (sender, e) =>
                    {
                        if (e.Error != null)
                        {
                            Logger.Log("An unexpected exception occurred while importing the work item category list", e.Error);
                            task.SetError(e.Error);
                            task.SetComplete("An unexpected exception occurred");
                        }
                        else
                        {
                            var loadResult = (Tuple<WorkItemCategoryList, ICollection<WorkItemTypeReference>>)e.Result;
                            this.SelectedWorkItemCategoryList = loadResult.Item1;
                            this.AvailableWorkItemTypeReferences = loadResult.Item2;
                            this.SelectedWorkItemCategory = this.SelectedWorkItemCategoryList.Categories.FirstOrDefault();
                            task.SetComplete("Done");
                        }
                    };
                    worker.RunWorkerAsync();
                }
            }
        }

        private bool CanImportWorkItemCategoryList(object argument)
        {
            return IsAnyTeamProjectSelected() && this.SelectedWorkItemCategoryList != null;
        }

        private void ImportWorkItemCategoryList(object argument)
        {
            var result = MessageBox.Show("This will import the work item category list to all selected Team Projects. Certain applications like Microsoft Test Manager rely on categories so modifying them can reduce their functionality. Are you sure you want to continue?", "Confirm Import", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            var task = new ApplicationTask("Importing work item category list", this.SelectedTeamProjects.Count, true);
            PublishStatus(new StatusEventArgs(task));
            var step = 0;
            var worker = new BackgroundWorker();
            worker.DoWork += (sender, e) =>
            {
                var tfs = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService<WorkItemStore>();
                var categoriesXml = this.SelectedWorkItemCategoryList.Save();
                foreach (var teamProject in this.SelectedTeamProjects)
                {
                    try
                    {
                        task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Importing work item category list in Team Project \"{0}\"", teamProject.Name));
                        var project = store.Projects[teamProject.Name];
                        WorkItemConfigurationItemImportExport.SetCategories(project, categoriesXml);
                    }
                    catch (Exception exc)
                    {
                        task.SetError(string.Format(CultureInfo.CurrentCulture, "An error occurred while importing the work item category list for Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while importing the work item category list", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete(task.IsError ? "Failed" : (task.IsWarning ? "Succeeded with warnings" : "Succeeded"));
                }
            };
            worker.RunWorkerAsync();
        }

        private bool CanAddWorkItemCategory(object argument)
        {
            return this.SelectedWorkItemCategoryList != null;
        }

        private void AddWorkItemCategory(object argument)
        {
            var category = new WorkItemCategory { Name = "New Category" };
            this.SelectedWorkItemCategoryList.Categories.Add(category);
            this.SelectedWorkItemCategory = category;
        }

        private bool CanRemoveSelectedWorkItemCategory(object argument)
        {
            return this.SelectedWorkItemCategoryList != null && this.SelectedWorkItemCategory != null;
        }

        private void RemoveSelectedWorkItemCategory(object argument)
        {
            this.SelectedWorkItemCategoryList.Categories.Remove(this.SelectedWorkItemCategory);
            this.SelectedWorkItemCategory = this.SelectedWorkItemCategoryList.Categories.FirstOrDefault();
        }

        #endregion

        #region Overrides

        protected override bool IsTfsSupported(TeamFoundationServerInfo server)
        {
            return server.MajorVersion >= TfsMajorVersion.V10;
        }

        #endregion

        #region Helper Methods

        private void PerformImport(Dictionary<TeamProjectInfo, List<WorkItemConfigurationItem>> teamProjectsWithCategories, ImportOptions options)
        {
            var numberOfSteps = teamProjectsWithCategories.Aggregate(0, (a, p) => a += p.Value.Count);
            var task = new ApplicationTask("Importing work item categories", numberOfSteps, true);
            PublishStatus(new StatusEventArgs(task));
            var worker = new BackgroundWorker();
            worker.DoWork += (sender, e) =>
            {
                var tfs = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService<WorkItemStore>();
                WorkItemConfigurationItemImportExport.Import(this.Logger, task, true, store, teamProjectsWithCategories, options);
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while importing work item categories", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete(task.IsError ? "Failed" : (task.IsWarning ? "Succeeded with warnings" : "Succeeded"));
                }
            };
            worker.RunWorkerAsync();
        }

        #endregion
    }
}


text:
module Data.Array.Repa.Repr.ForeignPtr
        ( F, Array (..)
        , fromForeignPtr, toForeignPtr
        , computeIntoS,   computeIntoP)
where
import Data.Array.Repa.Shape
import Data.Array.Repa.Base
import Data.Array.Repa.Eval.Load
import Data.Array.Repa.Eval.Target
import Data.Array.Repa.Repr.Delayed
import Foreign.Storable
import Foreign.ForeignPtr
import Foreign.Marshal.Alloc
import System.IO.Unsafe
import qualified Foreign.ForeignPtr.Unsafe      as Unsafe

-- | Arrays represented as foreign buffers in the C heap.
data F

-- | Read elements from a foreign buffer.
instance Storable a => Source F a where
 data Array F sh a
        = AForeignPtr !sh !Int !(ForeignPtr a)

 linearIndex (AForeignPtr _ len fptr) ix
  | ix < len
        = unsafePerformIO
        $ withForeignPtr fptr
        $ \ptr -> peekElemOff ptr ix

  | otherwise
  = error "Repa: foreign array index out of bounds"
 {-# INLINE linearIndex #-}

 unsafeLinearIndex (AForeignPtr _ _ fptr) ix
        = unsafePerformIO
        $ withForeignPtr fptr
        $ \ptr -> peekElemOff ptr ix
 {-# INLINE unsafeLinearIndex #-}

 extent (AForeignPtr sh _ _)
        = sh
 {-# INLINE extent #-}

 deepSeqArray (AForeignPtr sh len fptr) x
  = sh `deepSeq` len `seq` fptr `seq` x
 {-# INLINE deepSeqArray #-}

-- Load -----------------------------------------------------------------------
-- | Filling foreign buffers.
instance Storable e => Target F e where
 data MVec F e
  = FPVec !Int !(ForeignPtr e)

 newMVec n
  = do  let (proxy :: e) = undefined
        ptr              <- mallocBytes (sizeOf proxy * n)
        _                <- peek ptr  `asTypeOf` return proxy

        fptr             <- newForeignPtr finalizerFree ptr
        return           $ FPVec n fptr
 {-# INLINE newMVec #-}

 -- CAREFUL: Unwrapping the foreignPtr like this means we need to be careful
 -- to touch it after the last use, otherwise the finaliser might run too early.
 unsafeWriteMVec (FPVec _ fptr) !ix !x
  = pokeElemOff (Unsafe.unsafeForeignPtrToPtr fptr) ix x
 {-# INLINE unsafeWriteMVec #-}

 unsafeFreezeMVec !sh (FPVec len fptr)
  =     return  $ AForeignPtr sh len fptr
 {-# INLINE unsafeFreezeMVec #-}

 deepSeqMVec !(FPVec _ fptr) x
  = Unsafe.unsafeForeignPtrToPtr fptr `seq` x
 {-# INLINE deepSeqMVec #-}

 touchMVec (FPVec _ fptr)
  = touchForeignPtr fptr
 {-# INLINE touchMVec #-}

-- Conversions ----------------------------------------------------------------
-- | O(1). Wrap a `ForeignPtr` as an array.
fromForeignPtr
        :: Shape sh
        => sh -> ForeignPtr e -> Array F sh e
fromForeignPtr !sh !fptr
        = AForeignPtr sh (size sh) fptr
{-# INLINE fromForeignPtr #-}

-- | O(1). Unpack a `ForeignPtr` from an array.
toForeignPtr :: Array F sh e -> ForeignPtr e
toForeignPtr (AForeignPtr _ _ fptr)
        = fptr
{-# INLINE toForeignPtr #-}

-- | Compute an array sequentially and write the elements into a foreign
--   buffer without intermediate copying. If you want to copy a
--   pre-existing manifest array to a foreign buffer then `delay` it first.
computeIntoS
        :: (Load r1 sh e, Storable e)
        => ForeignPtr e -> Array r1 sh e -> IO ()
computeIntoS !fptr !arr
 = loadS arr (FPVec 0 fptr)
{-# INLINE computeIntoS #-}

-- | Compute an array in parallel and write the elements into a foreign
--   buffer without intermediate copying. If you want to copy a
--   pre-existing manifest array to a foreign buffer then `delay` it first.
computeIntoP
        :: (Load r1 sh e, Storable e)
        => ForeignPtr e -> Array r1 sh e -> IO ()
computeIntoP !fptr !arr
 = loadP arr (FPVec 0 fptr)
{-# INLINE computeIntoP #-}


text:
    curl --request GET \
         --url 'https://snippets.glot.io/snippets'

##### List snippets on page 5 with 3 snippets per page
    curl --request GET \
         --url 'https://snippets.glot.io/snippets?page=5&per_page=3'

##### List snippets by owner
    curl --request GET \
         --url 'https://snippets.glot.io/snippets?owner=anonymous'

##### List snippets by language
    curl --request GET \
         --url 'https://snippets.glot.io/snippets?language=erlang'

##### List snippets by owner by language
    curl --request GET \
         --url 'https://snippets.glot.io/snippets?owner=anonymous&language=erlang'

### List your snippets (requires api token)

##### List your snippets
    curl --request GET \
         --header 'Authorization: Token 0123456-789a-bcde-f012-3456789abcde' \
         --url 'https://snippets.glot.io/snippets'

##### List your snippets on page 5 with 3 snippets per page
    curl --request GET \
         --header 'Authorization: Token 0123456-789a-bcde-f012-3456789abcde' \
         --url 'https://snippets.glot.io/snippets?page=5&per_page=3'

##### List your snippets by language
    curl --request GET \
         --header 'Authorization: Token 0123456-789a-bcde-f012-3456789abcde' \
         --url 'https://snippets.glot.io/snippets?language=erlang'

### Example response data
    [
      {
        "url": "https://snippets.glot.io/snippets/e2txam1f3x",
        "id": "e2txam1f3x",
        "created": "2015-04-23T22:04:09Z",
        "modified": "2015-04-23T22:04:09Z",
        "language": "php",
        "title": "Hello world",
        "public": true,
        "owner": "anonymous",
        "files_hash": "7d87ee5fa673a6260abc705d56ac7b35b457f566"
      },
      {
        "url": "https://snippets.glot.io/snippets/e2txa5itxb",
        "id": "e2txa5itxb",
        "created": "2015-04-23T22:03:41Z",
        "modified": "2015-04-23T22:03:41Z",
        "language": "perl",
        "title": "Hello world",
        "public": true,
        "owner": "anonymous",
        "files_hash": "20f74f4277cafb12cd46e68008574dc92c5be35e"
      }
    ]

### Pagination
Information about pagination is provided by the [Link](http://tools.ietf.org/html/rfc5988) header in the response.
Pagination is controlled by the `page` and `per_page` query parameters. `page` must be >= 1, and `per_page` must
be <= 100. If the `per_page` parameter is not given it defaults to 100.

#### Example link header
    link: <https://snippets.glot.io/snippets?page=16&per_page=2>; rel="next",
          <https://snippets.glot.io/snippets?page=18&per_page=2>; rel="last",
          <https://snippets.glot.io/snippets?page=14&per_page=2>; rel="prev",
          <https://snippets.glot.io/snippets?page=1&per_page=2>; rel="first"


text:
#import <AsyncDisplayKit/ASLayoutController.h>
#import <AsyncDisplayKit/ASBaseDefines.h>

@interface ASAbstractLayoutController : NSObject <ASLayoutController>

- (void)setTuningParameters:(ASRangeTuningParameters)tuningParameters forRangeType:(ASLayoutRangeType)rangeType;

- (ASRangeTuningParameters)tuningParametersForRangeType:(ASLayoutRangeType)rangeType;

@property (nonatomic, assign) ASRangeTuningParameters tuningParameters ASDISPLAYNODE_DEPRECATED;

@end