text:
package org.apache.ambari.server.orm.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.metamodel.SingularAttribute;

import org.apache.ambari.server.actionmanager.ActionManager;
import org.apache.ambari.server.actionmanager.HostRoleStatus;
import org.apache.ambari.server.api.query.JpaPredicateVisitor;
import org.apache.ambari.server.api.query.JpaSortBuilder;
import org.apache.ambari.server.controller.internal.CalculatedStatus;
import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.utilities.PredicateHelper;
import org.apache.ambari.server.orm.RequiresSession;
import org.apache.ambari.server.orm.entities.HostRoleCommandEntity;
import org.apache.ambari.server.orm.entities.StageEntity;
import org.apache.ambari.server.orm.entities.StageEntityPK;
import org.apache.ambari.server.orm.entities.StageEntity_;
import org.apache.ambari.server.utils.StageUtils;
import org.eclipse.persistence.config.HintValues;
import org.eclipse.persistence.config.QueryHints;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;

@Singleton
public class StageDAO {

  /**
   * Mapping of valid status transitions that that are driven by manual input.
   */
  private static Map<HostRoleStatus, EnumSet<HostRoleStatus>> manualTransitionMap = new HashMap<>();

  static {
    manualTransitionMap.put(HostRoleStatus.HOLDING,
        EnumSet.of(HostRoleStatus.COMPLETED, HostRoleStatus.ABORTED));

    manualTransitionMap.put(HostRoleStatus.HOLDING_FAILED,
        EnumSet.of(HostRoleStatus.PENDING, HostRoleStatus.FAILED, HostRoleStatus.ABORTED));

    manualTransitionMap.put(HostRoleStatus.HOLDING_TIMEDOUT,
        EnumSet.of(HostRoleStatus.PENDING, HostRoleStatus.TIMEDOUT, HostRoleStatus.ABORTED));

    // todo: perhaps add a CANCELED status that just affects a stage and wont
    // abort the request
    // todo: so, if I scale 10 nodes and actually provision 5 and then later
    // decide I don't want those
    // todo: additional 5 nodes I can cancel them and the corresponding request
    // will have a status of COMPLETED
  }

  @Inject
  Provider<EntityManager> entityManagerProvider;

  @Inject
  DaoUtils daoUtils;

  @Inject
  HostRoleCommandDAO hostRoleCommandDao;

  @RequiresSession
  public StageEntity findByPK(StageEntityPK stageEntityPK) {
    return entityManagerProvider.get().find(StageEntity.class, stageEntityPK);
  }

  @RequiresSession
  public List<StageEntity> findAll() {
    return daoUtils.selectAll(entityManagerProvider.get(), StageEntity.class);
  }

  @RequiresSession
  public long getLastRequestId() {
    TypedQuery<Long> query = entityManagerProvider.get().createQuery("SELECT max(stage.requestId) FROM StageEntity stage", Long.class);
    Long result = daoUtils.selectSingle(query);
    if (result != null) {
      return result;
    } else {
      return 0;
    }
  }

  @RequiresSession
  public StageEntity findByActionId(String actionId) {
    long[] ids = StageUtils.getRequestStage(actionId);
    StageEntityPK pk = new StageEntityPK();
    pk.setRequestId(ids[0]);
    pk.setStageId(ids[1]);
    return findByPK(pk);
  }

  @RequiresSession
  public List<StageEntity> findByRequestId(long requestId) {
    TypedQuery<StageEntity> query = entityManagerProvider.get().createQuery("SELECT stage " +
        "FROM StageEntity stage " +
        "WHERE stage.requestId=?1 " +
        "ORDER BY stage.stageId", StageEntity.class);
    return daoUtils.selectList(query, requestId);
  }

  @RequiresSession
  public List<StageEntity> findByRequestIdAndCommandStatuses(Long requestId, Collection<HostRoleStatus> statuses) {
    TypedQuery<StageEntity> query = entityManagerProvider.get().createNamedQuery(
        "StageEntity.findByRequestIdAndCommandStatuses", StageEntity.class);

    query.setParameter("requestId", requestId);
    query.setParameter("statuses", statuses);
    return daoUtils.selectList(query);
  }

  /**
   * Finds the first stage matching any of the specified statuses for every
   * request. For example, to find the first {@link HostRoleStatus#IN_PROGRESS}
   * stage for every request, pass in
   * {@link HostRoleStatus#IN_PROGRESS_STATUSES}.
   *
   * @param statuses
   *          {@link HostRoleStatus}
   * @return the list of the first matching stage for the given statuses for
   *         every request.
   */
  @RequiresSession
  public List<StageEntity> findFirstStageByStatus(Collection<HostRoleStatus> statuses) {
    TypedQuery<Object[]> query = entityManagerProvider.get().createNamedQuery(
        "StageEntity.findFirstStageByStatus", Object[].class);

    query.setParameter("statuses", statuses);

    List<Object[]> results = daoUtils.selectList(query);
    List<StageEntity> stages = new ArrayList<>();

    for (Object[] result : results) {
      StageEntityPK stagePK = new StageEntityPK();
      stagePK.setRequestId((Long) result[0]);
      stagePK.setStageId((Long) result[1]);

      StageEntity stage = findByPK(stagePK);
      stages.add(stage);
    }

    return stages;
  }

  @RequiresSession
  public Map<Long, String> findRequestContext(List<Long> requestIds) {
    Map<Long, String> resultMap = new HashMap<>();
    if (requestIds != null && !requestIds.isEmpty()) {
      TypedQuery<StageEntity> query = entityManagerProvider.get()
        .createQuery("SELECT stage FROM StageEntity stage WHERE " +
          "stage.requestId IN (SELECT DISTINCT s.requestId FROM StageEntity s " +
          "WHERE s.requestId IN ?1)", StageEntity.class);
      List<StageEntity> result = daoUtils.selectList(query, requestIds);
      if (result != null && !result.isEmpty()) {
        for (StageEntity entity : result) {
          resultMap.put(entity.getRequestId(), entity.getRequestContext());
        }
      }
    }
    return resultMap;
  }

  @RequiresSession
  public String findRequestContext(long requestId) {
    TypedQuery<String> query = entityManagerProvider.get().createQuery(
      "SELECT stage.requestContext " + "FROM StageEntity stage " +
        "WHERE stage.requestId=?1", String.class);
    String result =  daoUtils.selectOne(query, requestId);
    if (result != null) {
      return result;
    }
    else {
      return ""; // Since it is defined as empty string in the StageEntity
    }
  }

  @Transactional
  public void create(StageEntity stageEntity) {
    entityManagerProvider.get().persist(stageEntity);
  }

  @Transactional
  public StageEntity merge(StageEntity stageEntity) {
    return entityManagerProvider.get().merge(stageEntity);
  }

  @Transactional
  public void remove(StageEntity stageEntity) {
    entityManagerProvider.get().remove(merge(stageEntity));
  }

  @Transactional
  public void removeByPK(StageEntityPK stageEntityPK) {
    remove(findByPK(stageEntityPK));
  }

  /**
   * Finds all {@link org.apache.ambari.server.orm.entities.StageEntity} that match the provided
   * {@link org.apache.ambari.server.controller.spi.Predicate}. This method will make JPA do the heavy lifting
   * of providing a slice of the result set.
   *
   * @param request
   * @return
   */
  @RequiresSession
  public List<StageEntity> findAll(Request request, Predicate predicate) {
    EntityManager entityManager = entityManagerProvider.get();

    // convert the Ambari predicate into a JPA predicate
    StagePredicateVisitor visitor = new StagePredicateVisitor();
    PredicateHelper.visit(predicate, visitor);

    CriteriaQuery<StageEntity> query = visitor.getCriteriaQuery();
    javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate();

    if (jpaPredicate != null) {
      query.where(jpaPredicate);
    }

    // sorting
    JpaSortBuilder<StageEntity> sortBuilder = new JpaSortBuilder<>();
    List<Order> sortOrders = sortBuilder.buildSortOrders(request.getSortRequest(), visitor);
    query.orderBy(sortOrders);

    TypedQuery<StageEntity> typedQuery = entityManager.createQuery(query);

    // !!! https://bugs.eclipse.org/bugs/show_bug.cgi?id=398067
    // ensure that an associated entity with a JOIN is not stale; this causes
    // the associated StageEntity to be stale
    typedQuery.setHint(QueryHints.REFRESH, HintValues.TRUE);

    return daoUtils.selectList(typedQuery);
  }

  /**
   * Update the given stage entity with the desired status.
   *
   * @param stage
   *          the stage entity to update
   * @param desiredStatus
   *          the desired stage status
   * @param actionManager
   *          the action manager
   *
   * @throws java.lang.IllegalArgumentException
   *           if the transition to the desired status is not a legal transition
   */
  @Transactional
  public void updateStageStatus(StageEntity stage, HostRoleStatus desiredStatus,
      ActionManager actionManager) {
    Collection<HostRoleCommandEntity> tasks = stage.getHostRoleCommands();

    HostRoleStatus currentStatus = CalculatedStatus.statusFromTaskEntities(tasks,
        stage.isSkippable()).getStatus();

    if (!isValidManualTransition(currentStatus, desiredStatus)) {
      throw new IllegalArgumentException(
          "Can not transition a stage from " + currentStatus + " to " + desiredStatus);
    }
    if (desiredStatus == HostRoleStatus.ABORTED) {
      actionManager.cancelRequest(stage.getRequestId(), "User aborted.");
    } else {
      List <HostRoleCommandEntity> hrcWithChangedStatus = new ArrayList<>();
      for (HostRoleCommandEntity hostRoleCommand : tasks) {
        HostRoleStatus hostRoleStatus = hostRoleCommand.getStatus();
        if (hostRoleStatus.equals(currentStatus)) {
          hrcWithChangedStatus.add(hostRoleCommand);
          hostRoleCommand.setStatus(desiredStatus);

          if (desiredStatus == HostRoleStatus.PENDING) {
            hostRoleCommand.setStartTime(-1L);
          }
          hostRoleCommandDao.merge(hostRoleCommand);
        }
      }
    }
  }

  /**
   *
   * @param stageEntityPK  {@link StageEntityPK}
   * @param status {@link HostRoleStatus}
   * @param displayStatus {@link HostRoleStatus}
   */
  @Transactional
  public void updateStatus(StageEntityPK stageEntityPK, HostRoleStatus status, HostRoleStatus displayStatus) {
    StageEntity stageEntity = findByPK(stageEntityPK);
    stageEntity.setStatus(status);
    stageEntity.setDisplayStatus(displayStatus);
    merge(stageEntity);
  }

  /**
   * Determine whether or not it is valid to transition from this stage status
   * to the given status.
   *
   * @param status
   *          the stage status being transitioned to
   *
   * @return true if it is valid to transition to the given stage status
   */
  private static boolean isValidManualTransition(HostRoleStatus status,
      HostRoleStatus desiredStatus) {
    EnumSet<HostRoleStatus> stageStatusSet = manualTransitionMap.get(status);
    return stageStatusSet != null && stageStatusSet.contains(desiredStatus);
  }

  /**
   * The {@link org.apache.ambari.server.orm.dao.StageDAO.StagePredicateVisitor} is used to convert an Ambari
   * {@link org.apache.ambari.server.controller.spi.Predicate} into a JPA {@link javax.persistence.criteria.Predicate}.
   */
  private final class StagePredicateVisitor extends
      JpaPredicateVisitor<StageEntity> {

    /**
     * Constructor.
     *
     */
    public StagePredicateVisitor() {
      super(entityManagerProvider.get(), StageEntity.class);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Class<StageEntity> getEntityClass() {
      return StageEntity.class;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<? extends SingularAttribute<?, ?>> getPredicateMapping(
        String propertyId) {
      return StageEntity_.getPredicateMapping().get(propertyId);
    }
  }
}


text:
When visualizing time series data, analyzing temporal patterns, or working with time in general, the irregularities of conventional time units quickly become apparent. In the [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar), for example, most months have 31 days but some have 28, 29 or 30; most years have 365 days but [leap years](https://en.wikipedia.org/wiki/Leap_year) have 366; and with [daylight saving](https://en.wikipedia.org/wiki/Daylight_saving_time), most days have 24 hours but some have 23 or 25. Adding to complexity, daylight saving conventions vary around the world.

As a result of these temporal peculiarities, it can be difficult to perform seemingly-trivial tasks. For example, if you want to compute the number of days that have passed between two dates, you can't simply subtract and divide by 24 hours (86,400,000 ms):

```js
var start = new Date(2015, 02, 01), // Sun Mar 01 2015 00:00:00 GMT-0800 (PST)
    end = new Date(2015, 03, 01); // Wed Apr 01 2015 00:00:00 GMT-0700 (PDT)
(end - start) / 864e5; // 30.958333333333332, oops!
```

You can, however, use [timeDay](#timeDay).[count](#interval_count):

```js
d3.timeDay.count(start, end); // 31
```

The [day](#day) [interval](#api-reference) is one of several provided by d3-time. Each interval represents a conventional unit of time—[hours](#timeHour), [weeks](#timeWeek), [months](#timeMonth), *etc.*—and has methods to calculate boundary dates. For example, [timeDay](#timeDay) computes midnight (typically 12:00 AM local time) of the corresponding day. In addition to [rounding](#interval_round) and [counting](#interval_count), intervals can also be used to generate arrays of boundary dates. For example, to compute each Sunday in the current month:

```js
var now = new Date;
d3.timeWeek.range(d3.timeMonth.floor(now), d3.timeMonth.ceil(now));
// [Sun Jun 07 2015 00:00:00 GMT-0700 (PDT),
//  Sun Jun 14 2015 00:00:00 GMT-0700 (PDT),
//  Sun Jun 21 2015 00:00:00 GMT-0700 (PDT),
//  Sun Jun 28 2015 00:00:00 GMT-0700 (PDT)]
```

The d3-time module does not implement its own calendaring system; it merely implements a convenient API for calendar math on top of ECMAScript [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date). Thus, it ignores leap seconds and can only work with the local time zone and [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) (UTC).

This module is used by D3's time scales to generate sensible ticks, by D3's time format, and can also be used directly to do things like [calendar layouts](http://bl.ocks.org/mbostock/4063318).

## Installing

If you use NPM, `npm install d3-time`. Otherwise, download the [latest release](https://github.com/d3/d3-time/releases/latest). You can also load directly from [d3js.org](https://d3js.org), either as a [standalone library](https://d3js.org/d3-time.v0.3.min.js) or as part of [D3 4.0](https://github.com/d3/d3). AMD, CommonJS, and vanilla environments are supported. In vanilla, a `d3` global is exported:

```html
<script src="https://d3js.org/d3-time.v0.3.min.js"></script>
<script>

var day = d3.timeDay(new Date);

</script>
```

[Try d3-time in your browser.](https://tonicdev.com/npm/d3-time)

## API Reference

# interval(date)

Alias for [*interval*.floor](#interval_floor). For example, [timeYear](#timeYear)(*date*) and timeYear.floor(*date*) are equivalent.

# interval.floor(date)

Returns a new date representing the latest interval boundary date before or equal to *date*. For example, [timeDay](#timeDay).floor(*date*) typically returns 12:00 AM local time on the given *date*.

This method is idempotent: if the specified *date* is already floored to the current interval, a new date with an identical time is returned. Furthermore, the returned date is the minimum expressible value of the associated interval, such that *interval*.floor(*interval*.floor(*date*) - 1) returns the preceeding interval boundary date.

Note that the `==` and `===` operators do not compare by value with [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) objects, and thus you cannot use them to tell whether the specified *date* has already been floored. Instead, coerce to a number and then compare:

```js
// Returns true if the specified date is a day boundary.
function isDay(date) {
  return +d3.timeDay.floor(date) === +date;
}
```

This is more reliable than testing whether the time is 12:00 AM, as in some time zones midnight may not exist due to daylight saving.

# interval.round(date)

Returns a new date representing the closest interval boundary date to *date*. For example, [timeDay](#timeDay).round(*date*) typically returns 12:00 AM local time on the given *date* if it is on or before noon, and 12:00 AM of the following day if it is after noon.

This method is idempotent: if the specified *date* is already rounded to the current interval, a new date with an identical time is returned.

# interval.ceil(date)

Returns a new date representing the earliest interval boundary date after or equal to *date*. For example, [timeDay](#timeDay).ceil(*date*) typically returns 12:00 AM local time on the date following the given *date*.

This method is idempotent: if the specified *date* is already ceilinged to the current interval, a new date with an identical time is returned. Furthermore, the returned date is the maximum expressible value of the associated interval, such that *interval*.ceil(*interval*.ceil(*date*) + 1) returns the following interval boundary date.

# interval.offset(date[, step])

Returns a new date equal to *date* plus *step* intervals. If *step* is not specified it defaults to 1. If *step* is negative, then the returned date will be before the specified *date*; if *step* is zero, then a copy of the specified *date* is returned; if *step* is not an integer, it is [floored](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor). This method does not round the specified *date* to the interval. For example, if *date* is today at 5:34 PM, then [timeDay](#timeDay).offset(*date*, 1) returns 5:34 PM tomorrow (even if daylight saving changes!).

# interval.range(start, stop[, step])

Returns every an array of dates representing every interval boundary after or equal to *start* (inclusive) and before *stop* (exclusive). If *step* is specified, then every *step*th boundary will be returned; for example, for the [timeDay](#timeDay) interval a *step* of 2 will return every other day. If *step* is not an integer, it is [floored](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor).

The first date in the returned array is the earliest boundary after or equal to *start*; subsequent dates are [offset](#interval_offset) by *step* intervals and [floored](#interval_floor). Thus, two overlapping ranges may be consistent. For example, this range contains odd days:

```js
d3.timeDay.range(new Date(2015, 0, 1), new Date(2015, 0, 7), 2);
// [Thu Jan 01 2015 00:00:00 GMT-0800 (PST),
//  Sat Jan 03 2015 00:00:00 GMT-0800 (PST),
//  Mon Jan 05 2015 00:00:00 GMT-0800 (PST)]
```

While this contains even days:

```js
d3.timeDay.range(new Date(2015, 0, 2), new Date(2015, 0, 8), 2);
// [Fri Jan 02 2015 00:00:00 GMT-0800 (PST),
//  Sun Jan 04 2015 00:00:00 GMT-0800 (PST),
//  Tue Jan 06 2015 00:00:00 GMT-0800 (PST)]
```

To make ranges consistent when a *step* is specified, use [*interval*.every](#interval_every) instead.

# interval.filter(test)

Returns a new interval that is a filtered subset of this interval using the specified *test* function. The *test* function is passed a date and should return true if and only if the specified date should be considered part of the interval. For example, to create an interval that returns the 1st, 11th, 21th and 31th (if it exists) of each month:

```js
var i = d3.timeDay.filter(function(d) { return (d.getDate() - 1) % 10 === 0; });
```

The returned filtered interval does not support [count](#interval_count). See also [*interval*.every](#interval_every).

# interval.every(step)

Returns a [filtered](#interval_filter) view of this interval representing every *step*th date. The meaning of *step* is dependent on this interval's parent interval as defined by the field function. For example, [timeMinute](#timeMinute).every(15) returns an interval representing every fifteen minutes, starting on the hour: :00, :15, :30, :45, etc. Note that for some intervals, the resulting dates may not be uniformly-spaced; [timeDay](#timeDay)'s parent interval is [timeMonth](#timeMonth), and thus the interval number resets at the start of each month. If *step* is not valid, returns null. If *step* is one, returns this interval.

This method can be used in conjunction with [*interval*.range](#interval_range) to ensure that two overlapping ranges are consistent. For example, this range contains odd days:

```js
d3.timeDay.every(2).range(new Date(2015, 0, 1), new Date(2015, 0, 7));
// [Thu Jan 01 2015 00:00:00 GMT-0800 (PST),
//  Sat Jan 03 2015 00:00:00 GMT-0800 (PST),
//  Mon Jan 05 2015 00:00:00 GMT-0800 (PST)]
```

As does this one:

```js
d3.timeDay.every(2).range(new Date(2015, 0, 2), new Date(2015, 0, 8));
// [Sat Jan 03 2015 00:00:00 GMT-0800 (PST),
//  Mon Jan 05 2015 00:00:00 GMT-0800 (PST),
//  Wed Jan 07 2015 00:00:00 GMT-0800 (PST)]
```

See also [*interval*.filter](#interval_filter).

# interval.count(start, end)

Returns the number of interval boundaries after *start* (exclusive) and before or equal to *end* (inclusive). Note that this behavior is slightly different than [*interval*.range](#interval_range) because its purpose is to return the zero-based number of the specified *end* date relative to the specified *start* date. For example, to compute the current zero-based day-of-year number:

```js
var now = new Date;
d3.timeDay.count(d3.timeYear(now), now); // 177
```

Likewise, to compute the current zero-based week-of-year number for weeks that start on Sunday:

```js
d3.timeSunday.count(d3.timeYear(now), now); // 25
```

# d3.timeInterval(floor, offset[, count[, field]])

Constructs a new custom interval given the specified *floor* and *offset* functions and an optional *count* function.

The *floor* function takes a single date as an argument and rounds it down to the nearest interval boundary.

The *offset* function takes a date and an integer step as arguments and advances the specified date by the specified number of boundaries; the step may be positive, negative or zero.

The optional *count* function takes a start date and an end date, already floored to the current interval, and returns the number of boundaries between the start (exclusive) and end (inclusive). If a *count* function is not specified, the returned interval does not expose [count](#interval_count) or [every](#interval_every) methods. Note: due to an internal optimization, the specified *count* function must not invoke *interval*.count on other time intervals.

The optional *field* function takes a date, already floored to the current interval, and returns the field value of the specified date, corresponding to the number of boundaries between this date (exclusive) and the latest previous parent boundary. For example, for the [timeDay](#timeDay) interval, this returns the number of days since the start of the month. If a *field* function is not specified, it defaults to counting the number of interval boundaries since the UNIX epoch of January 1, 1970 UTC. The *field* function defines the behavior of [*interval*.every](#interval_every).

### Intervals

The following intervals are provided:

# d3.timeMillisecond

# d3.utcMillisecond

Milliseconds; the shortest available time unit.

# d3.timeSecond

# d3.utcSecond

Seconds (e.g., 01:23:45.0000 AM); 1,000 milliseconds.

# d3.timeMinute

# d3.utcMinute

Minutes (e.g., 01:02:00 AM); 60 seconds. Note that ECMAScript [ignores leap seconds](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.1).

# d3.timeHour

# d3.utcHour

Hours (e.g., 01:00 AM); 60 minutes. Note that advancing time by one hour in local time can return the same hour or skip an hour due to daylight saving.

# d3.timeDay

# d3.utcDay

Days (e.g., February 7, 2012 at 12:00 AM); typically 24 hours. Days in local time may range from 23 to 25 hours due to daylight saving.

# d3.timeWeek

# d3.utcWeek

Alias for [sunday](#sunday); 7 days and typically 168 hours. Weeks in local time may range from 167 to 169 hours due on daylight saving.

# d3.timeSunday

# d3.utcSunday

Sunday-based weeks (e.g., February 5, 2012 at 12:00 AM).

# d3.timeMonday

# d3.utcMonday

Monday-based weeks (e.g., February 6, 2012 at 12:00 AM).

# d3.timeTuesday

# d3.utcTuesday

Tuesday-based weeks (e.g., February 7, 2012 at 12:00 AM).

# d3.timeWednesday

# d3.utcWednesday

Wednesday-based weeks (e.g., February 8, 2012 at 12:00 AM).

# d3.timeThursday

# d3.utcThursday

Thursday-based weeks (e.g., February 9, 2012 at 12:00 AM).

# d3.timeFriday

# d3.utcFriday

Friday-based weeks (e.g., February 10, 2012 at 12:00 AM).

# d3.timeSaturday

# d3.utcSaturday

Saturday-based weeks (e.g., February 11, 2012 at 12:00 AM).

# d3.timeMonth

# d3.utcMonth

Months (e.g., February 1, 2012 at 12:00 AM); ranges from 28 to 31 days.

# d3.timeYear

# d3.utcYear

Years (e.g., January 1, 2012 at 12:00 AM); ranges from 365 to 366 days.

### Ranges

For convenience, aliases for [*interval*.range](#interval_range) are also provided as plural forms of the corresponding interval.

# d3.timeMilliseconds(start, stop[, step])

# d3.utcMilliseconds(start, stop[, step])

Aliases for [timeMillisecond](#timeMillisecond).[range](#interval_range) and [utcMillisecond](#timeMillisecond).[range](#interval_range).

# d3.timeSeconds(start, stop[, step])

# d3.utcSeconds(start, stop[, step])

Aliases for [timeSecond](#timeSecond).[range](#interval_range) and [utcSecond](#timeSecond).[range](#interval_range).

# d3.timeMinutes(start, stop[, step])

# d3.utcMinutes(start, stop[, step])

Aliases for [timeMinute](#timeMinute).[range](#interval_range) and [utcMinute](#timeMinute).[range](#interval_range).

# d3.timeHours(start, stop[, step])

# d3.utcHours(start, stop[, step])

Aliases for [timeHour](#timeHour).[range](#interval_range) and [utcHour](#timeHour).[range](#interval_range).

# d3.timeDays(start, stop[, step])

# d3.utcDays(start, stop[, step])

Aliases for [timeTimeDay](#timeTimeDay).[range](#interval_range) and [utcDay](#timeTimeDay).[range](#interval_range).

# d3.timeWeeks(start, stop[, step])

# d3.utcWeeks(start, stop[, step])

Aliases for [timeWeek](#timeWeek).[range](#interval_range) and [utcWeek](#timeWeek).[range](#interval_range).

# d3.timeSundays(start, stop[, step])

# d3.utcSundays(start, stop[, step])

Aliases for [timeSunday](#timeSunday).[range](#interval_range) and [utcSunday](#timeSunday).[range](#interval_range).

# d3.timeMondays(start, stop[, step])

# d3.utcMondays(start, stop[, step])

Aliases for [timeMonday](#timeMonday).[range](#interval_range) and [utcMonday](#timeMonday).[range](#interval_range).

# d3.timeTuesdays(start, stop[, step])

# d3.utcTuesdays(start, stop[, step])

Aliases for [timeTuesday](#timeTuesday).[range](#interval_range) and [utcTuesday](#timeTuesday).[range](#interval_range).

# d3.timeWednesdays(start, stop[, step])

# d3.utcWednesdays(start, stop[, step])

Aliases for [timeWednesday](#timeWednesday).[range](#interval_range) and [utcWednesday](#timeWednesday).[range](#interval_range).

# d3.timeThursdays(start, stop[, step])

# d3.utcThursdays(start, stop[, step])

Aliases for [timeThursday](#timeThursday).[range](#interval_range) and [utcThursday](#timeThursday).[range](#interval_range).

# d3.timeFridays(start, stop[, step])

# d3.utcFridays(start, stop[, step])

Aliases for [timeFriday](#timeFriday).[range](#interval_range) and [utcFriday](#timeFriday).[range](#interval_range).

# d3.timeSaturdays(start, stop[, step])

# d3.utcSaturdays(start, stop[, step])

Aliases for [timeSaturday](#timeSaturday).[range](#interval_range) and [utcSaturday](#timeSaturday).[range](#interval_range).

# d3.timeMonths(start, stop[, step])

# d3.utcMonths(start, stop[, step])

Aliases for [timeMonth](#timeMonth).[range](#interval_range) and [utcMonth](#timeMonth).[range](#interval_range).

# d3.timeYears(start, stop[, step])

# d3.utcYears(start, stop[, step])

Aliases for [timeYear](#timeYear).[range](#interval_range) and [utcYear](#timeYear).[range](#interval_range).

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    >

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/card_view"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/station_city"
                android:layout_alignParentLeft="true"
                android:textSize="12sp"
                />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/station_country"
                android:layout_below="@+id/station_city"
                android:textSize="20sp"
                />
            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:id="@+id/btn_info"
                android:background="@drawable/attention"
                android:layout_alignParentRight="true"/>
            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentRight="true"
                android:background="@drawable/bus"
                android:id="@+id/btn_bus"
                android:layout_below="@+id/btn_info"/>
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>


text:
using StayWell.ServiceDefinitions.Content.Objects;
using StayWell.ServiceDefinitions.Mapping.Objects;
using StayWell.WebExample.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;

namespace StayWell.WebExample.App_Code.Mappers
{
    public class MappingToGroupedContentModelMapper : IMapToNew<List<ServiceLineMappingResponse>, List<GroupedContentModel>>
    {
        public List<GroupedContentModel> Map(List<ServiceLineMappingResponse> source)
        {
            List<GroupedContentModel> groupedResponse = new List<GroupedContentModel>();
            var groupedMapping = source.GroupBy(c => c.MappingType);
            foreach (var group in groupedMapping)
            {
                TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;

                GroupedContentModel model = new GroupedContentModel();
                model.Title = "Client Mapping Demo: " + textInfo.ToTitleCase(group.Key);
                model.Slug = group.Key;

                //Add only a distinct set of mapped services.  It is possible to get multiple hits depending on how
                //the mapping was originally done.

                List<ServiceLineMappingResponse> subMappings = group.GroupBy(c => c.Name).Select(grp => grp.First()).ToList();
                List<ContentReferenceModel> referenceModels = new List<ContentReferenceModel>();
                foreach (ServiceLineMappingResponse response in subMappings)
                {
                    referenceModels.Add(new ContentReferenceModel
                    {
                        Title = response.Name,
                        Uri = response.Uri,
                        Type = response.MappingType
                    });
                }
                model.Items = referenceModels;
                groupedResponse.Add(model);
            }

            return groupedResponse;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.premnirmal.Magnet.app">

  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

  <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme">
    <activity
        android:name="com.premnirmal.Magnet.app.ParanormalActivity"
        android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
    <service android:name="com.premnirmal.Magnet.app.MyService"/>
  </application>

</manifest>


text:
package spring.general.dto;

/**
 * @author Oleg Cherednik
 * @since 05.07.2016
 */
public enum UserType {
    INTERNAL,
    EXTERNAL
}


text:
<?php
/**
 *
 * Part of the QCubed PHP framework.
 *
 * @license MIT
 *
 */

namespace QCubed\Query\Condition;

/**
 * Class LessThan
 * @package QCubed\Query\Condition
 * @was QQConditionLessThan
 */
class LessThan extends ComparisonBase
{
    protected $strOperator = ' < ';
}


text:
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
  set(SDL2_ARCH_64 TRUE)
  set(SDL2_PROCESSOR_ARCH "x64")
else()
  set(SDL2_ARCH_64 FALSE)
  set(SDL2_PROCESSOR_ARCH "x86")
endif(CMAKE_SIZEOF_VOID_P EQUAL 8)

SET(SDL2_SEARCH_PATHS
	~/Library/Frameworks
	/Library/Frameworks
	/usr/local
	/usr
	/sw # Fink
	/opt/local # DarwinPorts
	/opt/csw # Blastwave
	/opt
)

if(NOT SDL2_MIXER_INCLUDE_DIR AND SDL2MIXER_INCLUDE_DIR)
  set(SDL2_MIXER_INCLUDE_DIR ${SDL2MIXER_INCLUDE_DIR} CACHE PATH "directory cache
entry initialized from old variable name")
endif()
find_path(SDL2_MIXER_INCLUDE_DIR SDL_mixer.h
  HINTS
    ENV SDL2MIXERDIR
    ENV SDL2DIR
  PATH_SUFFIXES include include/SDL2
  PATHS ${SDL2_SEARCH_PATHS}
)

if(NOT SDL2_MIXER_LIBRARY AND SDL2MIXER_LIBRARY)
  set(SDL2_MIXER_LIBRARY ${SDL2MIXER_LIBRARY} CACHE FILEPATH "file cache entry
initialized from old variable name")
endif()
find_library(SDL2_MIXER_LIBRARY
  NAMES SDL2_mixer
  HINTS
    ENV SDL2MIXERDIR
    ENV SDL2DIR
  PATH_SUFFIXES lib64 lib lib/${SDL2_PROCESSOR_ARCH}
  PATHS ${SDL2_SEARCH_PATHS}
)

if(SDL2_MIXER_INCLUDE_DIR AND EXISTS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h")
  file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h" SDL2_MIXER_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL_MIXER_MAJOR_VERSION[ \t]+[0-9]+$")
  file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h" SDL2_MIXER_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL_MIXER_MINOR_VERSION[ \t]+[0-9]+$")
  file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h" SDL2_MIXER_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL_MIXER_PATCHLEVEL[ \t]+[0-9]+$")
  string(REGEX REPLACE "^#define[ \t]+SDL_MIXER_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_MAJOR "${SDL2_MIXER_VERSION_MAJOR_LINE}")
  string(REGEX REPLACE "^#define[ \t]+SDL_MIXER_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_MINOR "${SDL2_MIXER_VERSION_MINOR_LINE}")
  string(REGEX REPLACE "^#define[ \t]+SDL_MIXER_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_PATCH "${SDL2_MIXER_VERSION_PATCH_LINE}")
  set(SDL2_MIXER_VERSION_STRING ${SDL2_MIXER_VERSION_MAJOR}.${SDL2_MIXER_VERSION_MINOR}.${SDL2_MIXER_VERSION_PATCH})
  unset(SDL2_MIXER_VERSION_MAJOR_LINE)
  unset(SDL2_MIXER_VERSION_MINOR_LINE)
  unset(SDL2_MIXER_VERSION_PATCH_LINE)
  unset(SDL2_MIXER_VERSION_MAJOR)
  unset(SDL2_MIXER_VERSION_MINOR)
  unset(SDL2_MIXER_VERSION_PATCH)
endif()

set(SDL2_MIXER_LIBRARIES ${SDL2_MIXER_LIBRARY})
set(SDL2_MIXER_INCLUDE_DIRS ${SDL2_MIXER_INCLUDE_DIR})

include(FindPackageHandleStandardArgs)

FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_mixer
                                  REQUIRED_VARS SDL2_MIXER_LIBRARIES SDL2_MIXER_INCLUDE_DIRS
                                  VERSION_VAR SDL2_MIXER_VERSION_STRING)

# for backward compatiblity
set(SDL2MIXER_LIBRARY ${SDL2_MIXER_LIBRARIES})
set(SDL2MIXER_INCLUDE_DIR ${SDL2_MIXER_INCLUDE_DIRS})
set(SDL2MIXER_FOUND ${SDL2_MIXER_FOUND})

mark_as_advanced(SDL2_MIXER_LIBRARY SDL2_MIXER_INCLUDE_DIR)


text:
"""(disabled by default) support for testing pytest and pytest plugins."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import codecs
import gc
import os
import platform
import re
import subprocess
import sys
import time
import traceback
from fnmatch import fnmatch
from weakref import WeakKeyDictionary

import py
import six

import pytest
from _pytest._code import Source
from _pytest.assertion.rewrite import AssertionRewritingHook
from _pytest.capture import MultiCapture
from _pytest.capture import SysCapture
from _pytest.compat import safe_str
from _pytest.main import EXIT_INTERRUPTED
from _pytest.main import EXIT_OK
from _pytest.main import Session
from _pytest.pathlib import Path

IGNORE_PAM = [  # filenames added when obtaining details about the current user
    u"/var/lib/sss/mc/passwd"
]

def pytest_addoption(parser):
    parser.addoption(
        "--lsof",
        action="store_true",
        dest="lsof",
        default=False,
        help="run FD checks if lsof is available",
    )

    parser.addoption(
        "--runpytest",
        default="inprocess",
        dest="runpytest",
        choices=("inprocess", "subprocess"),
        help=(
            "run pytest sub runs in tests using an 'inprocess' "
            "or 'subprocess' (python -m main) method"
        ),
    )

    parser.addini(
        "pytester_example_dir", help="directory to take the pytester example files from"
    )

def pytest_configure(config):
    if config.getvalue("lsof"):
        checker = LsofFdLeakChecker()
        if checker.matching_platform():
            config.pluginmanager.register(checker)

def raise_on_kwargs(kwargs):
    if kwargs:
        raise TypeError("Unexpected arguments: {}".format(", ".join(sorted(kwargs))))

class LsofFdLeakChecker(object):
    def get_open_files(self):
        out = self._exec_lsof()
        open_files = self._parse_lsof_output(out)
        return open_files

    def _exec_lsof(self):
        pid = os.getpid()
        return py.process.cmdexec("lsof -Ffn0 -p %d" % pid)

    def _parse_lsof_output(self, out):
        def isopen(line):
            return line.startswith("f") and (
                "deleted" not in line
                and "mem" not in line
                and "txt" not in line
                and "cwd" not in line
            )

        open_files = []

        for line in out.split("\n"):
            if isopen(line):
                fields = line.split("\0")
                fd = fields[0][1:]
                filename = fields[1][1:]
                if filename in IGNORE_PAM:
                    continue
                if filename.startswith("/"):
                    open_files.append((fd, filename))

        return open_files

    def matching_platform(self):
        try:
            py.process.cmdexec("lsof -v")
        except (py.process.cmdexec.Error, UnicodeDecodeError):
            # cmdexec may raise UnicodeDecodeError on Windows systems with
            # locale other than English:
            # https://bitbucket.org/pytest-dev/py/issues/66
            return False
        else:
            return True

    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
    def pytest_runtest_protocol(self, item):
        lines1 = self.get_open_files()
        yield
        if hasattr(sys, "pypy_version_info"):
            gc.collect()
        lines2 = self.get_open_files()

        new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}
        leaked_files = [t for t in lines2 if t[0] in new_fds]
        if leaked_files:
            error = []
            error.append("***** %s FD leakage detected" % len(leaked_files))
            error.extend([str(f) for f in leaked_files])
            error.append("*** Before:")
            error.extend([str(f) for f in lines1])
            error.append("*** After:")
            error.extend([str(f) for f in lines2])
            error.append(error[0])
            error.append("*** function %s:%s: %s " % item.location)
            error.append("See issue #2366")
            item.warn(pytest.PytestWarning("\n".join(error)))

# XXX copied from execnet's conftest.py - needs to be merged
winpymap = {
    "python2.7": r"C:\Python27\python.exe",
    "python3.4": r"C:\Python34\python.exe",
    "python3.5": r"C:\Python35\python.exe",
    "python3.6": r"C:\Python36\python.exe",
}

def getexecutable(name, cache={}):
    try:
        return cache[name]
    except KeyError:
        executable = py.path.local.sysfind(name)
        if executable:
            import subprocess

            popen = subprocess.Popen(
                [str(executable), "--version"],
                universal_newlines=True,
                stderr=subprocess.PIPE,
            )
            out, err = popen.communicate()
            if name == "jython":
                if not err or "2.5" not in err:
                    executable = None
                if "2.5.2" in err:
                    executable = None  # http://bugs.jython.org/issue1790
            elif popen.returncode != 0:
                # handle pyenv's 127
                executable = None
        cache[name] = executable
        return executable

@pytest.fixture(params=["python2.7", "python3.4", "pypy", "pypy3"])
def anypython(request):
    name = request.param
    executable = getexecutable(name)
    if executable is None:
        if sys.platform == "win32":
            executable = winpymap.get(name, None)
            if executable:
                executable = py.path.local(executable)
                if executable.check():
                    return executable
        pytest.skip("no suitable %s found" % (name,))
    return executable

# used at least by pytest-xdist plugin

@pytest.fixture
def _pytest(request):
    """Return a helper which offers a gethookrecorder(hook) method which
    returns a HookRecorder instance which helps to make assertions about called
    hooks.

    """
    return PytestArg(request)

class PytestArg(object):
    def __init__(self, request):
        self.request = request

    def gethookrecorder(self, hook):
        hookrecorder = HookRecorder(hook._pm)
        self.request.addfinalizer(hookrecorder.finish_recording)
        return hookrecorder

def get_public_names(values):
    """Only return names from iterator values without a leading underscore."""
    return [x for x in values if x[0] != "_"]

class ParsedCall(object):
    def __init__(self, name, kwargs):
        self.__dict__.update(kwargs)
        self._name = name

    def __repr__(self):
        d = self.__dict__.copy()
        del d["_name"]
        return "<ParsedCall %r(**%r)>" % (self._name, d)

class HookRecorder(object):
    """Record all hooks called in a plugin manager.

    This wraps all the hook calls in the plugin manager, recording each call
    before propagating the normal calls.

    """

    def __init__(self, pluginmanager):
        self._pluginmanager = pluginmanager
        self.calls = []

        def before(hook_name, hook_impls, kwargs):
            self.calls.append(ParsedCall(hook_name, kwargs))

        def after(outcome, hook_name, hook_impls, kwargs):
            pass

        self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after)

    def finish_recording(self):
        self._undo_wrapping()

    def getcalls(self, names):
        if isinstance(names, str):
            names = names.split()
        return [call for call in self.calls if call._name in names]

    def assert_contains(self, entries):
        __tracebackhide__ = True
        i = 0
        entries = list(entries)
        backlocals = sys._getframe(1).f_locals
        while entries:
            name, check = entries.pop(0)
            for ind, call in enumerate(self.calls[i:]):
                if call._name == name:
                    print("NAMEMATCH", name, call)
                    if eval(check, backlocals, call.__dict__):
                        print("CHECKERMATCH", repr(check), "->", call)
                    else:
                        print("NOCHECKERMATCH", repr(check), "-", call)
                        continue
                    i += ind + 1
                    break
                print("NONAMEMATCH", name, "with", call)
            else:
                pytest.fail("could not find %r check %r" % (name, check))

    def popcall(self, name):
        __tracebackhide__ = True
        for i, call in enumerate(self.calls):
            if call._name == name:
                del self.calls[i]
                return call
        lines = ["could not find call %r, in:" % (name,)]
        lines.extend(["  %s" % x for x in self.calls])
        pytest.fail("\n".join(lines))

    def getcall(self, name):
        values = self.getcalls(name)
        assert len(values) == 1, (name, values)
        return values[0]

    # functionality for test reports

    def getreports(self, names="pytest_runtest_logreport pytest_collectreport"):
        return [x.report for x in self.getcalls(names)]

    def matchreport(
        self,
        inamepart="",
        names="pytest_runtest_logreport pytest_collectreport",
        when=None,
    ):
        """return a testreport whose dotted import path matches"""
        values = []
        for rep in self.getreports(names=names):
            try:
                if not when and rep.when != "call" and rep.passed:
                    # setup/teardown passing reports - let's ignore those
                    continue
            except AttributeError:
                pass
            if when and getattr(rep, "when", None) != when:
                continue
            if not inamepart or inamepart in rep.nodeid.split("::"):
                values.append(rep)
        if not values:
            raise ValueError(
                "could not find test report matching %r: "
                "no test reports at all!" % (inamepart,)
            )
        if len(values) > 1:
            raise ValueError(
                "found 2 or more testreports matching %r: %s" % (inamepart, values)
            )
        return values[0]

    def getfailures(self, names="pytest_runtest_logreport pytest_collectreport"):
        return [rep for rep in self.getreports(names) if rep.failed]

    def getfailedcollections(self):
        return self.getfailures("pytest_collectreport")

    def listoutcomes(self):
        passed = []
        skipped = []
        failed = []
        for rep in self.getreports("pytest_collectreport pytest_runtest_logreport"):
            if rep.passed:
                if getattr(rep, "when", None) == "call":
                    passed.append(rep)
            elif rep.skipped:
                skipped.append(rep)
            elif rep.failed:
                failed.append(rep)
        return passed, skipped, failed

    def countoutcomes(self):
        return [len(x) for x in self.listoutcomes()]

    def assertoutcome(self, passed=0, skipped=0, failed=0):
        realpassed, realskipped, realfailed = self.listoutcomes()
        assert passed == len(realpassed)
        assert skipped == len(realskipped)
        assert failed == len(realfailed)

    def clear(self):
        self.calls[:] = []

@pytest.fixture
def linecomp(request):
    return LineComp()

@pytest.fixture(name="LineMatcher")
def LineMatcher_fixture(request):
    return LineMatcher

@pytest.fixture
def testdir(request, tmpdir_factory):
    return Testdir(request, tmpdir_factory)

rex_outcome = re.compile(r"(\d+) ([\w-]+)")

class RunResult(object):
    """The result of running a command.

    Attributes:

    :ret: the return value
    :outlines: list of lines captured from stdout
    :errlines: list of lines captures from stderr
    :stdout: :py:class:`LineMatcher` of stdout, use ``stdout.str()`` to
       reconstruct stdout or the commonly used ``stdout.fnmatch_lines()``
       method
    :stderr: :py:class:`LineMatcher` of stderr
    :duration: duration in seconds

    """

    def __init__(self, ret, outlines, errlines, duration):
        self.ret = ret
        self.outlines = outlines
        self.errlines = errlines
        self.stdout = LineMatcher(outlines)
        self.stderr = LineMatcher(errlines)
        self.duration = duration

    def parseoutcomes(self):
        """Return a dictionary of outcomestring->num from parsing the terminal
        output that the test process produced.

        """
        for line in reversed(self.outlines):
            if "seconds" in line:
                outcomes = rex_outcome.findall(line)
                if outcomes:
                    d = {}
                    for num, cat in outcomes:
                        d[cat] = int(num)
                    return d
        raise ValueError("Pytest terminal report not found")

    def assert_outcomes(
        self, passed=0, skipped=0, failed=0, error=0, xpassed=0, xfailed=0
    ):
        """Assert that the specified outcomes appear with the respective
        numbers (0 means it didn't occur) in the text output from a test run.

        """
        d = self.parseoutcomes()
        obtained = {
            "passed": d.get("passed", 0),
            "skipped": d.get("skipped", 0),
            "failed": d.get("failed", 0),
            "error": d.get("error", 0),
            "xpassed": d.get("xpassed", 0),
            "xfailed": d.get("xfailed", 0),
        }
        expected = {
            "passed": passed,
            "skipped": skipped,
            "failed": failed,
            "error": error,
            "xpassed": xpassed,
            "xfailed": xfailed,
        }
        assert obtained == expected

class CwdSnapshot(object):
    def __init__(self):
        self.__saved = os.getcwd()

    def restore(self):
        os.chdir(self.__saved)

class SysModulesSnapshot(object):
    def __init__(self, preserve=None):
        self.__preserve = preserve
        self.__saved = dict(sys.modules)

    def restore(self):
        if self.__preserve:
            self.__saved.update(
                (k, m) for k, m in sys.modules.items() if self.__preserve(k)
            )
        sys.modules.clear()
        sys.modules.update(self.__saved)

class SysPathsSnapshot(object):
    def __init__(self):
        self.__saved = list(sys.path), list(sys.meta_path)

    def restore(self):
        sys.path[:], sys.meta_path[:] = self.__saved

class Testdir(object):
    """Temporary test directory with tools to test/run pytest itself.

    This is based on the ``tmpdir`` fixture but provides a number of methods
    which aid with testing pytest itself.  Unless :py:meth:`chdir` is used all
    methods will use :py:attr:`tmpdir` as their current working directory.

    Attributes:

    :tmpdir: The :py:class:`py.path.local` instance of the temporary directory.

    :plugins: A list of plugins to use with :py:meth:`parseconfig` and
       :py:meth:`runpytest`.  Initially this is an empty list but plugins can
       be added to the list.  The type of items to add to the list depends on
       the method using them so refer to them for details.

    """

    class TimeoutExpired(Exception):
        pass

    def __init__(self, request, tmpdir_factory):
        self.request = request
        self._mod_collections = WeakKeyDictionary()
        name = request.function.__name__
        self.tmpdir = tmpdir_factory.mktemp(name, numbered=True)
        self.test_tmproot = tmpdir_factory.mktemp("tmp-" + name, numbered=True)
        os.environ["PYTEST_DEBUG_TEMPROOT"] = str(self.test_tmproot)
        self.plugins = []
        self._cwd_snapshot = CwdSnapshot()
        self._sys_path_snapshot = SysPathsSnapshot()
        self._sys_modules_snapshot = self.__take_sys_modules_snapshot()
        self.chdir()
        self.request.addfinalizer(self.finalize)
        method = self.request.config.getoption("--runpytest")
        if method == "inprocess":
            self._runpytest_method = self.runpytest_inprocess
        elif method == "subprocess":
            self._runpytest_method = self.runpytest_subprocess

    def __repr__(self):
        return "<Testdir %r>" % (self.tmpdir,)

    def finalize(self):
        """Clean up global state artifacts.

        Some methods modify the global interpreter state and this tries to
        clean this up.  It does not remove the temporary directory however so
        it can be looked at after the test run has finished.

        """
        self._sys_modules_snapshot.restore()
        self._sys_path_snapshot.restore()
        self._cwd_snapshot.restore()
        os.environ.pop("PYTEST_DEBUG_TEMPROOT", None)

    def __take_sys_modules_snapshot(self):
        # some zope modules used by twisted-related tests keep internal state
        # and can't be deleted; we had some trouble in the past with
        # `zope.interface` for example
        def preserve_module(name):
            return name.startswith("zope")

        return SysModulesSnapshot(preserve=preserve_module)

    def make_hook_recorder(self, pluginmanager):
        """Create a new :py:class:`HookRecorder` for a PluginManager."""
        pluginmanager.reprec = reprec = HookRecorder(pluginmanager)
        self.request.addfinalizer(reprec.finish_recording)
        return reprec

    def chdir(self):
        """Cd into the temporary directory.

        This is done automatically upon instantiation.

        """
        self.tmpdir.chdir()

    def _makefile(self, ext, args, kwargs, encoding="utf-8"):
        items = list(kwargs.items())

        def to_text(s):
            return s.decode(encoding) if isinstance(s, bytes) else six.text_type(s)

        if args:
            source = u"\n".join(to_text(x) for x in args)
            basename = self.request.function.__name__
            items.insert(0, (basename, source))

        ret = None
        for basename, value in items:
            p = self.tmpdir.join(basename).new(ext=ext)
            p.dirpath().ensure_dir()
            source = Source(value)
            source = u"\n".join(to_text(line) for line in source.lines)
            p.write(source.strip().encode(encoding), "wb")
            if ret is None:
                ret = p
        return ret

    def makefile(self, ext, *args, **kwargs):
        r"""Create new file(s) in the testdir.

        :param str ext: The extension the file(s) should use, including the dot, e.g. `.py`.
        :param list[str] args: All args will be treated as strings and joined using newlines.
           The result will be written as contents to the file.  The name of the
           file will be based on the test function requesting this fixture.
        :param kwargs: Each keyword is the name of a file, while the value of it will
           be written as contents of the file.

        Examples:

        .. code-block:: python

            testdir.makefile(".txt", "line1", "line2")

            testdir.makefile(".ini", pytest="[pytest]\naddopts=-rs\n")

        """
        return self._makefile(ext, args, kwargs)

    def makeconftest(self, source):
        """Write a contest.py file with 'source' as contents."""
        return self.makepyfile(conftest=source)

    def makeini(self, source):
        """Write a tox.ini file with 'source' as contents."""
        return self.makefile(".ini", tox=source)

    def getinicfg(self, source):
        """Return the pytest section from the tox.ini config file."""
        p = self.makeini(source)
        return py.iniconfig.IniConfig(p)["pytest"]

    def makepyfile(self, *args, **kwargs):
        """Shortcut for .makefile() with a .py extension."""
        return self._makefile(".py", args, kwargs)

    def maketxtfile(self, *args, **kwargs):
        """Shortcut for .makefile() with a .txt extension."""
        return self._makefile(".txt", args, kwargs)

    def syspathinsert(self, path=None):
        """Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.

        This is undone automatically when this object dies at the end of each
        test.

        """
        if path is None:
            path = self.tmpdir
        sys.path.insert(0, str(path))
        # a call to syspathinsert() usually means that the caller wants to
        # import some dynamically created files, thus with python3 we
        # invalidate its import caches
        self._possibly_invalidate_import_caches()

    def _possibly_invalidate_import_caches(self):
        # invalidate caches if we can (py33 and above)
        try:
            import importlib
        except ImportError:
            pass
        else:
            if hasattr(importlib, "invalidate_caches"):
                importlib.invalidate_caches()

    def mkdir(self, name):
        """Create a new (sub)directory."""
        return self.tmpdir.mkdir(name)

    def mkpydir(self, name):
        """Create a new python package.

        This creates a (sub)directory with an empty ``__init__.py`` file so it
        gets recognised as a python package.

        """
        p = self.mkdir(name)
        p.ensure("__init__.py")
        return p

    def copy_example(self, name=None):
        import warnings
        from _pytest.warning_types import PYTESTER_COPY_EXAMPLE

        warnings.warn(PYTESTER_COPY_EXAMPLE, stacklevel=2)
        example_dir = self.request.config.getini("pytester_example_dir")
        if example_dir is None:
            raise ValueError("pytester_example_dir is unset, can't copy examples")
        example_dir = self.request.config.rootdir.join(example_dir)

        for extra_element in self.request.node.iter_markers("pytester_example_path"):
            assert extra_element.args
            example_dir = example_dir.join(*extra_element.args)

        if name is None:
            func_name = self.request.function.__name__
            maybe_dir = example_dir / func_name
            maybe_file = example_dir / (func_name + ".py")

            if maybe_dir.isdir():
                example_path = maybe_dir
            elif maybe_file.isfile():
                example_path = maybe_file
            else:
                raise LookupError(
                    "{} cant be found as module or package in {}".format(
                        func_name, example_dir.bestrelpath(self.request.confg.rootdir)
                    )
                )
        else:
            example_path = example_dir.join(name)

        if example_path.isdir() and not example_path.join("__init__.py").isfile():
            example_path.copy(self.tmpdir)
            return self.tmpdir
        elif example_path.isfile():
            result = self.tmpdir.join(example_path.basename)
            example_path.copy(result)
            return result
        else:
            raise LookupError(
                'example "{}" is not found as a file or directory'.format(example_path)
            )

    Session = Session

    def getnode(self, config, arg):
        """Return the collection node of a file.

        :param config: :py:class:`_pytest.config.Config` instance, see
           :py:meth:`parseconfig` and :py:meth:`parseconfigure` to create the
           configuration

        :param arg: a :py:class:`py.path.local` instance of the file

        """
        session = Session(config)
        assert "::" not in str(arg)
        p = py.path.local(arg)
        config.hook.pytest_sessionstart(session=session)
        res = session.perform_collect([str(p)], genitems=False)[0]
        config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)
        return res

    def getpathnode(self, path):
        """Return the collection node of a file.

        This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to
        create the (configured) pytest Config instance.

        :param path: a :py:class:`py.path.local` instance of the file

        """
        config = self.parseconfigure(path)
        session = Session(config)
        x = session.fspath.bestrelpath(path)
        config.hook.pytest_sessionstart(session=session)
        res = session.perform_collect([x], genitems=False)[0]
        config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)
        return res

    def genitems(self, colitems):
        """Generate all test items from a collection node.

        This recurses into the collection node and returns a list of all the
        test items contained within.

        """
        session = colitems[0].session
        result = []
        for colitem in colitems:
            result.extend(session.genitems(colitem))
        return result

    def runitem(self, source):
        """Run the "test_func" Item.

        The calling test instance (class containing the test method) must
        provide a ``.getrunner()`` method which should return a runner which
        can run the test protocol for a single item, e.g.
        :py:func:`_pytest.runner.runtestprotocol`.

        """
        # used from runner functional tests
        item = self.getitem(source)
        # the test class where we are called from wants to provide the runner
        testclassinstance = self.request.instance
        runner = testclassinstance.getrunner()
        return runner(item)

    def inline_runsource(self, source, *cmdlineargs):
        """Run a test module in process using ``pytest.main()``.

        This run writes "source" into a temporary file and runs
        ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance
        for the result.

        :param source: the source code of the test module

        :param cmdlineargs: any extra command line arguments to use

        :return: :py:class:`HookRecorder` instance of the result

        """
        p = self.makepyfile(source)
        values = list(cmdlineargs) + [p]
        return self.inline_run(*values)

    def inline_genitems(self, *args):
        """Run ``pytest.main(['--collectonly'])`` in-process.

        Runs the :py:func:`pytest.main` function to run all of pytest inside
        the test process itself like :py:meth:`inline_run`, but returns a
        tuple of the collected items and a :py:class:`HookRecorder` instance.

        """
        rec = self.inline_run("--collect-only", *args)
        items = [x.item for x in rec.getcalls("pytest_itemcollected")]
        return items, rec

    def inline_run(self, *args, **kwargs):
        """Run ``pytest.main()`` in-process, returning a HookRecorder.

        Runs the :py:func:`pytest.main` function to run all of pytest inside
        the test process itself.  This means it can return a
        :py:class:`HookRecorder` instance which gives more detailed results
        from that run than can be done by matching stdout/stderr from
        :py:meth:`runpytest`.

        :param args: command line arguments to pass to :py:func:`pytest.main`

        :param plugin: (keyword-only) extra plugin instances the
           ``pytest.main()`` instance should use

        :return: a :py:class:`HookRecorder` instance

        """
        finalizers = []
        try:
            # When running pytest inline any plugins active in the main test
            # process are already imported.  So this disables the warning which
            # will trigger to say they can no longer be rewritten, which is
            # fine as they have already been rewritten.
            orig_warn = AssertionRewritingHook._warn_already_imported

            def revert_warn_already_imported():
                AssertionRewritingHook._warn_already_imported = orig_warn

            finalizers.append(revert_warn_already_imported)
            AssertionRewritingHook._warn_already_imported = lambda *a: None

            # Any sys.module or sys.path changes done while running pytest
            # inline should be reverted after the test run completes to avoid
            # clashing with later inline tests run within the same pytest test,
            # e.g. just because they use matching test module names.
            finalizers.append(self.__take_sys_modules_snapshot().restore)
            finalizers.append(SysPathsSnapshot().restore)

            # Important note:
            # - our tests should not leave any other references/registrations
            #   laying around other than possibly loaded test modules
            #   referenced from sys.modules, as nothing will clean those up
            #   automatically

            rec = []

            class Collect(object):
                def pytest_configure(x, config):
                    rec.append(self.make_hook_recorder(config.pluginmanager))

            plugins = kwargs.get("plugins") or []
            plugins.append(Collect())
            ret = pytest.main(list(args), plugins=plugins)
            if len(rec) == 1:
                reprec = rec.pop()
            else:

                class reprec(object):
                    pass

            reprec.ret = ret

            # typically we reraise keyboard interrupts from the child run
            # because it's our user requesting interruption of the testing
            if ret == EXIT_INTERRUPTED and not kwargs.get("no_reraise_ctrlc"):
                calls = reprec.getcalls("pytest_keyboard_interrupt")
                if calls and calls[-1].excinfo.type == KeyboardInterrupt:
                    raise KeyboardInterrupt()
            return reprec
        finally:
            for finalizer in finalizers:
                finalizer()

    def runpytest_inprocess(self, *args, **kwargs):
        """Return result of running pytest in-process, providing a similar
        interface to what self.runpytest() provides.

        """
        if kwargs.get("syspathinsert"):
            self.syspathinsert()
        now = time.time()
        capture = MultiCapture(Capture=SysCapture)
        capture.start_capturing()
        try:
            try:
                reprec = self.inline_run(*args, **kwargs)
            except SystemExit as e:

                class reprec(object):
                    ret = e.args[0]

            except Exception:
                traceback.print_exc()

                class reprec(object):
                    ret = 3

        finally:
            out, err = capture.readouterr()
            capture.stop_capturing()
            sys.stdout.write(out)
            sys.stderr.write(err)

        res = RunResult(reprec.ret, out.split("\n"), err.split("\n"), time.time() - now)
        res.reprec = reprec
        return res

    def runpytest(self, *args, **kwargs):
        """Run pytest inline or in a subprocess, depending on the command line
        option "--runpytest" and return a :py:class:`RunResult`.

        """
        args = self._ensure_basetemp(args)
        return self._runpytest_method(*args, **kwargs)

    def _ensure_basetemp(self, args):
        args = list(args)
        for x in args:
            if safe_str(x).startswith("--basetemp"):
                break
        else:
            args.append("--basetemp=%s" % self.tmpdir.dirpath("basetemp"))
        return args

    def parseconfig(self, *args):
        """Return a new pytest Config instance from given commandline args.

        This invokes the pytest bootstrapping code in _pytest.config to create
        a new :py:class:`_pytest.core.PluginManager` and call the
        pytest_cmdline_parse hook to create a new
        :py:class:`_pytest.config.Config` instance.

        If :py:attr:`plugins` has been populated they should be plugin modules
        to be registered with the PluginManager.

        """
        args = self._ensure_basetemp(args)

        import _pytest.config

        config = _pytest.config._prepareconfig(args, self.plugins)
        # we don't know what the test will do with this half-setup config
        # object and thus we make sure it gets unconfigured properly in any
        # case (otherwise capturing could still be active, for example)
        self.request.addfinalizer(config._ensure_unconfigure)
        return config

    def parseconfigure(self, *args):
        """Return a new pytest configured Config instance.

        This returns a new :py:class:`_pytest.config.Config` instance like
        :py:meth:`parseconfig`, but also calls the pytest_configure hook.

        """
        config = self.parseconfig(*args)
        config._do_configure()
        self.request.addfinalizer(config._ensure_unconfigure)
        return config

    def getitem(self, source, funcname="test_func"):
        """Return the test item for a test function.

        This writes the source to a python file and runs pytest's collection on
        the resulting module, returning the test item for the requested
        function name.

        :param source: the module source

        :param funcname: the name of the test function for which to return a
            test item

        """
        items = self.getitems(source)
        for item in items:
            if item.name == funcname:
                return item
        assert 0, "%r item not found in module:\n%s\nitems: %s" % (
            funcname,
            source,
            items,
        )

    def getitems(self, source):
        """Return all test items collected from the module.

        This writes the source to a python file and runs pytest's collection on
        the resulting module, returning all test items contained within.

        """
        modcol = self.getmodulecol(source)
        return self.genitems([modcol])

    def getmodulecol(self, source, configargs=(), withinit=False):
        """Return the module collection node for ``source``.

        This writes ``source`` to a file using :py:meth:`makepyfile` and then
        runs the pytest collection on it, returning the collection node for the
        test module.

        :param source: the source code of the module to collect

        :param configargs: any extra arguments to pass to
            :py:meth:`parseconfigure`

        :param withinit: whether to also write an ``__init__.py`` file to the
            same directory to ensure it is a package

        """
        if isinstance(source, Path):
            path = self.tmpdir.join(str(source))
            assert not withinit, "not supported for paths"
        else:
            kw = {self.request.function.__name__: Source(source).strip()}
            path = self.makepyfile(**kw)
        if withinit:
            self.makepyfile(__init__="#")
        self.config = config = self.parseconfigure(path, *configargs)
        return self.getnode(config, path)

    def collect_by_name(self, modcol, name):
        """Return the collection node for name from the module collection.

        This will search a module collection node for a collection node
        matching the given name.

        :param modcol: a module collection node; see :py:meth:`getmodulecol`

        :param name: the name of the node to return

        """
        if modcol not in self._mod_collections:
            self._mod_collections[modcol] = list(modcol.collect())
        for colitem in self._mod_collections[modcol]:
            if colitem.name == name:
                return colitem

    def popen(self, cmdargs, stdout, stderr, **kw):
        """Invoke subprocess.Popen.

        This calls subprocess.Popen making sure the current working directory
        is in the PYTHONPATH.

        You probably want to use :py:meth:`run` instead.

        """
        env = os.environ.copy()
        env["PYTHONPATH"] = os.pathsep.join(
            filter(None, [os.getcwd(), env.get("PYTHONPATH", "")])
        )
        kw["env"] = env

        popen = subprocess.Popen(
            cmdargs, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, **kw
        )
        popen.stdin.close()

        return popen

    def run(self, *cmdargs, **kwargs):
        """Run a command with arguments.

        Run a process using subprocess.Popen saving the stdout and stderr.

        :param args: the sequence of arguments to pass to `subprocess.Popen()`
        :param timeout: the period in seconds after which to timeout and raise
            :py:class:`Testdir.TimeoutExpired`

        Returns a :py:class:`RunResult`.

        """
        __tracebackhide__ = True

        timeout = kwargs.pop("timeout", None)
        raise_on_kwargs(kwargs)

        cmdargs = [
            str(arg) if isinstance(arg, py.path.local) else arg for arg in cmdargs
        ]
        p1 = self.tmpdir.join("stdout")
        p2 = self.tmpdir.join("stderr")
        print("running:", *cmdargs)
        print("     in:", py.path.local())
        f1 = codecs.open(str(p1), "w", encoding="utf8")
        f2 = codecs.open(str(p2), "w", encoding="utf8")
        try:
            now = time.time()
            popen = self.popen(
                cmdargs, stdout=f1, stderr=f2, close_fds=(sys.platform != "win32")
            )

            def handle_timeout():
                __tracebackhide__ = True

                timeout_message = (
                    "{seconds} second timeout expired running:"
                    " {command}".format(seconds=timeout, command=cmdargs)
                )

                popen.kill()
                popen.wait()
                raise self.TimeoutExpired(timeout_message)

            if timeout is None:
                ret = popen.wait()
            elif six.PY3:
                try:
                    ret = popen.wait(timeout)
                except subprocess.TimeoutExpired:
                    handle_timeout()
            else:
                end = time.time() + timeout

                resolution = min(0.1, timeout / 10)

                while True:
                    ret = popen.poll()
                    if ret is not None:
                        break

                    if time.time() > end:
                        handle_timeout()

                    time.sleep(resolution)
        finally:
            f1.close()
            f2.close()
        f1 = codecs.open(str(p1), "r", encoding="utf8")
        f2 = codecs.open(str(p2), "r", encoding="utf8")
        try:
            out = f1.read().splitlines()
            err = f2.read().splitlines()
        finally:
            f1.close()
            f2.close()
        self._dump_lines(out, sys.stdout)
        self._dump_lines(err, sys.stderr)
        return RunResult(ret, out, err, time.time() - now)

    def _dump_lines(self, lines, fp):
        try:
            for line in lines:
                print(line, file=fp)
        except UnicodeEncodeError:
            print("couldn't print to %s because of encoding" % (fp,))

    def _getpytestargs(self):
        return sys.executable, "-mpytest"

    def runpython(self, script):
        """Run a python script using sys.executable as interpreter.

        Returns a :py:class:`RunResult`.

        """
        return self.run(sys.executable, script)

    def runpython_c(self, command):
        """Run python -c "command", return a :py:class:`RunResult`."""
        return self.run(sys.executable, "-c", command)

    def runpytest_subprocess(self, *args, **kwargs):
        """Run pytest as a subprocess with given arguments.

        Any plugins added to the :py:attr:`plugins` list will added using the
        ``-p`` command line option.  Additionally ``--basetemp`` is used put
        any temporary files and directories in a numbered directory prefixed
        with "runpytest-" so they do not conflict with the normal numbered
        pytest location for temporary files and directories.

        :param args: the sequence of arguments to pass to the pytest subprocess
        :param timeout: the period in seconds after which to timeout and raise
            :py:class:`Testdir.TimeoutExpired`

        Returns a :py:class:`RunResult`.

        """
        __tracebackhide__ = True

        p = py.path.local.make_numbered_dir(
            prefix="runpytest-", keep=None, rootdir=self.tmpdir
        )
        args = ("--basetemp=%s" % p,) + args
        plugins = [x for x in self.plugins if isinstance(x, str)]
        if plugins:
            args = ("-p", plugins[0]) + args
        args = self._getpytestargs() + args
        return self.run(*args, timeout=kwargs.get("timeout"))

    def spawn_pytest(self, string, expect_timeout=10.0):
        """Run pytest using pexpect.

        This makes sure to use the right pytest and sets up the temporary
        directory locations.

        The pexpect child is returned.

        """
        basetemp = self.tmpdir.mkdir("temp-pexpect")
        invoke = " ".join(map(str, self._getpytestargs()))
        cmd = "%s --basetemp=%s %s" % (invoke, basetemp, string)
        return self.spawn(cmd, expect_timeout=expect_timeout)

    def spawn(self, cmd, expect_timeout=10.0):
        """Run a command using pexpect.

        The pexpect child is returned.

        """
        pexpect = pytest.importorskip("pexpect", "3.0")
        if hasattr(sys, "pypy_version_info") and "64" in platform.machine():
            pytest.skip("pypy-64 bit not supported")
        if sys.platform.startswith("freebsd"):
            pytest.xfail("pexpect does not work reliably on freebsd")
        logfile = self.tmpdir.join("spawn.out").open("wb")
        child = pexpect.spawn(cmd, logfile=logfile)
        self.request.addfinalizer(logfile.close)
        child.timeout = expect_timeout
        return child

def getdecoded(out):
    try:
        return out.decode("utf-8")
    except UnicodeDecodeError:
        return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % (
            py.io.saferepr(out),
        )

class LineComp(object):
    def __init__(self):
        self.stringio = py.io.TextIO()

    def assert_contains_lines(self, lines2):
        """Assert that lines2 are contained (linearly) in lines1.

        Return a list of extralines found.

        """
        __tracebackhide__ = True
        val = self.stringio.getvalue()
        self.stringio.truncate(0)
        self.stringio.seek(0)
        lines1 = val.split("\n")
        return LineMatcher(lines1).fnmatch_lines(lines2)

class LineMatcher(object):
    """Flexible matching of text.

    This is a convenience class to test large texts like the output of
    commands.

    The constructor takes a list of lines without their trailing newlines, i.e.
    ``text.splitlines()``.

    """

    def __init__(self, lines):
        self.lines = lines
        self._log_output = []

    def str(self):
        """Return the entire original text."""
        return "\n".join(self.lines)

    def _getlines(self, lines2):
        if isinstance(lines2, str):
            lines2 = Source(lines2)
        if isinstance(lines2, Source):
            lines2 = lines2.strip().lines
        return lines2

    def fnmatch_lines_random(self, lines2):
        """Check lines exist in the output using in any order.

        Lines are checked using ``fnmatch.fnmatch``. The argument is a list of
        lines which have to occur in the output, in any order.

        """
        self._match_lines_random(lines2, fnmatch)

    def re_match_lines_random(self, lines2):
        """Check lines exist in the output using ``re.match``, in any order.

        The argument is a list of lines which have to occur in the output, in
        any order.

        """
        self._match_lines_random(lines2, lambda name, pat: re.match(pat, name))

    def _match_lines_random(self, lines2, match_func):
        """Check lines exist in the output.

        The argument is a list of lines which have to occur in the output, in
        any order.  Each line can contain glob whildcards.

        """
        lines2 = self._getlines(lines2)
        for line in lines2:
            for x in self.lines:
                if line == x or match_func(x, line):
                    self._log("matched: ", repr(line))
                    break
            else:
                self._log("line %r not found in output" % line)
                raise ValueError(self._log_text)

    def get_lines_after(self, fnline):
        """Return all lines following the given line in the text.

        The given line can contain glob wildcards.

        """
        for i, line in enumerate(self.lines):
            if fnline == line or fnmatch(line, fnline):
                return self.lines[i + 1 :]
        raise ValueError("line %r not found in output" % fnline)

    def _log(self, *args):
        self._log_output.append(" ".join((str(x) for x in args)))

    @property
    def _log_text(self):
        return "\n".join(self._log_output)

    def fnmatch_lines(self, lines2):
        """Search captured text for matching lines using ``fnmatch.fnmatch``.

        The argument is a list of lines which have to match and can use glob
        wildcards.  If they do not match a pytest.fail() is called.  The
        matches and non-matches are also printed on stdout.

        """
        __tracebackhide__ = True
        self._match_lines(lines2, fnmatch, "fnmatch")

    def re_match_lines(self, lines2):
        """Search captured text for matching lines using ``re.match``.

        The argument is a list of lines which have to match using ``re.match``.
        If they do not match a pytest.fail() is called.

        The matches and non-matches are also printed on stdout.

        """
        __tracebackhide__ = True
        self._match_lines(lines2, lambda name, pat: re.match(pat, name), "re.match")

    def _match_lines(self, lines2, match_func, match_nickname):
        """Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.

        :param list[str] lines2: list of string patterns to match. The actual
            format depends on ``match_func``
        :param match_func: a callable ``match_func(line, pattern)`` where line
            is the captured line from stdout/stderr and pattern is the matching
            pattern
        :param str match_nickname: the nickname for the match function that
            will be logged to stdout when a match occurs

        """
        lines2 = self._getlines(lines2)
        lines1 = self.lines[:]
        nextline = None
        extralines = []
        __tracebackhide__ = True
        for line in lines2:
            nomatchprinted = False
            while lines1:
                nextline = lines1.pop(0)
                if line == nextline:
                    self._log("exact match:", repr(line))
                    break
                elif match_func(nextline, line):
                    self._log("%s:" % match_nickname, repr(line))
                    self._log("   with:", repr(nextline))
                    break
                else:
                    if not nomatchprinted:
                        self._log("nomatch:", repr(line))
                        nomatchprinted = True
                    self._log("    and:", repr(nextline))
                extralines.append(nextline)
            else:
                self._log("remains unmatched: %r" % (line,))
                pytest.fail(self._log_text)


text:
{% extends 'pages/base.html' %}

{% block maintitle %}
  Notifications - Oppia
{% endblock maintitle %}

{% block navbar_breadcrumb %}

      Notifications

{% endblock navbar_breadcrumb %}

{% block content %}

Notifications

      Last updated: <[getLocaleAbbreviatedDatetimeString(jobQueuedMsec)]>

      <md-card ng-if="recentNotifications.length === 0" class="oppia-page-card oppia-notifications-dashboard-card">
        No recent notifications.
      </md-card>

 0">
        <md-card ng-repeat="notification in recentNotifications" class="oppia-dashboard-row"
          ng-class="{'oppia-dashboard-row-recent': lastSeenMsec && lastSeenMsec < notification.last_updated_ms && notification.author_username !== currentUsername}" ng-click="navigateToItem(notification.activity_id, notification.type)">

                

                

                <[notification.author_username]>

                  Anonymous

                made a new commit to

                left a comment on

                <[notification.activity_title]>

            <[getLocaleAbbreviatedDatetimeString(notification.last_updated_ms)]>

        </md-card>

{% endblock %}

{% block footer_js %}
  {{ super() }}

{% endblock footer_js %}


text:
/*!
 * Star Rating Chinese Translations
 *
 * This file must be loaded after 'star-rating.js'. Patterns in braces '{}', or
 * any HTML markup tags in the messages must not be converted or translated.
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 *
 * @see http://github.com/kartik-v/bootstrap-star-rating
 * @author Kartik Visweswaran <kartikv2@gmail.com>
 * @author Freeman
 */
 (function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'window', 'document'], factory);
    } else if (typeof module === 'object' && typeof module.exports === 'object') {
        factory(require('jquery'), window, document);
    } else {
        factory(window.jQuery, window, document);
    }
}(function ($, window, document, undefined) {
    "use strict";
    $.fn.ratingLocales['zh'] = {
        defaultCaption: '{rating} 星',
        starCaptions: {
            0.5: '半星',
            1: '一星',
            1.5: '一星半',
            2: '二星',
            2.5: '二星半',
            3: '三星',
            3.5: '三星半',
            4: '四星',
            4.5: '四星半',
            5: '五星'
        },
        clearButtonTitle: '清除',
        clearCaption: '未评级'
    };
}));


text:
namespace NLog.LayoutRenderers
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Globalization;
    using System.Text;
    using Microsoft.Win32;
    using NLog.Common;
    using NLog.Internal;
    using NLog.Config;
    using NLog.Layouts;

    ///
    /// A value from the Registry.
    ///
    [LayoutRenderer("registry")]
    public class RegistryLayoutRenderer : LayoutRenderer
    {
        ///
        /// Create new renderer
        ///
        public RegistryLayoutRenderer()
        {
            RequireEscapingSlashesInDefaultValue = true;
        }

        ///
        /// Gets or sets the registry value name.
        ///
        /// <docgen category='Registry Options' order='10' />
        public Layout Value { get; set; }

        ///
        /// Gets or sets the value to be output when the specified registry key or value is not found.
        ///
        /// <docgen category='Registry Options' order='10' />
        public Layout DefaultValue { get; set; }

        ///
        /// Require escaping backward slashes in <see cref="DefaultValue"/>. Need to be backwards-compatible.
        ///
        /// When true:
        ///
        /// `\` in value should be configured as `\\`
        /// `\\` in value should be configured as `\\\\`.
        ///
        /// <remarks>Default value wasn't a Layout before and needed an escape of the slash</remarks>
        /// <docgen category='Registry Options' order='50' />
        [DefaultValue(true)]
        public bool RequireEscapingSlashesInDefaultValue { get; set; }

#if !NET3_5
        ///
        /// Gets or sets the registry view (see: https://msdn.microsoft.com/de-de/library/microsoft.win32.registryview.aspx).
        /// Allowed values: Registry32, Registry64, Default
        ///
        /// <docgen category='Registry Options' order='10' />
        [DefaultValue("Default")]
        public RegistryView View { get; set; }
#endif
        ///
        /// Gets or sets the registry key.
        ///
        /// <example>
        /// HKCU\Software\NLogTest
        /// </example>
        /// <remarks>
        /// Possible keys:
        ///

        ///
HKEY_LOCAL_MACHINE

        ///
HKLM

        ///
HKEY_CURRENT_USER

        ///
HKCU

        ///
HKEY_CLASSES_ROOT

        ///
HKEY_USERS

        ///
HKEY_CURRENT_CONFIG

        ///
HKEY_DYN_DATA

        ///
HKEY_PERFORMANCE_DATA

        ///

        /// </remarks>
        /// <docgen category='Registry Options' order='10' />
        [RequiredParameter]
        public Layout Key { get; set; }

        ///
        /// Reads the specified registry key and value and appends it to
        /// the passed <see cref="StringBuilder"/>.
        ///
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event. Ignored.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            object registryValue = null;
            // Value = null is necessary for querying "unnamed values"
            string renderedValue = Value?.Render(logEvent);

            var parseResult = ParseKey(Key.Render(logEvent));
            try
            {
#if !NET3_5
                using (RegistryKey rootKey = RegistryKey.OpenBaseKey(parseResult.Hive, View))
#else
                var rootKey = MapHiveToKey(parseResult.Hive);

#endif

                {

                    if (parseResult.HasSubKey)
                    {
                        using (RegistryKey registryKey = rootKey.OpenSubKey(parseResult.SubKey))
                        {
                            if (registryKey != null) registryValue = registryKey.GetValue(renderedValue);
                        }
                    }
                    else
                    {
                        registryValue = rootKey.GetValue(renderedValue);
                    }
                }
            }
            catch (Exception ex)
            {
                InternalLogger.Error("Error when writing to registry");
                if (ex.MustBeRethrown())
                {
                    throw;
                }
            }

            string value = null;
            if (registryValue != null) // valid value returned from registry will never be null
            {
                value = Convert.ToString(registryValue, CultureInfo.InvariantCulture);
            }
            else if (DefaultValue != null)
            {
                value = DefaultValue.Render(logEvent);

                if (RequireEscapingSlashesInDefaultValue)
                {
                    //remove escape slash
                    value = value.Replace("\\\\", "\\");
                }
            }
            builder.Append(value);
        }

        private class ParseResult
        {
            public string SubKey { get; set; }

            public RegistryHive Hive { get; set; }

            ///
            /// Has <see cref="SubKey"/>?
            ///
            public bool HasSubKey => !string.IsNullOrEmpty(SubKey);
        }

        ///
        /// Parse key to <see cref="RegistryHive"/> and subkey.
        ///
        /// <param name="key">full registry key name</param>
        /// <returns>Result of parsing, never <c>null</c>.</returns>
        private static ParseResult ParseKey(string key)
        {
            string hiveName;
            int pos = key.IndexOfAny(new char[] { '\\', '/' });

            string subkey = null;
            if (pos >= 0)
            {
                hiveName = key.Substring(0, pos);

                //normalize slashes
                subkey = key.Substring(pos + 1).Replace('/', '\\');

                //remove starting slashes
                subkey = subkey.TrimStart('\\');

                //replace double slashes from pre-layout times
                subkey = subkey.Replace("\\\\", "\\");

            }
            else
            {
                hiveName = key;
            }

            var hive = ParseHiveName(hiveName);

            return new ParseResult
            {
                SubKey = subkey,
                Hive = hive,
            };
        }

        ///
        /// Aliases for the hives. See https://msdn.microsoft.com/en-us/library/ctb3kd86(v=vs.110).aspx
        ///
        private static readonly Dictionary<string, RegistryHive> HiveAliases = new Dictionary<string, RegistryHive>(StringComparer.OrdinalIgnoreCase)
        {
            {"HKEY_LOCAL_MACHINE", RegistryHive.LocalMachine},
            {"HKLM", RegistryHive.LocalMachine},
            {"HKEY_CURRENT_USER", RegistryHive.CurrentUser},
            {"HKCU", RegistryHive.CurrentUser},
            {"HKEY_CLASSES_ROOT", RegistryHive.ClassesRoot},
            {"HKEY_USERS", RegistryHive.Users},
            {"HKEY_CURRENT_CONFIG", RegistryHive.CurrentConfig},
            {"HKEY_DYN_DATA", RegistryHive.DynData},
            {"HKEY_PERFORMANCE_DATA", RegistryHive.PerformanceData},
        };

        private static RegistryHive ParseHiveName(string hiveName)
        {
            RegistryHive hive;
            if (HiveAliases.TryGetValue(hiveName, out hive))
            {
                return hive;
            }

            //ArgumentException is consistent
            throw new ArgumentException($"Key name is not supported. Root hive '{hiveName}' not recognized.");
        }

#if NET3_5
        private static RegistryKey MapHiveToKey(RegistryHive hive)
        {
            switch (hive)
            {
                case RegistryHive.LocalMachine:
                    return Registry.LocalMachine;
                case RegistryHive.CurrentUser:
                    return Registry.CurrentUser;
                default:
                    throw new ArgumentException("Only RegistryHive.LocalMachine and RegistryHive.CurrentUser are supported.", nameof(hive));
            }
        }
#endif
    }
}

#endif


text:
package org.apache.flink.core.fs;

import org.apache.flink.annotation.Internal;
import org.apache.flink.util.AbstractCloseableRegistry;

import javax.annotation.Nonnull;

import java.io.Closeable;
import java.util.HashMap;
import java.util.Map;

/**
 * This class allows to register instances of {@link Closeable}, which are all closed if this registry is closed.
 *
 *
Registering to an already closed registry will throw an exception and close the provided {@link Closeable}
 *
 *
All methods in this class are thread-safe.
 */
@Internal
public class CloseableRegistry extends AbstractCloseableRegistry<Closeable, Object> {

	private static final Object DUMMY = new Object();

	public CloseableRegistry() {
		super(new HashMap<>());
	}

	@Override
	protected void doRegister(@Nonnull Closeable closeable, @Nonnull Map<Closeable, Object> closeableMap) {
		closeableMap.put(closeable, DUMMY);
	}

	@Override
	protected boolean doUnRegister(@Nonnull Closeable closeable, @Nonnull Map<Closeable, Object> closeableMap) {
		return closeableMap.remove(closeable) != null;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <parent>
    <groupId>co.cdev</groupId>
    <artifactId>agave-project-root</artifactId>
    <version>2.1-SNAPSHOT</version>
  </parent>

  <modelVersion>4.0.0</modelVersion>
  <artifactId>agave-web-framework</artifactId>
  <name>Agave Web Framework</name>

  <dependencies>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>agave-configuration</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
    <dependency>
      <groupId>org.jmock</groupId>
      <artifactId>jmock</artifactId>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>agave-configuration</artifactId>
      <version>${project.version}</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>agave-core</artifactId>
      <version>${project.version}</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>${project.artifactId}-${project.version}</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>test-jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>with-deps</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>1.4</version>
            <executions>
              <execution>
                <phase>package</phase>
                <goals>
                  <goal>shade</goal>
                </goals>
                <configuration>
                  <finalName>${project.artifactId}-with-deps-${project.version}</finalName>
                  <shadedArtifactAttached>true</shadedArtifactAttached>
                  <shadedClassifierName>with-deps</shadedClassifierName>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

</project>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta content="cloud , programming" name="keywords">
    <meta content="tophatsteve" name="author">
    <meta property="og:title" content="Containers - Tech Debt">
    <meta property="og:url" content="http://techdebt.co.uk/tags/containers/">
    <meta property="og:description" content="">
    <meta property="og:type" content="website" />
    <title>Containers | Tech Debt</title>

    <link rel="stylesheet" href="http://techdebt.co.uk/css/style.css">
    <link rel="shortcut icon" type="image/png" sizes="32x32" href="http://techdebt.co.uk/img/favicon-32x32.png">
    <link rel="shortcut icon" type="image/png" sizes="96x96" href="http://techdebt.co.uk/img/favicon-96x96.png">
    <link rel="shortcut icon" type="image/png" sizes="16x16" href="http://techdebt.co.uk/img/favicon-16x16.png">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha256-eZrrJcwDc/3uDhsdt61sL2oOBY362qM3lon1gyExkL0="
      crossorigin="anonymous" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/github.min.css">

Tech Debt

Running Go in Azure with Container Instances

August 10, 2017

        cloud

        azure

        containers

        go

        Go is not an officially supported language in Azure the way it is on Google Cloud Platform. You can sort of run Go code as part of a web app by installing the “Go Lang for Azure Websites” extension, but this really only allows you to run your code as part of the IIS pipeline, rather than as a standalone server. The best way to run an actual Go server in Azure is via a container.

        ...
          Read more

Copyright (c) 2018, all rights reserved.


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

/**
 *
 * @author xandergerreman
 */
public interface Sound {

    public void playSound();
}