text:
/**
 * Autogenerated by Thrift Compiler (0.9.3)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.storm.generated;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)")
public class WorkerMetricList implements org.apache.thrift.TBase<WorkerMetricList, WorkerMetricList._Fields>, java.io.Serializable, Cloneable, Comparable<WorkerMetricList> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("WorkerMetricList");

  private static final org.apache.thrift.protocol.TField METRICS_FIELD_DESC = new org.apache.thrift.protocol.TField("metrics", org.apache.thrift.protocol.TType.LIST, (short)1);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new WorkerMetricListStandardSchemeFactory());
    schemes.put(TupleScheme.class, new WorkerMetricListTupleSchemeFactory());
  }

  private List<WorkerMetricPoint> metrics; // required

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    METRICS((short)1, "metrics");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // METRICS
          return METRICS;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.METRICS, new org.apache.thrift.meta_data.FieldMetaData("metrics", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
            new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, WorkerMetricPoint.class))));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(WorkerMetricList.class, metaDataMap);
  }

  public WorkerMetricList() {
  }

  public WorkerMetricList(
    List<WorkerMetricPoint> metrics)
  {
    this();
    this.metrics = metrics;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public WorkerMetricList(WorkerMetricList other) {
    if (other.is_set_metrics()) {
      List<WorkerMetricPoint> __this__metrics = new ArrayList<WorkerMetricPoint>(other.metrics.size());
      for (WorkerMetricPoint other_element : other.metrics) {
        __this__metrics.add(new WorkerMetricPoint(other_element));
      }
      this.metrics = __this__metrics;
    }
  }

  public WorkerMetricList deepCopy() {
    return new WorkerMetricList(this);
  }

  @Override
  public void clear() {
    this.metrics = null;
  }

  public int get_metrics_size() {
    return (this.metrics == null) ? 0 : this.metrics.size();
  }

  public java.util.Iterator<WorkerMetricPoint> get_metrics_iterator() {
    return (this.metrics == null) ? null : this.metrics.iterator();
  }

  public void add_to_metrics(WorkerMetricPoint elem) {
    if (this.metrics == null) {
      this.metrics = new ArrayList<WorkerMetricPoint>();
    }
    this.metrics.add(elem);
  }

  public List<WorkerMetricPoint> get_metrics() {
    return this.metrics;
  }

  public void set_metrics(List<WorkerMetricPoint> metrics) {
    this.metrics = metrics;
  }

  public void unset_metrics() {
    this.metrics = null;
  }

  /** Returns true if field metrics is set (has been assigned a value) and false otherwise */
  public boolean is_set_metrics() {
    return this.metrics != null;
  }

  public void set_metrics_isSet(boolean value) {
    if (!value) {
      this.metrics = null;
    }
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case METRICS:
      if (value == null) {
        unset_metrics();
      } else {
        set_metrics((List<WorkerMetricPoint>)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case METRICS:
      return get_metrics();

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case METRICS:
      return is_set_metrics();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof WorkerMetricList)
      return this.equals((WorkerMetricList)that);
    return false;
  }

  public boolean equals(WorkerMetricList that) {
    if (that == null)
      return false;

    boolean this_present_metrics = true && this.is_set_metrics();
    boolean that_present_metrics = true && that.is_set_metrics();
    if (this_present_metrics || that_present_metrics) {
      if (!(this_present_metrics && that_present_metrics))
        return false;
      if (!this.metrics.equals(that.metrics))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    List<Object> list = new ArrayList<Object>();

    boolean present_metrics = true && (is_set_metrics());
    list.add(present_metrics);
    if (present_metrics)
      list.add(metrics);

    return list.hashCode();
  }

  @Override
  public int compareTo(WorkerMetricList other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = Boolean.valueOf(is_set_metrics()).compareTo(other.is_set_metrics());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (is_set_metrics()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.metrics, other.metrics);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("WorkerMetricList(");
    boolean first = true;

    sb.append("metrics:");
    if (this.metrics == null) {
      sb.append("null");
    } else {
      sb.append(this.metrics);
    }
    first = false;
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class WorkerMetricListStandardSchemeFactory implements SchemeFactory {
    public WorkerMetricListStandardScheme getScheme() {
      return new WorkerMetricListStandardScheme();
    }
  }

  private static class WorkerMetricListStandardScheme extends StandardScheme<WorkerMetricList> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, WorkerMetricList struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // METRICS
            if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
              {
                org.apache.thrift.protocol.TList _list870 = iprot.readListBegin();
                struct.metrics = new ArrayList<WorkerMetricPoint>(_list870.size);
                WorkerMetricPoint _elem871;
                for (int _i872 = 0; _i872 < _list870.size; ++_i872)
                {
                  _elem871 = new WorkerMetricPoint();
                  _elem871.read(iprot);
                  struct.metrics.add(_elem871);
                }
                iprot.readListEnd();
              }
              struct.set_metrics_isSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, WorkerMetricList struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.metrics != null) {
        oprot.writeFieldBegin(METRICS_FIELD_DESC);
        {
          oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.metrics.size()));
          for (WorkerMetricPoint _iter873 : struct.metrics)
          {
            _iter873.write(oprot);
          }
          oprot.writeListEnd();
        }
        oprot.writeFieldEnd();
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class WorkerMetricListTupleSchemeFactory implements SchemeFactory {
    public WorkerMetricListTupleScheme getScheme() {
      return new WorkerMetricListTupleScheme();
    }
  }

  private static class WorkerMetricListTupleScheme extends TupleScheme<WorkerMetricList> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, WorkerMetricList struct) throws org.apache.thrift.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      BitSet optionals = new BitSet();
      if (struct.is_set_metrics()) {
        optionals.set(0);
      }
      oprot.writeBitSet(optionals, 1);
      if (struct.is_set_metrics()) {
        {
          oprot.writeI32(struct.metrics.size());
          for (WorkerMetricPoint _iter874 : struct.metrics)
          {
            _iter874.write(oprot);
          }
        }
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, WorkerMetricList struct) throws org.apache.thrift.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      BitSet incoming = iprot.readBitSet(1);
      if (incoming.get(0)) {
        {
          org.apache.thrift.protocol.TList _list875 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
          struct.metrics = new ArrayList<WorkerMetricPoint>(_list875.size);
          WorkerMetricPoint _elem876;
          for (int _i877 = 0; _i877 < _list875.size; ++_i877)
          {
            _elem876 = new WorkerMetricPoint();
            _elem876.read(iprot);
            struct.metrics.add(_elem876);
          }
        }
        struct.set_metrics_isSet(true);
      }
    }
  }

}


text:
using System;

namespace AwesomeTestLogger
{
    public class OutputFormatter
    {
        private const int ColumnWidth = 78;
        private int _column = 0;

        public void WriteSuccess()
        {
            WriteTestOutput(".", ConsoleColor.Green);
        }

        public void WriteFailed()
        {
            WriteTestOutput("F", ConsoleColor.Red);
        }

        public void WriteLine(ConsoleColor color, string text, params object[] obj)
        {
            Console.ForegroundColor = color;
            Console.WriteLine(text, obj);
            Console.ResetColor();
        }

        public void WriteLine(string text, params object[] obj)
        {
            Console.WriteLine(text, obj);
        }

        private void WriteTestOutput(string output, ConsoleColor color)
        {
            if (ShouldGoToNewLine())
            {
                NewLine();
            }

            Console.ForegroundColor = color;
            Console.Write(output);
            Console.ResetColor();

            _column++;
        }

        public void NewLine()
        {
            Console.WriteLine();
            _column = 0;
        }

        private bool ShouldGoToNewLine()
        {
            return _column == ColumnWidth;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.syncope.client.console.wizards.any;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.common.util.CollectionUtils;
import org.apache.syncope.client.console.layout.GroupForm;
import org.apache.syncope.client.console.layout.GroupFormLayoutInfo;
import org.apache.syncope.client.console.rest.GroupRestClient;
import org.apache.syncope.client.ui.commons.wizards.AjaxWizard;
import org.apache.syncope.client.ui.commons.wizards.AjaxWizardBuilder;
import org.apache.syncope.client.ui.commons.wizards.any.AnyWrapper;
import org.apache.syncope.common.lib.AnyOperations;
import org.apache.syncope.common.lib.EntityTOUtils;
import org.apache.syncope.common.lib.request.GroupCR;
import org.apache.syncope.common.lib.request.GroupUR;
import org.apache.syncope.common.lib.to.GroupTO;
import org.apache.syncope.common.lib.to.ProvisioningResult;
import org.apache.wicket.PageReference;

public class GroupWizardBuilder extends AnyWizardBuilder<GroupTO> implements GroupForm {

    private static final long serialVersionUID = 5945391813567245081L;

    protected final GroupRestClient groupRestClient = new GroupRestClient();

    public GroupWizardBuilder(
            final GroupTO groupTO,
            final List<String> anyTypeClasses,
            final GroupFormLayoutInfo formLayoutInfo,
            final PageReference pageRef) {

        super(Optional.ofNullable(groupTO).map(GroupWrapper::new).
                orElse(null), anyTypeClasses, formLayoutInfo, pageRef);
    }

    /**
     * Constructor to be used for Remediation details only.
     *
     * @param previousGroupTO previous group status.
     * @param groupTO new group status to be approved.
     * @param anyTypeClasses any type classes.
     * @param formLayoutInfo from layout.
     * @param pageRef reference page.
     */
    public GroupWizardBuilder(
            final GroupTO previousGroupTO,
            final GroupTO groupTO,
            final List<String> anyTypeClasses,
            final GroupFormLayoutInfo formLayoutInfo,
            final PageReference pageRef) {

        super(new GroupWrapper(previousGroupTO, groupTO), anyTypeClasses, formLayoutInfo, pageRef);
    }

    /**
     * This method has been overridden to manage asynchronous translation of FIQL string to search classes list and
     * viceversa.
     *
     * @param item wizard backend item.
     * @return the current builder.
     */
    @Override
    public AjaxWizardBuilder<AnyWrapper<GroupTO>> setItem(final AnyWrapper<GroupTO> item) {
        return (AjaxWizardBuilder<AnyWrapper<GroupTO>>) (item != null
                ? super.setItem(new GroupWrapper(item.getInnerObject()))
                : super.setItem(null));
    }

    @Override
    protected Serializable onApplyInternal(final AnyWrapper<GroupTO> modelObject) {
        GroupTO updated = modelObject instanceof GroupWrapper
                ? GroupWrapper.class.cast(modelObject).fillDynamicConditions()
                : modelObject.getInnerObject();

        ProvisioningResult<GroupTO> result;
        if (updated.getKey() == null) {
            GroupCR req = new GroupCR();
            EntityTOUtils.toAnyCR(updated, req);
            result = GroupRestClient.create(req);
        } else {
            GroupTO original = getOriginalItem().getInnerObject();
            fixPlainAndVirAttrs(updated, original);

            // SYNCOPE-1170
            boolean othersNotEqualsOrBlanks =
                    !updated.getADynMembershipConds().equals(original.getADynMembershipConds())
                    || (StringUtils.isNotBlank(original.getUDynMembershipCond())
                    && StringUtils.isBlank(updated.getUDynMembershipCond()))
                    || (StringUtils.isBlank(original.getUDynMembershipCond())
                    && StringUtils.isNotBlank(updated.getUDynMembershipCond()))
                    || StringUtils.isAllBlank(original.getUDynMembershipCond(), updated.getUDynMembershipCond())
                    || !updated.getUDynMembershipCond().equals(original.getUDynMembershipCond())
                    || !CollectionUtils.diff(updated.getTypeExtensions(), original.getTypeExtensions()).isEmpty();

            GroupUR groupUR = AnyOperations.diff(updated, original, false);

            // update just if it is changed
            if (groupUR.isEmpty() && !othersNotEqualsOrBlanks) {
                result = new ProvisioningResult<>();
                result.setEntity(updated);
            } else {
                result = groupRestClient.update(original.getETagValue(), groupUR);
            }
        }

        return result;
    }

    @Override
    protected Optional<Details<GroupTO>> addOptionalDetailsPanel(final AnyWrapper<GroupTO> modelObject) {
        return Optional.of(new GroupDetails(
                GroupWrapper.class.cast(modelObject),
                mode == AjaxWizard.Mode.TEMPLATE,
                modelObject.getInnerObject().getKey() != null,
                pageRef));
    }
}


text:
package perf

import (
	"fmt"
	"strconv"
	"strings"
	"unsafe"

	"golang.org/x/sys/unix"
)

const (
	// PERF_TYPE_TRACEPOINT is a kernel tracepoint.
	PERF_TYPE_TRACEPOINT = 2
)

// AvailableEvents returns a mapping of available subsystems and their
// corresponding list of available events.
func AvailableEvents() (map[string][]string, error) {
	events := map[string][]string{}
	// BUG(hodgesds): this should ideally check mounts for debugfs
	rawEvents, err := fileToStrings(TracingDir + "/available_events")
	// Events are colon delimited by type so parse the type and add sub
	// events appropriately.
	if err != nil {
		return events, err
	}
	for _, rawEvent := range rawEvents {
		splits := strings.Split(rawEvent, ":")
		if len(splits) <= 1 {
			continue
		}
		eventTypeEvents, found := events[splits[0]]
		if found {
			events[splits[0]] = append(eventTypeEvents, splits[1])
			continue
		}
		events[splits[0]] = []string{splits[1]}
	}
	return events, err
}

// AvailableSubsystems returns a slice of available subsystems.
func AvailableSubsystems() ([]string, error) {
	subsystems := []string{}
	// BUG(hodgesds): this should ideally check mounts for debugfs
	rawEvents, err := fileToStrings(TracingDir + "/available_events")
	// Events are colon delimited by type so parse the type and add sub
	// events appropriately.
	if err != nil {
		return subsystems, err
	}
	for _, rawEvent := range rawEvents {
		splits := strings.Split(rawEvent, ":")
		if len(splits) <= 1 {
			continue
		}
		subsystems = append(subsystems, splits[0])
	}
	return subsystems, nil
}

// AvailableTracers returns the list of available tracers.
func AvailableTracers() ([]string, error) {
	return fileToStrings(TracingDir + "/available_tracers")
}

// CurrentTracer returns the current tracer.
func CurrentTracer() (string, error) {
	res, err := fileToStrings(TracingDir + "/current_tracer")
	return res[0], err
}

// GetTracepointConfig is used to get the configuration for a trace event.
func GetTracepointConfig(subsystem, event string) (uint64, error) {
	res, err := fileToStrings(
		TracingDir + fmt.Sprintf("/events/%s/%s/id", subsystem, event))
	if err != nil {
		return 0, err
	}
	return strconv.ParseUint(res[0], 10, 64)
}

// ProfileTracepoint is used to profile a kernel tracepoint event for a
// specific PID. Events can be listed with `perf list` for Tracepoint Events or
// in the /sys/kernel/debug/tracing/events directory with the kind being the
// directory and the event being the subdirectory.
func ProfileTracepoint(subsystem, event string, pid, cpu int, opts ...int) (BPFProfiler, error) {
	config, err := GetTracepointConfig(subsystem, event)
	if err != nil {
		return nil, err
	}
	eventAttr := &unix.PerfEventAttr{
		Type:        PERF_TYPE_TRACEPOINT,
		Config:      config,
		Size:        uint32(unsafe.Sizeof(unix.PerfEventAttr{})),
		Bits:        unix.PerfBitDisabled | unix.PerfBitExcludeHv,
		Read_format: unix.PERF_FORMAT_TOTAL_TIME_RUNNING | unix.PERF_FORMAT_TOTAL_TIME_ENABLED,
		Sample_type: PERF_SAMPLE_IDENTIFIER,
	}
	var eventOps int
	if len(opts) > 0 {
		eventOps = opts[0]
	}
	fd, err := unix.PerfEventOpen(
		eventAttr,
		pid,
		cpu,
		-1,
		eventOps,
	)
	if err != nil {
		return nil, err
	}

	return &profiler{
		fd: fd,
	}, nil
}

// TracepointEventAttr is used to return an PerfEventAttr for a trace event.
func TracepointEventAttr(subsystem, event string) (*unix.PerfEventAttr, error) {
	config, err := GetTracepointConfig(subsystem, event)
	if err != nil {
		return nil, err
	}
	return &unix.PerfEventAttr{
		Type:        PERF_TYPE_TRACEPOINT,
		Config:      config,
		Size:        uint32(unsafe.Sizeof(unix.PerfEventAttr{})),
		Bits:        unix.PerfBitDisabled | unix.PerfBitExcludeHv,
		Read_format: unix.PERF_FORMAT_TOTAL_TIME_RUNNING | unix.PERF_FORMAT_TOTAL_TIME_ENABLED,
		Sample_type: PERF_SAMPLE_IDENTIFIER,
	}, nil
}


text:
import React from 'react'
import cx from 'classnames'
import Button from '../Button'
import type { PropsC } from '../types'

class Action extends React.Component {
  props: PropsC
  static defaultProps = {
    component: Button,
  }
  static displayName = 'Card.Action'

  render() {
    const { component: Component, className, ...rest } = this.props
    const rootClassName = cx(
      'mdc-card__action',
      'mdc-button--compact',
      className
    )
    return <Component className={rootClassName} {...rest} />
  }
}

export default Action


text:
<!doctype html>

    <title>AngularJS Website</title>

    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/website.css">

        Home
        About
        Experiments


text:
package com.thinkgem.jeesite.modules.huli.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.modules.huli.entity.FriendTask;
import com.thinkgem.jeesite.modules.huli.dao.FriendTaskDao;

/**
 * 任务管理Service
 * @author shuai
 * @version 2017-08-20
 */
@Service
@Transactional(readOnly = true)
public class FriendTaskService extends CrudService<FriendTaskDao, FriendTask> {

	/**
	 * 持久层对象
	 */
	@Autowired
	protected FriendTaskDao dao;

	public FriendTask get(String id) {
		return super.get(id);
	}

	public List<FriendTask> findList(FriendTask friendTask) {
		return super.findList(friendTask);
	}

	public Page<FriendTask> findPage(Page<FriendTask> page, FriendTask friendTask) {
		return super.findPage(page, friendTask);
	}

	@Transactional(readOnly = false)
	public void save(FriendTask friendTask) {
		//super.save(friendTask);
		if (friendTask.getIsNewRecord()){
			friendTask.setId(IdGen.uuid());
			friendTask.setCreateTime(new Date());
			friendTask.setUpdateTime(new Date());
			dao.insert(friendTask);
		}else{
			friendTask.setUpdateTime(new Date());
			dao.update(friendTask);
		}
	}

	@Transactional(readOnly = false)
	public void delete(FriendTask friendTask) {
		super.delete(friendTask);
	}

	public List<FriendTask> getTasksByInviteOpenid(String inviteOpenid) {
		return dao.getTasksByInviteOpenid(inviteOpenid);
	}

	public List<FriendTask> getTasksByFriendShip(String inviteOpenid,String taskOpenid) {
		return dao.getTasksByOpenids(inviteOpenid,taskOpenid);
	}

	public FriendTask getByOpenids(String inviteOpenid, String taskOpenId) {
		FriendTask  task =  null;
		List<FriendTask> taskList = dao.getTasksByOpenids(inviteOpenid, taskOpenId);
		if(taskList != null && taskList.size()>0){
			task = taskList.get(0);
		}
		return task;
	}

}


text:
<?php

namespace App\Models;

use Core\Database;

class TestModel extends Model
{
    /**
     * @return self
     * @throws \Exception
     */
    public static function create(): self
    {
        return new self();
    }

    /**
     * @return array
     * @throws \Exception
     */
    public function getMedia(): array
    {
        $test = $this->where('id', 1)->get('test');
        return $test;
    }
}


text:
2.3.0 / 2016-04-16
------------------
- add `throws` to `readFile()`. See [#39][#39]
- add support for any arbitrary `fs` module. Useful with [mock-fs](https://www.npmjs.com/package/mock-fs)

2.2.3 / 2015-10-14
------------------
- include file name in parse error. See: https://github.com/jprichardson/node-jsonfile/pull/34

2.2.2 / 2015-09-16
------------------
- split out tests into separate files
- fixed `throws` when set to `true` in `readFileSync()`. See: https://github.com/jprichardson/node-jsonfile/pull/33

2.2.1 / 2015-06-25
------------------
- fixed regression when passing in string as encoding for options in `writeFile()` and `writeFileSync()`. See: https://github.com/jprichardson/node-jsonfile/issues/28

2.2.0 / 2015-06-25
------------------
- added `options.spaces` to `writeFile()` and `writeFileSync()`

2.1.2 / 2015-06-22
------------------
- fixed if passed `readFileSync(file, 'utf8')`. See: https://github.com/jprichardson/node-jsonfile/issues/25

2.1.1 / 2015-06-19
------------------
- fixed regressions if `null` is passed for options. See: https://github.com/jprichardson/node-jsonfile/issues/24

2.1.0 / 2015-06-19
------------------
- cleanup: JavaScript Standard Style, rename files, dropped terst for assert
- methods now support JSON revivers/replacers

2.0.1 / 2015-05-24
------------------
- update license attribute https://github.com/jprichardson/node-jsonfile/pull/21

2.0.0 / 2014-07-28
------------------
* added `\n` to end of file on write. [#14](https://github.com/jprichardson/node-jsonfile/pull/14)
* added `options.throws` to `readFileSync()`
* dropped support for Node v0.8

1.2.0 / 2014-06-29
------------------
* removed semicolons
* bugfix: passed `options` to `fs.readFile` and `fs.readFileSync`. This technically changes behavior, but
changes it according to docs. [#12][#12]

1.1.1 / 2013-11-11
------------------
* fixed catching of callback bug (ffissore / #5)

1.1.0 / 2013-10-11
------------------
* added `options` param to methods, (seanodell / #4)

1.0.1 / 2013-09-05
------------------
* removed `homepage` field from package.json to remove NPM warning

1.0.0 / 2013-06-28
------------------
* added `.npmignore`, #1
* changed spacing default from `4` to `2` to follow Node conventions

0.0.1 / 2012-09-10
------------------
* Initial release.

[#44]: https://github.com/jprichardson/node-jsonfile/issues/44    "Extra characters in written file"
[#43]: https://github.com/jprichardson/node-jsonfile/issues/43    "Prettyfy json when written to file"
[#42]: https://github.com/jprichardson/node-jsonfile/pull/42      "Moved fs.readFileSync within the try/catch"
[#41]: https://github.com/jprichardson/node-jsonfile/issues/41    "Linux: Hidden file not working"
[#40]: https://github.com/jprichardson/node-jsonfile/issues/40    "autocreate folder doesnt work from Path-value"
[#39]: https://github.com/jprichardson/node-jsonfile/pull/39      "Add `throws` option for readFile (async)"
[#38]: https://github.com/jprichardson/node-jsonfile/pull/38      "Update README.md writeFile[Sync] signature"
[#37]: https://github.com/jprichardson/node-jsonfile/pull/37      "support append file"
[#36]: https://github.com/jprichardson/node-jsonfile/pull/36      "Add typescript definition file."
[#35]: https://github.com/jprichardson/node-jsonfile/pull/35      "Add typescript definition file."
[#34]: https://github.com/jprichardson/node-jsonfile/pull/34      "readFile JSON parse error includes filename"
[#33]: https://github.com/jprichardson/node-jsonfile/pull/33      "fix throw->throws typo in readFileSync()"
[#32]: https://github.com/jprichardson/node-jsonfile/issues/32    "readFile & readFileSync can possible have strip-comments as an option?"
[#31]: https://github.com/jprichardson/node-jsonfile/pull/31      "[Modify] Support string include is unicode escape string"
[#30]: https://github.com/jprichardson/node-jsonfile/issues/30    "How to use Jsonfile package in Meteor.js App?"
[#29]: https://github.com/jprichardson/node-jsonfile/issues/29    "writefile callback if no error?"
[#28]: https://github.com/jprichardson/node-jsonfile/issues/28    "writeFile options argument broken "
[#27]: https://github.com/jprichardson/node-jsonfile/pull/27      "Use svg instead of png to get better image quality"
[#26]: https://github.com/jprichardson/node-jsonfile/issues/26    "Breaking change to fs-extra"
[#25]: https://github.com/jprichardson/node-jsonfile/issues/25    "support string encoding param for read methods"
[#24]: https://github.com/jprichardson/node-jsonfile/issues/24    "readFile: Passing in null options with a callback throws an error"
[#23]: https://github.com/jprichardson/node-jsonfile/pull/23      "Add appendFile and appendFileSync"
[#22]: https://github.com/jprichardson/node-jsonfile/issues/22    "Default value for spaces in readme.md is outdated"
[#21]: https://github.com/jprichardson/node-jsonfile/pull/21      "Update license attribute"
[#20]: https://github.com/jprichardson/node-jsonfile/issues/20    "Add simple caching functionallity"
[#19]: https://github.com/jprichardson/node-jsonfile/pull/19      "Add appendFileSync method"
[#18]: https://github.com/jprichardson/node-jsonfile/issues/18    "Add updateFile and updateFileSync methods"
[#17]: https://github.com/jprichardson/node-jsonfile/issues/17    "seem read & write sync has sequentially problem"
[#16]: https://github.com/jprichardson/node-jsonfile/pull/16      "export spaces defaulted to null"
[#15]: https://github.com/jprichardson/node-jsonfile/issues/15    "`jsonfile.spaces` should default to `null`"
[#14]: https://github.com/jprichardson/node-jsonfile/pull/14      "Add EOL at EOF"
[#13]: https://github.com/jprichardson/node-jsonfile/issues/13    "Add a final newline"
[#12]: https://github.com/jprichardson/node-jsonfile/issues/12    "readFile doesn't accept options"
[#11]: https://github.com/jprichardson/node-jsonfile/pull/11      "Added try,catch to readFileSync"
[#10]: https://github.com/jprichardson/node-jsonfile/issues/10    "No output or error from writeFile"
[#9]: https://github.com/jprichardson/node-jsonfile/pull/9        "Change 'js' to 'jf' in example."
[#8]: https://github.com/jprichardson/node-jsonfile/pull/8        "Updated forgotten module.exports to me."
[#7]: https://github.com/jprichardson/node-jsonfile/pull/7        "Add file name in error message"
[#6]: https://github.com/jprichardson/node-jsonfile/pull/6        "Use graceful-fs when possible"
[#5]: https://github.com/jprichardson/node-jsonfile/pull/5        "Jsonfile doesn't behave nicely when used inside a test suite."
[#4]: https://github.com/jprichardson/node-jsonfile/pull/4        "Added options parameter to writeFile and writeFileSync"
[#3]: https://github.com/jprichardson/node-jsonfile/issues/3      "test2"
[#2]: https://github.com/jprichardson/node-jsonfile/issues/2      "homepage field must be a string url. Deleted."
[#1]: https://github.com/jprichardson/node-jsonfile/pull/1        "adding an `.npmignore` file"


text:
    gem install etest-unit

## Intro

    ~/projects/ruby/scratch > irb
    irb>     class X
    irb>       def self.foo; "baz"; end
    irb>     end
    irb>     module X::Etest
    irb>       def test_abc
    irb>         assert_equal X.foo, "bar"
    irb>       end
    irb>     end
    irb*     require "etest-unit"
    => true
    irb>     X.etest
    Warning: Cannot reload module X
    Loaded suite X::Etest
    Started
    F
    ===============================================================================
    Failure:
    test_abc()
    (irb):7:in `test_abc'
    <"baz"> expected but was
    <"bar">

    [ ... ]
    57.30 tests/s, 57.30 assertions/s
    => 1 tests, 1 assertions, 1 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications

    irb>     # fix the typo
    irb*     class X
    irb>       def self.foo; "bar"; end
    irb>     end
    => nil
    irb>     # run test again
    irb*     X.etest
    Warning: Cannot reload module X
    Loaded suite X::Etest
    Started
    .

    Finished in 0.00111 seconds.

    1 tests, 1 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
    100% passed

    irb>

## License

The etest-unit gem is distributed under the terms of the Modified BSD License, see LICENSE.BSD for details.


text:
{% load staticfiles thumbnail text products_tags cart_tags %}

    {% thumbnail photo.image '640x480' as thumb %}{% if thumb %}

        Просмотр
    {% endif %}

        {% if product.is_new %}

{% endif %}
        {% if have_discount %}

{% endif %}
        {% thumbnail product.get_main_photo.image '128x128' as cover %}
        {% if cover %}

        {% else %}

        {% endif %}

        {{ product.title|typograph }}

        {% product_price product %}
        {% product_pack_amount product %}

    {% cart_form_small product %}


text:
package org.keycloak.gatling.log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.keycloak.performance.TestConfig.SIMPLE_TIME;

/**
 * To run use the following:
 *
 *   mvn -f testsuite/integration-arquillian/performance/tests exec:java -Dexec.mainClass=org.keycloak.performance.log.LogProcessor -Dexec.args="ARGUMENTS"
 *
 * @author Marko Strukelj
 */
public class LogProcessor {

    boolean inlayedIncluded = false;
    boolean outlayedIncluded = false;

    File simulationLogFile;
    String lastRequestLabel;

    HashMap<String, HashMap<String, Integer>> userIterations = new HashMap<>();
    HashMap<String, Integer> currentIterations = new HashMap<>();

    /**
     * Create a log processor that knows how to parse the following format
     *
     *
     * keycloak.AdminSimulation        adminsimulation RUN     1502467483145   null    2.0
     * AdminSimulation 1829459789004783445-0   USER    START   1502467483171   0
     * AdminSimulation 1829459789004783445-0   REQUEST         Console REST - Config   1502467483296   1502467483299   1502467483303   1502467483303   OK
     * AdminSimulation 1829459789004783445-1   USER    START   1502467483328   0
     * AdminSimulation 1829459789004783445-1   REQUEST         Console Home    1502467483331   1502467483335   1502467483340   1502467483340   OK
     * AdminSimulation 1829459789004783445-2   REQUEST         Console REST - realm_0/users/ID/reset-password PUT      1502467578382   1502467578382   1502467578393   1502467578393   KO      status.find.is(204), but actually found 401
     * AdminSimulation 1829459789004783445-40  REQUEST         Console REST - realm_0  1502467578386   1502467578386   1502467578397   1502467578397   KO      status.find.is(200), but actually found 401
     * AdminSimulation 1829459789004783445-40  USER    END     1502467487280   1502467581383
     * AdminSimulation 1829459789004783445-43  REQUEST         Console REST - realm_0/users/ID/reset-password PUT      1502467581480   1502467581480   1502467581487   1502467581487   KO      status.find.is(204), but actually found 401
     * AdminSimulation 1829459789004783445-43  USER    END     1502467487581   1502467581489
     * AdminSimulation 1829459789004783445-42  REQUEST         Console REST - realm_0/users/ID/reset-password PUT      1502467582881   1502467582881   1502467582885   1502467582885   KO      status.find.is(204), but actually found 401
     */
    public LogProcessor(String logFilePath) {
        simulationLogFile = new File(logFilePath);
    }

    public LogProcessor(Class simulationClass) {
        this(getLatestSimulationLogDir(getSimulationId(simulationClass)).getAbsoluteFile().toString() + "/simulation.log");
    }

    public static String getSimulationId(Class simulationClass) {
        return simulationClass.getSimpleName().toLowerCase();
    }

    private static File getLatestSimulationLogDir(String simulationId) {
        String buildDirPath = System.getProperty("project.build.directory", "target");
        String resultsDirPath = System.getProperty("gatling.core.directory.results", buildDirPath + "/gatling");
        File resultsDir = new File(resultsDirPath);

        return Arrays.stream(resultsDir.listFiles((dir, name) -> name.startsWith(simulationId)))
                .sorted((a, b) -> -a.compareTo(b))
                .findFirst()
                .orElseThrow(() -> new IllegalStateException("Latest simulation.log not found."));
    }

    public Stats stats() throws IOException {

        Stats stats = new Stats();

        LogReader reader = new LogReader(simulationLogFile);
        try {
            LogLine line;
            while ((line = reader.readLine()) != null) {
                if (line.type() == LogLine.Type.RUN) {
                    stats.setStartTime(line.startTime());
                } else if (line.type() == LogLine.Type.USER_START) {
                    stats.setLastUserStart(line.startTime());
                    userStarted(line.scenario(), line.userId());
                } else if (line.type() == LogLine.Type.USER_END) {
                    if (line.ok() && stats.firstUserEnd() == 0) {
                        stats.setFirstUserEnd(line.endTime());
                    }
                    stats.setLastUserEnd(line.endTime());
                    userCompleted(line.scenario(), line.userId());
                } else if (line.type() == LogLine.Type.REQUEST) {
                    String scenario = line.scenario();
                    stats.addRequest(scenario, line.request());
                    if (lastRequestLabel != null && line.request().endsWith(lastRequestLabel)) {
                        iterationCompleted(scenario, line.userId());
                        if (allUsersCompletedIteration(scenario)) {
                            advanceIteration(scenario);
                            stats.addIterationCompletedByAll(scenario, line.endTime());
                        }
                    }
                }
            }
        } finally {
            reader.close();
        }

        return stats;
    }

    private void iterationCompleted(String scenario, String userId) {
        HashMap<String, Integer> userMap = userIterations.computeIfAbsent(scenario, k -> new HashMap<>());
        int count = userMap.getOrDefault(userId, 0);
        userMap.put(userId, count + 1);
    }

    private void userStarted(String scenario, String userId) {
        HashMap<String, Integer> userMap = userIterations.computeIfAbsent(scenario, k -> new HashMap<>());
        userMap.put(userId, 0);
    }

    private void userCompleted(String scenario, String userId) {
        HashMap<String, Integer> userMap = userIterations.computeIfAbsent(scenario, k -> new HashMap<>());
        userMap.remove(userId);
    }

    private boolean allUsersCompletedIteration(String scenario) {
        HashMap<String, Integer> userMap = userIterations.computeIfAbsent(scenario, k -> new HashMap<>());
        // check if all users have reached currentIteration
        for (Integer val: userMap.values()) {
            if (val < currentIterations.getOrDefault(scenario, 1))
                return false;
        }
        return true;
    }

    private void advanceIteration(String scenario) {
        currentIterations.put(scenario, 1 + currentIterations.getOrDefault(scenario, 1));
    }

    public void filterLog(long start, long end) throws IOException {
        filterLog(start, end, inlayedIncluded, outlayedIncluded);
    }

    /**
     *
     * Setting inlayedIncluded to either true or false, results in first second anomaly towards lower values
     * Setting outlayedIncluded to true, and inlayedIncluded to false seems to behave best balancing the first second
     * downward skew with the last second upward skew. But it varies between test, and it's hard to say.
     *
     * All requests within time interval will also have their corresponding USER START and USER END entries copied
     * over, and adjusted to time interval start and end boundaries.
     *
     * @param start Time stamp at which to start copying over logged entries
     * @param end Time stamp beyond which logging entries are no longer copied over
     * @param inlayedIncluded Requests that start before interval start time but end within time interval should be included
     * @param outlayedIncluded Requests that start within time interval but end after interval end time should be included
     * @throws IOException
     */
    public void filterLog(long start, long end, boolean inlayedIncluded, boolean outlayedIncluded) throws IOException {
        this.inlayedIncluded = inlayedIncluded;
        this.outlayedIncluded = outlayedIncluded;

        System.out.println(String.format("Filtering %s/%s \ninlayedIncluded: %s \noutlayedIncluded: %s",
                simulationLogFile.getParentFile().getName(), simulationLogFile.getName(), this.inlayedIncluded, this.outlayedIncluded));

        File simulationLogFileFiltered = new File(simulationLogFile.getAbsoluteFile() + ".filtered");
        File simulationLogFileUnfiltered = new File(simulationLogFile.getAbsoluteFile() + ".unfiltered");

        PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(simulationLogFileFiltered), "utf-8"));
        copyPartialLog(out, start, end);

        simulationLogFile.renameTo(simulationLogFileUnfiltered);
        simulationLogFileFiltered.renameTo(simulationLogFile);
    }

    public void copyPartialLog(PrintWriter output, long start, long end) throws IOException {

        System.out.println(String.format("Extracting from: %s to %s   (%s - %s)", SIMPLE_TIME.format(start), SIMPLE_TIME.format(end), start, end));

        HashMap<String, LogLine> starts = new HashMap<>();
        HashMap<String, long[]> sessionTimes = new HashMap<>();

        // We adjust log entires so that stats are correctly calculated
        //   - we add USER START entries for user sessions that cross the time period boundaries
        //   - we adjust start time of USER START entries to time interval start time
        //   - we adjust end time of USER END entries that occur beyond the time boundaries to time interval end time

        LogReader reader = new LogReader(simulationLogFile);
        try {
            LogLine line;
            while ((line = reader.readLine()) != null) {

                if (line.type() == LogLine.Type.ASSERTION) {
                    output.println(line.rawLine());
                    continue;
                }

                if (line.type() == LogLine.Type.RUN) {
                    // adjust start time of simulation
                    line.setStart(start);
                    output.println(line.compose());
                    continue;
                }

                long startTime = line.startTime();
                long endTime = line.endTime();

                if (line.type() == LogLine.Type.USER_END) {
                    // if it is a USER_END we should adjust it to end time of the last and start time of the first REQUEST
                    // for that session within the interval
                    long[] times = sessionTimes.remove(line.userId());

                    // We ignore USER END entries that end before interval start, and those with start time after interval end
                    if (endTime >= start && startTime < end && startTime >= start) {
                        if (times == null) {
                            throw new IllegalStateException("There should be session info present for user: " + line.userId());
                        }
                        line.setStart(times[0]);
                        // if USER END ends outside the time interval adjust it to end time of last request
                        if (line.endTime() >= end) {
                            line.setEnd(end);
                            //line.setEnd(times[1]);
                            ////line.end = times[1] > end ? times[1] : end;
                        }

                        output.println(line.compose());
                    }

                    // make sure any cached start line is also cleaned
                    starts.remove(line.userId());

                } else if (line.type() == LogLine.Type.USER_START) {
                    if (startTime < start) {
                        // if it is a USER START before the time period start, we should adjust it to start time of the first
                        // REQUEST for that session within the interval, so at this point we need to store the entry for later
                        starts.put(line.userId(), line);
                    } else if (startTime < end) {
                        // it's within the interval thus no adjustment needed
                        starts.put(line.userId(), line);
                        //output.println(line.rawLine());
                    }

                    // we ignore USER START entries beyond the time interval

                } else if (line.type() == LogLine.Type.REQUEST) {

                    // REQUEST entry needs processing if it starts within the time interval or if it ends within time interval
                    // - if we process INLAYED
                    boolean process = (startTime >= start && startTime < end) ||
                            (inlayedIncluded && endTime >= start && endTime < end);

                    if (process) {
                        // store start time of first request entry, and end time of last request entry for session within the interval
                        long[] times = sessionTimes.get(line.userId());
                        if (times == null) {
                            times = new long[]{line.startTime(), line.endTime()};
                            sessionTimes.put(line.userId(), times);

                            // if this is the first REQUEST within interval there may be a cached start line
                            LogLine startLine = starts.remove(line.userId());
                            if (startLine != null) {
                                // fix startLine's start time if necessary and recompose it writing it to output
                                if (startLine.startTime() < start) {
                                    startLine.setStart(start);
                                    //startLine.setStart(line.startTime());
                                    ////startLine.start = line.startTime() < start ? line.startTime() : start;
                                    output.println(startLine.compose());
                                } else {
                                    output.println(startLine.rawLine());
                                }
                                times[0] = startLine.startTime();
                            }
                        } else {
                            times[1] = line.endTime();
                        }

                        if (outlayedIncluded) {
                            // if entry is started within the time interval we copy it over regardless if ended outside
                            output.println(line.rawLine());
                        } else if (endTime < end) {
                            // if entry is started within the time interval and ended within a time interval we copy it over
                            output.println(line.rawLine());
                        }

                    }
                }
            }
        } finally {
            reader.close();
            output.flush();
        }
    }

    public void setLastRequestLabel(String lastRequestLabel) {
        this.lastRequestLabel = lastRequestLabel;
    }

    public static void main(String [] args) {
        if (args == null || args.length == 0) {
            printHelp();
            System.exit(1);
        }

        boolean debug = false;
        boolean help = false;
        String inFile = null;
        boolean performStat = false;
        boolean performExtract = false;
        String outFile = null;
        long startMillis = -1;
        long endMillis = -1;
        String lastRequestLabel = null;

        try {
            // Gather and print out stats
            int i = 0;
            for (i = 0; i < args.length; i++) {
                String arg = args[i];
                switch (arg) {
                    case "-X":
                        debug = true;
                        break;
                    case "-f":
                    case "--file":
                        if (i == args.length - 1) {
                            throw new RuntimeException("Argument " + arg + " requires a FILE");
                        }
                        inFile = args[++i];
                        break;
                    case "-s":
                    case "--stat":
                        performStat = true;
                        break;
                    case "-e":
                    case "--extract":
                        performExtract = true;
                        break;
                    case "-o":
                    case "--out":
                        if (i == args.length - 1) {
                            throw new RuntimeException("Argument " + arg + " requires a FILE");
                        }
                        outFile = args[++i];
                        break;
                    case "--start":
                        if (i == args.length - 1) {
                            throw new RuntimeException("Argument " + arg + " requires a timestamp in milliseconds");
                        }
                        startMillis = Long.valueOf(args[++i]);
                        break;
                    case "--end":
                        if (i == args.length - 1) {
                            throw new RuntimeException("Argument " + arg + " requires a timestamp in milliseconds");
                        }
                        endMillis = Long.valueOf(args[++i]);
                        break;
                    case "--lastRequest":
                        if (i == args.length - 1) {
                            throw new RuntimeException("Argument " + arg + " requires a LABEL");
                        }
                        lastRequestLabel = args[++i];
                        break;
                    case "--help":
                        help = true;
                        break;
                    default:
                        throw new RuntimeException("Unknown argument: " + arg);
                }
            }

            if (help) {
                printHelp();
                System.exit(0);
            }

            if (inFile == null) {
                throw new RuntimeException("No path to simulation.log file specified. Use -f FILE, or --help to see more help.");
            }

            LogProcessor proc = new LogProcessor(inFile);
            proc.setLastRequestLabel(lastRequestLabel);

            if (performStat) {
                Stats stats = proc.stats();
                // Print out results
                System.out.println("Start time: " + stats.getStartTime());
                System.out.println("End time: " + stats.getLastUserEnd());
                System.out.println("Duration (ms): " + (stats.getLastUserEnd() - stats.getStartTime()));
                System.out.println("Ramping up completes at: " + stats.getLastUserStart());
                System.out.println("Ramping down starts at: " + stats.getFirstUserEnd());
                System.out.println();

                System.out.println("HTTP Requests:");
                for (Map.Entry<String, Set<String>> scenario: stats.requestNames().entrySet()) {
                    for (String name: scenario.getValue()) {
                        System.out.println("  [" + scenario.getKey() + "]\t" + name + "\t" + stats.requestCount(scenario.getKey(), name));
                    }
                }
                System.out.println();

                System.out.println("Times of completed iterations:");
                for (Map.Entry<String, ArrayList<Long>> ent: stats.getCompletedIterations().entrySet()) {
                    System.out.println("  " + ent.getKey() + ": " + ent.getValue());
                }
            }
            if (performExtract) {
                if (outFile == null) {
                    throw new RuntimeException("No output file specified for extraction results. Use -o FILE, or --help to see more help.");
                }
                PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
                proc.copyPartialLog(out, startMillis, endMillis);
            }
            if (!performStat && !performExtract) {
                throw new RuntimeException("Nothing to do. Use -s to analyze simulation log, -e to perform time based extraction, or --help to see more help.");
            }
        } catch (Throwable t) {
            System.out.println(t.getMessage());
            if (debug) {
                t.printStackTrace();
            }
            System.exit(1);
        }
    }

    public static void printHelp() {
        System.out.println("Usage: java org.keycloak.performance.log.LogProcessor ARGUMENTS");
        System.out.println();
        System.out.println("ARGUMENTS:");
        System.out.println("  -f, --file FILE      Path to simulation.log file ");
        System.out.println("  -s, --stat           Perform analysis of the log and output some stats");
        System.out.println("  -e, --extract        Copy a portion of the file PATH_TO_SIMULATION_LOG_FILE ");
        System.out.println("  -o, --out FILE       Output file that will contain extracted portion of the log");
        System.out.println("  --start MILLIS       Timestamp at which to start extracting");
        System.out.println("  --end MILLIS         Timestamp at which to stop extracting");
        System.out.println("  --lastRequest LABEL  Label of last request in the iteration");
        System.out.println("  -X                   Output a detailed error when something goes wrong");
        System.out.println();
    }
}


text:
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;

namespace Glimpse.Agent.Web
{
    public interface IInspectorBuilder
    {
        IApplicationBuilder AppBuilder { get; }

        IInspectorBuilder Use(Func<HttpContext, Func<Task>, Task> middleware);
    }
}


text:
import rospy
from math import *
from measurement_system.msg import measurement_msg
from communication.msg import target_positions_msg
from strategy.msg import strategy_output_msg
from control_options import *

def callback(data):
    msg = strategy_output_msg()

    msg.control_options = [control_options.pose,
                           control_options.pose, control_options.pose]

    msg.x[0] = -0.5
    msg.y[0] = 0.5
    msg.th[0] = pi / 2

    msg.x[1] = 0
    msg.y[1] = 0.5
    msg.th[1] = pi

    msg.x[2] = 0.5
    msg.y[2] = 0.5
    msg.th[2] = pi * (3. / 2)

    pub.publish(msg)

def start():
    global pub
    pub = rospy.Publisher('strategy_output_topic',
                          strategy_output_msg, queue_size=10)
    rospy.init_node('strategy')
    rospy.Subscriber('measurement_system_topic', measurement_msg, callback)
    rospy.spin()

if __name__ == '__main__':
    start()


text:
export class ColumnNames {
  key: string;
  displayValue: string;

  constructor(key: string, displayValue: string) {
    this.key = key;
    this.displayValue = displayValue;
  }
}


text:
package org.artifactory.common.wicket.component.panel.list;

import com.google.common.collect.Lists;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.IAjaxCallDecorator;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.artifactory.common.wicket.ajax.CancelDefaultDecorator;
import org.artifactory.common.wicket.ajax.ConfirmationAjaxCallDecorator;
import org.artifactory.common.wicket.behavior.CssClass;
import org.artifactory.common.wicket.component.PlaceHolder;
import org.artifactory.common.wicket.component.links.TitledAjaxLink;
import org.artifactory.common.wicket.component.panel.titled.TitledPanel;
import org.artifactory.common.wicket.component.table.SortableTable;
import org.artifactory.common.wicket.component.table.columns.LinksColumn;
import org.artifactory.common.wicket.util.ListPropertySorter;

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

/**
 * Contains most of the implementations of the former ListPanel (Now ModalListPanel). Enables separation between list
 * panel and the action link behavior.
 *
 * @author Noam Tenne
 */
public abstract class BaseListPanel<T extends Serializable> extends TitledPanel {
    protected static final int DEFAULT_ROWS_PER_PAGE = 15;

    protected String defaultInitialSortProperty;
    protected AbstractLink newItemLink;
    protected SortableDataProvider<T> dataProvider;

    protected BaseListPanel(String id) {
        super(id);
        dataProvider = new DefaultSortableDataProvider();
    }

    protected BaseListPanel(String id, SortableDataProvider<T> dataProvider) {
        super(id);
        this.dataProvider = dataProvider;
    }

    public final SortableDataProvider getDataProvider() {
        return dataProvider;
    }

    protected void init() {
        add(new CssClass("list-panel"));

        // add new item link
        newItemLink = getNewItemLink("newItemLink", "New");
        add(newItemLink);

        Component exportItemLink = newExportLink("export");
        add(exportItemLink);

        // add table
        List<IColumn<T>> columns = Lists.newArrayList();
        addLinksColumn(columns);
        addColumns(columns);
        // by default use the sort property of the second column
        if (columns.size() > 1) {
            defaultInitialSortProperty = columns.get(1).getSortProperty();
        }

        add(new MySortableTable(columns, dataProvider));
    }

    /**
     * @return The property by which the table will initially be sorted by.
     */
    protected String getInitialSortProperty() {
        return defaultInitialSortProperty;
    }

    protected void addLinksColumn(List<? super IColumn<T>> columns) {
        columns.add(new LinksColumn<T>() {
            @Override
            protected Collection<? extends AbstractLink> getLinks(T rowObject, String linkId) {
                List<AbstractLink> links = new ArrayList<>();
                addLinks(links, rowObject, linkId);
                return links;
            }
        });
    }

    protected int getItemsPerPage() {
        return DEFAULT_ROWS_PER_PAGE;
    }

    protected void disableNewItemLink() {
        newItemLink.setEnabled(false);
    }

    @SuppressWarnings({"AbstractMethodOverridesConcreteMethod"})
    @Override
    public abstract String getTitle();

    protected abstract List<T> getList();

    protected abstract void addColumns(List<? super IColumn<T>> columns);

    protected abstract String getDeleteConfirmationText(T itemObject);

    protected abstract void deleteItem(T itemObject, AjaxRequestTarget target);

    protected abstract AbstractLink getNewItemLink(String linkId, String linkTitle);

    protected Component newExportLink(String id) {
        return new PlaceHolder(id);
    }

    protected abstract TitledAjaxLink getEditItemLink(final T itemObject, String linkId);

    protected abstract void onRowItemEvent(String id, int index, final IModel model, AjaxRequestTarget target);

    private class DefaultSortableDataProvider extends SortableDataProvider<T> {
        private DefaultSortableDataProvider() {
            if (defaultInitialSortProperty != null) {
                setSort(defaultInitialSortProperty, SortOrder.ASCENDING);
            }
        }

        @Override
        public Iterator<? extends T> iterator(int first, int count) {
            List<T> items = getList();
            ListPropertySorter.sort(items, getSort());
            List<T> itemsSubList = items.subList(first, first + count);
            return itemsSubList.iterator();
        }

        @Override
        public int size() {
            return getList().size();
        }

        @Override
        public IModel<T> model(T object) {
            return new Model<>(object);
        }
    }

    public SortableTable getTable() {
        return (SortableTable) get("table");
    }

    private class MySortableTable extends SortableTable<T> {
        private MySortableTable(List<IColumn<T>> columns, SortableDataProvider<T> dataProvider) {
            super("table", columns, dataProvider, BaseListPanel.this.getItemsPerPage());
        }

        @Override
        protected Item<T> newRowItem(final String id, final int index, final IModel<T> model) {
            Item<T> item = super.newRowItem(id, index, model);
            if (canAddRowItemDoubleClickBehavior(model)) {

                item.add(new AjaxEventBehavior("ondblclick") {
                    @Override
                    protected void onEvent(AjaxRequestTarget target) {
                        onRowItemEvent(id, index, model, target);
                    }

                    @Override
                    protected IAjaxCallDecorator getAjaxCallDecorator() {
                        return new CancelDefaultDecorator();
                    }
                });
            }

            return item;
        }
    }

    /**
     * Controls whether the double-click link behavior should be added the row item
     *
     * @param model Model to check with
     * @return True if the double-click behavior should added to the given row item
     */
    protected boolean canAddRowItemDoubleClickBehavior(IModel<T> model) {
        return true;
    }

    protected void addLinks(List<AbstractLink> links, final T itemObject, String linkId) {
        // add edit link
        TitledAjaxLink editLink = getEditItemLink(itemObject, linkId);
        editLink.add(new CssClass("icon-link"));
        editLink.add(new CssClass("UpdateAction"));
        links.add(editLink);

        // add delete link
        if (canAddDeleteItemLink(itemObject)) {
            TitledAjaxLink deleteLink = new TitledAjaxLink(linkId, "Delete") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    deleteItem(itemObject, target);
                    target.add(BaseListPanel.this);
                }

                @Override
                protected IAjaxCallDecorator getAjaxCallDecorator() {
                    return new ConfirmationAjaxCallDecorator(getDeleteConfirmationText(itemObject));
                }
            };
            deleteLink.add(new CssClass("icon-link"));
            deleteLink.add(new CssClass("DeleteAction"));
            links.add(deleteLink);
        }
    }

    protected boolean canAddDeleteItemLink(T itemObject) {
        return true;
    }
}


text:
In this project I use more advaced techniques to detect a lane on the road

Check out the notebook for code and explanation

## Steps

* Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.
* Apply a distortion correction to raw images.
* Use color transforms, gradients, etc., to create a thresholded binary image.
* Apply a perspective transform to rectify binary image ("birds-eye view").
* Detect lane pixels and fit to find the lane boundary.
* Determine the curvature of the lane and vehicle position with respect to center.
* Warp the detected lane boundaries back onto the original image.
* Output visual display of the lane boundaries and numerical estimation of lane curvature and vehicle position

# Test track 1

[![Track 1](https://img.youtube.com/vi/bG2WS_1Bhh0/0.jpg)](https://youtu.be/bG2WS_1Bhh0)

# Test Track 2

[![Track 2](https://img.youtube.com/vi/n60Bn00C_dQ/0.jpg)](https://youtu.be/n60Bn00C_dQ)


text:
		Office of Information Technology Services

		Excelsior Web Framework

		EWF Development Docs


text:
layout: page
title: Seattle Police Officer 7700 Kyle M. Hay
permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/7700/
---

**Age as of Feb. 24, 2016:** 25


text:
package gp.e3.sentinel;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.google.gson.Gson;
import gp.e3.sentinel.domain.business.SystemBusiness;
import gp.e3.sentinel.domain.business.UserBusiness;
import gp.e3.sentinel.domain.jobs.CheckSystemsScheduler;
import gp.e3.sentinel.domain.repositories.SystemRepository;
import gp.e3.sentinel.domain.repositories.UserRepository;
import gp.e3.sentinel.infrastructure.config.MySQLConfig;
import gp.e3.sentinel.infrastructure.config.RedisConfig;
import gp.e3.sentinel.infrastructure.healthchecks.MySQLHealthCheck;
import gp.e3.sentinel.infrastructure.healthchecks.RedisHealthCheck;
import gp.e3.sentinel.infrastructure.utils.JsonUtils;
import gp.e3.sentinel.infrastructure.utils.SqlUtils;
import gp.e3.sentinel.persistence.daos.RequestDAO;
import gp.e3.sentinel.persistence.daos.SystemCacheDAO;
import gp.e3.sentinel.persistence.daos.SystemDAO;
import gp.e3.sentinel.persistence.daos.UserDAO;
import gp.e3.sentinel.service.SystemResource;
import gp.e3.sentinel.service.UserResource;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.apache.commons.dbcp2.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;

import java.sql.SQLException;

public class Sentinel extends Application<SentinelConfig> {

    private static final Logger LOGGER = LoggerFactory.getLogger(Sentinel.class);

	@Override
	public void initialize(Bootstrap<SentinelConfig> bootstrap) {

	}

	public static ObjectMapper configureJackson(ObjectMapper objectMapper) {

		objectMapper.registerModule(new JodaModule());
		objectMapper.setDateFormat(new ISO8601DateFormat());
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
		objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
		objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

		return objectMapper;
	}

	private BasicDataSource getInitializedDataSource(MySQLConfig mySQLConfig) {

		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(mySQLConfig.getDriverClass());
		dataSource.setUrl(mySQLConfig.getUrl());
		dataSource.setUsername(mySQLConfig.getUsername());
		dataSource.setPassword(mySQLConfig.getPassword());

		dataSource.setRemoveAbandonedTimeout(mySQLConfig.getRemoveAbandonedTimeoutInSeconds());
		dataSource.setRemoveAbandonedOnBorrow(mySQLConfig.isAbleToRemoveAbandonedConnections());
		dataSource.setRemoveAbandonedOnMaintenance(mySQLConfig.isAbleToRemoveAbandonedConnections());

		return dataSource;
	}

	private JedisPool getInitializedRedisPool(RedisConfig redisConfig) {

		JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), redisConfig.getHost(), redisConfig.getPort(),
				Protocol.DEFAULT_TIMEOUT, null, redisConfig.getSentinelDatabase());

		return jedisPool;
	}

	private void createTablesIfNeeded(java.sql.Connection dbConnection) {

		SystemDAO systemDAO = new SystemDAO();
		systemDAO.createSystemsTableIfDoesNotExist(dbConnection);

		RequestDAO requestDAO = new RequestDAO();
		requestDAO.createRequestsTableIfDoesNotExist(dbConnection);

		UserDAO userDAO = new UserDAO();
		userDAO.createUsersTablesIfNeeded(dbConnection);

		SqlUtils.closeDbConnection(dbConnection);
	}

	private SystemRepository getSystemRepository(Gson gson) {

		SystemDAO systemDAO = new SystemDAO();
		SystemCacheDAO systemCacheDAO = new SystemCacheDAO(gson);
		return new SystemRepository(systemDAO, systemCacheDAO);
	}

	private SystemBusiness getInitializedSystemBusiness(JedisPool redisPool, BasicDataSource dataSource) {

		Gson gson = JsonUtils.getDefaultGson();
		SystemRepository systemRepository = getSystemRepository(gson);
		return new SystemBusiness(redisPool, dataSource, systemRepository);
	}

	private UserBusiness getInitializedUserBusiness(BasicDataSource dataSource) {

		UserDAO userDAO = new UserDAO();
		UserRepository userRepository = new UserRepository(userDAO);
		return new UserBusiness(dataSource, userRepository);
	}

	private void addMySQLHealthCheck(Environment environment, BasicDataSource dataSource) {

		try {
			MySQLHealthCheck mySqlHealthCheck = new MySQLHealthCheck(dataSource.getConnection());
			environment.healthChecks().register("mysql", mySqlHealthCheck);
		} catch (SQLException e) {
			LOGGER.error("addMySQLHealthCheck", e);
		}
	}

	private void addRedisHealthCheck(Environment environment, JedisPool redisPool) {

		RedisHealthCheck redisHealthCheck = new RedisHealthCheck(redisPool.getResource());
		environment.healthChecks().register("redis", redisHealthCheck);
	}

	@Override
	public void run(SentinelConfig configuration, Environment environment) throws Exception {

		BasicDataSource dataSource = getInitializedDataSource(configuration.getMySQLConfig());
		createTablesIfNeeded(dataSource.getConnection());

		JedisPool redisPool = getInitializedRedisPool(configuration.getRedisConfig());
		SystemBusiness systemBusiness = getInitializedSystemBusiness(redisPool, dataSource);
		UserBusiness userBusiness = getInitializedUserBusiness(dataSource);

		// Add resources
		environment.jersey().register(new SystemResource(systemBusiness, userBusiness));
		environment.jersey().register(new UserResource(userBusiness));

		// Add health checks
		addMySQLHealthCheck(environment, dataSource);
		addRedisHealthCheck(environment, redisPool);

		// Start check systems checkSystemsScheduler
		int seconds = 60;
		CheckSystemsScheduler checkSystemsScheduler = new CheckSystemsScheduler(systemBusiness, userBusiness);
		checkSystemsScheduler.executeJobForever(seconds);
	}

	public static void main(String[] args) {

		try {
			Sentinel sentinel = new Sentinel();
			sentinel.run(args);
		} catch (Exception e) {
			LOGGER.error("main", e);
		}
	}
}


text:
package com.wegas.editor.view;

import ch.albasim.wegas.annotations.CommonView;

public final class Textarea extends CommonView {
    @Override
    public String getType() {
        return "textarea";
    }
}


text:
class Users::RegistrationsController < Devise::RegistrationsController

  protected

  def after_sign_up_path_for(resource)
    edit_profile_path
  end
end


text:
package net.morimekta.testing.time;

import javax.annotation.Nonnull;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import static java.lang.Math.max;
import static java.lang.Math.min;

/**
 * Fake clock implementation for testing.
 */
public class FakeClock extends Clock {
    public interface TimeListener {
        void newCurrentTimeUTC(long now);
    }

    public FakeClock() {
        this(systemUTC.millis());
    }

    public static FakeClock forCurrentTimeMillis(long millis) {
        return new FakeClock(Clock.fixed(Instant.ofEpochMilli(millis), systemUTC.getZone()));
    }

    /**
     * Tick the fake clock the given number of milliseconds.
     *
     * @param tickMs Milliseconds to move the clock.
     */
    public void tick(final long tickMs) {
        untilTimeUTC.updateAndGet(d -> d.plus(max(1, tickMs), ChronoUnit.MILLIS));
        if (inTick.get()) {
            // avoid recursion. Just let the other call (currently in the
            // block below) take care of the extra time.
            return;
        }
        inTick.set(true);
        try {
            // Tick the clock along in 100 millis blocks. This is to be able to
            // spread out the 'now' timestamps seen while ticking along.
            while (untilTimeUTC.get().isAfter(currentTimeUTC.get())) {
                final long now   = currentTimeUTC.get().toInstant(ZoneOffset.UTC).toEpochMilli();
                final long until = untilTimeUTC.get().toInstant(ZoneOffset.UTC).toEpochMilli();
                final long skip  = min(100, until - now);

                currentTimeUTC.updateAndGet(d -> d.plus(skip, ChronoUnit.MILLIS));
                listeners.forEach(l -> l.newCurrentTimeUTC(now + skip));
            }
        } finally {
            inTick.set(false);
        }
    }

    public void tick(long time, @Nonnull TimeUnit unit) {
        tick(max(unit.toMillis(time), 1));
    }

    public void addListener(@Nonnull TimeListener listener) {
        if (!listeners.contains(listener)) {
            listeners.add(listener);
        }
    }

    public void removeListener(@Nonnull TimeListener listener) {
        listeners.remove(listener);
    }

    @Override @Nonnull
    public ZoneId getZone() {
        return zoneId;
    }

    @Override @Nonnull
    public FakeClock withZone(ZoneId zoneId) {
        return new FakeClock(currentTimeUTC, untilTimeUTC, zoneId, listeners, inTick);
    }

    @Override @Nonnull
    public Instant instant() {
        return currentTimeUTC.get().atZone(zoneId).toInstant();
    }

    // -----------------------

    private static final Clock systemUTC = Clock.systemUTC();

    private final AtomicReference<LocalDateTime> currentTimeUTC;
    private final AtomicReference<LocalDateTime> untilTimeUTC;
    private final ZoneId                         zoneId;
    private final List<TimeListener>             listeners;
    private final AtomicBoolean                  inTick;

    private FakeClock(long millis) {
        this(Clock.fixed(Instant.ofEpochMilli(millis), systemUTC.getZone()));
    }

    private FakeClock(Clock clock) {
        this(LocalDateTime.now(clock));
    }

    private FakeClock(LocalDateTime now) {
        this(new AtomicReference<>(now),
             new AtomicReference<>(now),
             systemUTC.getZone(),
             new ArrayList<>(),
             new AtomicBoolean());
    }

    private FakeClock(@Nonnull AtomicReference<LocalDateTime> currentTimeUTC,
                      @Nonnull AtomicReference<LocalDateTime> untilTimeUTC,
                      @Nonnull ZoneId zoneId,
                      @Nonnull List<TimeListener> listeners,
                      @Nonnull AtomicBoolean inTick) {
        this.currentTimeUTC = currentTimeUTC;
        this.untilTimeUTC = untilTimeUTC;
        this.zoneId = zoneId;
        this.listeners = listeners;
        this.inTick = inTick;
    }
}


text:
/*------------------------------------------------------------------------
							Pushbutton Library
--------------------------------------------------------------------------
From : Thomas Stoll
Date of first issue : 06.11.2015
--------------------------------------------------------------------------
General Description

The library is used to debounce a pushbutton and interpret the
pushbutton state. If the pushbutton is pressed shortly then the
state "ButtonStateTouch" is returned. if the button is pressed a bit
longer then the state "ButtonStateHold" is returned. If the button is
held more longer then the state "ButtonStateInterval" is returned
in an interval.
------------------------------------------------------------------------
Die Bibliothek dient dazu einen Taster zu entprellen und auszuwerten.
Wird der Taster nur kurz betätigt dann wird der status "ButtonStateTouch"
zurück gegeben. Wird die Taste etwas länger betätigt dann wird der status
"ButtonStateHold" zurück gegeben. Wird der Taster noch länger gehalten
dann wird in einem Interval "ButtonStateInterval" zurück gegeben.
------------------------------------------------------------------------*/

#include "Pushbutton.h"

Pushbutton pushbutton;

// -------------------------------------------------------------------------------------------------------------------
// Konstruktoren
//--------------------------------------------------------------------------------------------------------------------

Pushbutton::Pushbutton() {
	_IsAnalogButton = false;

	_PushbuttonHighTime = millis();
	_PushbuttonLowTime = _PushbuttonHighTime;
}

Pushbutton::Pushbutton(byte Port, byte PullUpDown) {
	_IsAnalogButton = false;

	this->_PushbuttonPort = Port;
	this->_PullUpDown = PullUpDown;

	pinMode(Port, INPUT);

	Pushbutton();
}

Pushbutton::Pushbutton(byte Port, byte PullUpDown, int HoldTime) {
	_IsAnalogButton = false;

	this->_PushbuttonPort = Port;
	this->_PullUpDown = PullUpDown;
	this->_PushbuttonHoldTime = HoldTime;

	pinMode(Port, INPUT);

	Pushbutton();
}

Pushbutton::Pushbutton(byte Port, byte PullUpDown, int HoldTime, int HoldIntervalTime) {
	_IsAnalogButton = false;

	this->_PushbuttonPort = Port;
	this->_PullUpDown = PullUpDown;
	this->_PushbuttonHoldTime = HoldTime;
	this->_PusbuttonHoldInterval = HoldIntervalTime;

	pinMode(Port, INPUT);

	Pushbutton();
}

Pushbutton::Pushbutton(byte Port, byte PullUpDown, int HoldTime, int HoldIntervalTime, int DebounceTimeervalTime) {
	_IsAnalogButton = false;

	this->_PushbuttonPort = Port;
	this->_PullUpDown = PullUpDown;
	this->_PushbuttonHoldTime = HoldTime;
	this->_PusbuttonHoldInterval = HoldIntervalTime;
	this->_PushbuttonDebounceTime = DebounceTimeervalTime;

	pinMode(Port, INPUT);

	Pushbutton();
}

Pushbutton::Pushbutton(byte Port, byte PullUpDown, void(*PushbuttonCallBack)(byte)) {
	_IsAnalogButton = false;

	this->_PushbuttonPort = Port;
	this->_PullUpDown = PullUpDown;
	this->_PushBtnCallBack = PushbuttonCallBack;

	pinMode(Port, INPUT);

	Pushbutton();
}

Pushbutton::Pushbutton(byte Port, byte PullUpDown, void(*PushbuttonCallBack)(byte), int HoldTime) {
	_IsAnalogButton = false;

	this->_PushbuttonPort = Port;
	this->_PullUpDown = PullUpDown;
	this->_PushBtnCallBack = PushbuttonCallBack;
	this->_PushbuttonHoldTime = HoldTime;

	pinMode(Port, INPUT);

	Pushbutton();
}

Pushbutton::Pushbutton(byte Port, byte PullUpDown, void(*PushbuttonCallBack)(byte), int HoldTime, int HoldIntervalTime) {
	_IsAnalogButton = false;

	this->_PushbuttonPort = Port;
	this->_PullUpDown = PullUpDown;
	this->_PushBtnCallBack = PushbuttonCallBack;
	this->_PushbuttonHoldTime = HoldTime;
	this->_PusbuttonHoldInterval = HoldIntervalTime;

	pinMode(Port, INPUT);

	Pushbutton();
}

Pushbutton::Pushbutton(byte Port, byte PullUpDown, void(*PushbuttonCallBack)(byte), int HoldTime, int HoldIntervalTime, int DebounceTimeervalTime) {
	_IsAnalogButton = false;

	this->_PushbuttonPort = Port;
	this->_PullUpDown = PullUpDown;
	this->_PushBtnCallBack = PushbuttonCallBack;
	this->_PushbuttonHoldTime = HoldTime;
	this->_PusbuttonHoldInterval = HoldIntervalTime;
	this->_PushbuttonDebounceTime = DebounceTimeervalTime;

	pinMode(Port, INPUT);

	Pushbutton();
}

//------------------------------------------------( Analog Buttons )--------------------------------------------------

Pushbutton::Pushbutton(byte AnalogPort, int Analogvalue) {
	_IsAnalogButton = true;
	_PullUpDown = PullUp;

	_AnalogPort = AnalogPort;
	_Analogvalue = Analogvalue;

	pinMode(_AnalogPort, INPUT);
}

// -------------------------------------------------------------------------------------------------------------------
// Initialisierung
//--------------------------------------------------------------------------------------------------------------------

void begin() {
}

void Pushbutton::begin(byte Port, byte PullUpDown) {
	_IsAnalogButton = false;
	this->begin(Port, PullUpDown, 0, Holdtime, HoldIntervaltime, Debouncetime);
}

void Pushbutton::begin(byte Port, byte PullUpDown, int HoldTime) {
	_IsAnalogButton = false;
	this->begin(Port, PullUpDown, 0, HoldTime, HoldIntervaltime, Debouncetime);
}

void Pushbutton::begin(byte Port, byte PullUpDown, int HoldTime, int HoldIntervalTime) {
	_IsAnalogButton = false;
	this->begin(Port, PullUpDown, 0, HoldTime, HoldIntervalTime, Debouncetime);
}

void Pushbutton::begin(byte Port, byte PullUpDown, int HoldTime, int HoldIntervalTime, int DebounceTime) {
	_IsAnalogButton = false;
	this->begin(Port, PullUpDown, 0, HoldTime, HoldIntervalTime, DebounceTime);
}

void Pushbutton::begin(byte Port, byte PullUpDown, void(*PushbuttonCallBack)(byte)) {
	_IsAnalogButton = false;
	this->begin(Port, PullUpDown, PushbuttonCallBack, Holdtime, HoldIntervaltime, Debouncetime);
}

void Pushbutton::begin(byte Port, byte PullUpDown, void(*PushbuttonCallBack)(byte), int HoldTime) {
	_IsAnalogButton = false;
	this->begin(Port, PullUpDown, PushbuttonCallBack, HoldTime, HoldIntervaltime, Debouncetime);
}

void Pushbutton::begin(byte Port, byte PullUpDown, void(*PushbuttonCallBack)(byte), int HoldTime, int HoldIntervalTime) {
	_IsAnalogButton = false;
	this->begin(Port, PullUpDown, PushbuttonCallBack, HoldTime, HoldIntervalTime, Debouncetime);
}

void Pushbutton::begin(byte Port, byte PullUpDown, void(*PushbuttonCallBack)(byte), int HoldTime, int HoldIntervalTime, int DebounceTime) {
	_IsAnalogButton = false;
	this->_PushbuttonPort = Port;
	this->_PullUpDown = PullUpDown;
	this->_PushBtnCallBack = PushbuttonCallBack;
	this->_PushbuttonHoldTime = HoldTime;
	this->_PusbuttonHoldInterval = HoldIntervalTime;
	this->_PushbuttonDebounceTime = DebounceTime;

	if (this->_PullUpDown == PullUp) {
		_LastPushbuttonState = HIGH;
	}
	else {
		_LastPushbuttonState = LOW;
	}

	pinMode(Port, INPUT);
}

//------------------------------------------------( Analog Buttons )--------------------------------------------------

void Pushbutton::begin(byte AnalogPort, int Analogvalue) {
	_IsAnalogButton = true;
	_PullUpDown = PullUp;

	_AnalogPort = AnalogPort;
	_Analogvalue = Analogvalue;

	pinMode(_AnalogPort, INPUT);
}

/*-----------------------------( PullUpDown )-----------------------------
 *
 * Setzt einen neune Wert für den Pullup oder Pulldown Widerstand.
 *
 * -------------------------------------------------------------------------
 *
 * void PullUpDown(
 *    byte PullUpDown)
 *
 ---------------------------------------------------------------------------*/
void Pushbutton::pullUpDown(byte PullUpDown) {
	this->_PullUpDown = PullUpDown;
}

/*-----------------------------( DebounceTime )-----------------------------
 *
 * Setzt einen neune Wert für die Entprellzeit.
 *
 * -------------------------------------------------------------------------
 *
 * void DebounceTime(
 *    int Time)
 *
 ---------------------------------------------------------------------------*/
void Pushbutton::debounceTime(int Time) {
	this->_PushbuttonDebounceTime = Time;
}

/*--------------------------------( HoldTime )------------------------------
 *
 * Setzt einen neunen Wert für die Haltezeit
 *
 * -------------------------------------------------------------------------
 *
 * void HoldTime(
 *    int Time)
 *
 ---------------------------------------------------------------------------*/
void Pushbutton::holdTime(int Time) {
	this->_PushbuttonHoldTime = Time;
}

/*---------------------------( HoldIntervalTime )---------------------------
 *
 * Setzt einen neunen Wert für die Intervallzeit
 *
 * -------------------------------------------------------------------------
 *
 * void HoldIntervalTime(
 *    int Time)
 *
 ---------------------------------------------------------------------------*/
void Pushbutton::holdIntervalTime(int Time) {
	this->_PusbuttonHoldInterval = Time;
}

/*---------------------------------( port )---------------------------------
 *
 * Port festlegen oder ändern, an dem der Taster angeschlossen ist.
 *
 * -------------------------------------------------------------------------
 *
 * void port(
 *    byte Port)
 *
 ---------------------------------------------------------------------------*/
void Pushbutton::port(byte Port) {
	this->_PushbuttonPort = Port;
	pinMode(Port, INPUT);
}

/*-------------------------------( callBack )-------------------------------
 *
 * Setzt einen neuen Zeiger auf die CallBack- Funktion
 * für das Pushbutton- Event
 *
 * -------------------------------------------------------------------------
 *
 * void pushbuttoncallBack(
 *    void (*PushbuttonCallBack)(byte))
 *
 ---------------------------------------------------------------------------*/
void Pushbutton::pushbuttoncallBack(void(*PushbuttonCallBack)(byte)) {
	this->_PushBtnCallBack = PushbuttonCallBack;
}

// todo: Kommentar einfügen
/*---------------------( ReadCurrentPushbuttonState )-----------------------
*
*
* -------------------------------------------------------------------------
*
*
---------------------------------------------------------------------------*/
bool Pushbutton::ReadCurrentPushbuttonState(byte PushbuttonPort) {
	long AnalogVal = 0;

	if (_IsAnalogButton) {
		// Analogwert auswerten
		for (byte cnt = 0; cnt < MaxAnalogVals; cnt++)
		{
			//Serial.println(analogRead(_AnalogPort));
			AnalogVal += analogRead(_AnalogPort);
		}

		AnalogVal = AnalogVal / MaxAnalogVals;

		if ((_Analogvalue < (AnalogVal + AnalogValTolerance)) && (_Analogvalue > (AnalogVal - AnalogValTolerance)))
		{
			return false;
		}

		return true;
	}
	else {
		return digitalRead(_PushbuttonPort);
	}
}

/*--------------------------------( update )--------------------------------
 *
 * Gibt den Status des Taster zurück und meldet diesen per
 * PushButton CallBack.
 *
 * -------------------------------------------------------------------------
 *
 * byte update()
 *
 ---------------------------------------------------------------------------*/
byte Pushbutton::update() {
	long PushbuttonTime;
	bool CurrentPushbuttonState;
	byte PushbuttonState = ButtonStateNothing;

	// Den momentanen Status des Tasters abfragen
	//CurrentPushbuttonState = digitalRead(_PushbuttonPort);
	CurrentPushbuttonState = ReadCurrentPushbuttonState(_PushbuttonPort);

	//*
	// Wenn sich der Status des Tasters seit dem letzten aufruf
	// geändert hat, dann...
	//*
	if (CurrentPushbuttonState != _LastPushbuttonState) {

		// Den momentanen Status des Taster abspeichern
		_LastPushbuttonState = CurrentPushbuttonState;

		// Der Taster ist nicht mehr im Hold- Status
		_PushbuttonOnHold = false;

		if (this->_PullUpDown == PullUp) {
			// Es ist ein Pullup Widerstand am eingang angeschlossen

			// ...Überprüfen welchen zustand der Taster jetzt hat.
			if (CurrentPushbuttonState) {
				// der taster ist jetzt High. das entspricht der
				// aufwärts Flanke.

				// Zeit speichern zu der, der Taster nach High gewechselt hat.
				_PushbuttonHighTime = millis();

				// Zeit zwischen dem letzten aufruf und jetzt berechnen.
				PushbuttonTime = _PushbuttonHighTime - _PushbuttonLowTime;

				// War die Zeit länger als die Entprellzeit und kürzer als
				// die Haltezeit des Tasters, dann wurde der Taster nur
				// kurz gedrückt. Der Status des Taster ist "Touch".
				if ((PushbuttonTime > _PushbuttonDebounceTime) && (PushbuttonTime < _PushbuttonHoldTime)) {
					PushbuttonState = ButtonStateTouch;
				}
			}
			else {
				// der taster ist jetzt Low. das entspricht der
				// abwärts Flanke.
				_PushbuttonLowTime = millis();
			}
		}
		else {
			// Es ist ein Pulldown Widerstand am eingang angeschlossen

			// ...Überprüfen welchen zustand der Taster jetzt hat.
			if (!CurrentPushbuttonState) {
				// der taster ist jetzt LOW. das entspricht der
				// abwärts Flanke.

				// Zeit speichern zu der, der Taster nach High gewechselt hat.
				_PushbuttonLowTime = millis();

				// Zeit zwischen dem letzten aufruf und jetzt berechnen.
				PushbuttonTime = _PushbuttonLowTime - _PushbuttonHighTime;

				// War die Zeit länger als die Entprellzeit und kürzer als
				// die Haltezeit des Tasters, dann wurde der Taster nur
				// kurz gedrückt. Der Status des Taster ist "Touch".
				if ((PushbuttonTime > _PushbuttonDebounceTime) && (PushbuttonTime < _PushbuttonHoldTime)) {
					PushbuttonState = ButtonStateTouch;
				}
			}
			else {
				// der taster ist jetzt Low. das entspricht der
				// aufwärts Flanke.
				_PushbuttonHighTime = millis();
			}
		}
	}

	//*
	// Wenn der Taster immer noch gedrückt ist dann auswerten wie lange schon
	//*
	if (this->_PullUpDown == PullUp) {
		// Es ist ein Pullup Widerstand am eingang angeschlossen

		if (!CurrentPushbuttonState) {
			// Zeit speichern zu der, der Taster nach High gewechselt hat.
			_PushbuttonHighTime = millis();

			// Zeit zwischen dem letzten aufruf und jetzt berechnen.
			PushbuttonTime = _PushbuttonHighTime - _PushbuttonLowTime;

			// Wenn der Taster noch nicht im Hold- Status ist und die Holdtime
			// überschritten wurde
			if (!_PushbuttonOnHold && (PushbuttonTime > _PushbuttonHoldTime)) {
				_PushbuttonOnHold = true;
				PushbuttonState = ButtonStateHold;
			}

			// Wenn der Taster im Hold- Status ist dann den Intervall auslösen.
			if (_PushbuttonOnHold && ((_PushbuttonHighTime - (_PushbuttonLowTime + _PushbuttonHoldTime)) > _PusbuttonHoldInterval)) {
				_PushbuttonLowTime = _PushbuttonLowTime + _PusbuttonHoldInterval;
				PushbuttonState = ButtonStateInterval;
			}
		}
	}
	else {
		// Es ist ein Pulldown Widerstand am eingang angeschlossen

		if (CurrentPushbuttonState) {
			// Zeit speichern zu der, der Taster nach Low gewechselt hat.
			_PushbuttonLowTime = millis();

			// Zeit zwischen dem letzten aufruf und jetzt berechnen.
			PushbuttonTime = _PushbuttonLowTime - _PushbuttonHighTime;

			// Wenn der Taster noch nicht im Hold- Status ist und die Holdtime
			// überschritten wurde
			if (!_PushbuttonOnHold && (PushbuttonTime > _PushbuttonHoldTime)) {
				_PushbuttonOnHold = true;
				PushbuttonState = ButtonStateHold;
			}

			// Wenn der Taster im Hold- Status ist dann den Intervall auslösen.
			if (_PushbuttonOnHold && ((_PushbuttonLowTime - (_PushbuttonHighTime + _PushbuttonHoldTime)) > _PusbuttonHoldInterval)) {
				_PushbuttonHighTime = _PushbuttonHighTime + _PusbuttonHoldInterval;
				PushbuttonState = ButtonStateInterval;
			}
		}
	}

	if (_PushBtnCallBack != 0) {
		this->_PushBtnCallBack(PushbuttonState);
	}

	return PushbuttonState;
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Widget with Adobe Animate</title>
    <link rel="stylesheet" href="css/style.css" type="text/css">
    <link rel="stylesheet" href="fonts/fonts.css" type="text/css" />

        <canvas id="canvas" width="1920" height="1080" style="position: absolute; display: block; background-color:rgba(255, 255, 255, 1.00);"></canvas>