text:
package com.cloudera.llama.am;

import com.cloudera.llama.am.api.LlamaAMEvent;
import com.cloudera.llama.am.api.LlamaAMListener;
import com.cloudera.llama.am.api.PlacedReservation;
import com.cloudera.llama.am.api.PlacedResource;
import com.cloudera.llama.server.ClientInfo;
import com.cloudera.llama.server.ClientNotificationService;
import com.cloudera.llama.util.UUID;
import com.cloudera.llama.util.VersionInfo;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.module.SimpleModule;
import org.codehaus.jackson.map.ser.SerializerBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RestData implements LlamaAMListener,
    ClientNotificationService.Listener {

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

  private static final Map<String, String> VERSION_INFO =
      new LinkedHashMap<String, String>();

  static {
    VERSION_INFO.put("llamaVersion", VersionInfo.getVersion());
    VERSION_INFO.put("llamaBuiltDate", VersionInfo.getBuiltDate());
    VERSION_INFO.put("llamaBuiltBy", VersionInfo.getBuiltBy());
    VERSION_INFO.put("llamaScmUri", VersionInfo.getSCMURI());
    VERSION_INFO.put("llamaScmRevision", VersionInfo.getSCMRevision());
    VERSION_INFO.put("llamaSourceMD5", VersionInfo.getSourceMD5());
    VERSION_INFO.put("llamaHadoopVersion", VersionInfo.getHadoopVersion());
  }

  public static final String REST_VERSION_KEY = "llamaRestJsonVersion";
  public static final String REST_VERSION_VALUE = "1.0.0";

  static final String VERSION_INFO_KEY = "llamaVersionInfo";
  static final String RESERVATIONS_COUNT_KEY = "reservationsCount";
  static final String QUEUES_SUMMARY_KEY = "queuesSummary";
  static final String CLIENTS_SUMMARY_KEY = "clientsSummary";
  static final String NODES_SUMMARY_KEY = "nodesSummary";

  static final String SUMMARY_DATA = "summaryData";
  static final String ALL_DATA = "allData";
  static final String RESERVATION_DATA = "reservationData";
  static final String QUEUE_DATA = "queueData";
  static final String HANDLE_DATA = "handleData";
  static final String NODE_DATA = "nodeData";

  static final String COUNT = "count";
  static final String RESERVATIONS = "reservations";
  static final String CLIENT_INFOS = "clientInfos";
  static final String NODES_CROSSREF = "nodesCrossref";
  static final String HANDLES_CROSSREF = "handlesCrossref";
  static final String QUEUES_CROSSREF = "queuesCrossref";
  static final String HA_SERVER_STATUS = "llamaAMServerStatus";

  static final String CLIENT_INFO = "clientInfo";
  static final String QUEUE = "queue";
  static final String NODE = "node";

  private final ObjectMapper jsonMapper;
  private final ReadWriteLock lock;
  private final Map<UUID, PlacedReservation> reservationsMap;
  private final Map<UUID, List<PlacedReservation>> handleReservationsMap;
  private final Map<String, List<PlacedReservation>> queueReservationsMap;
  private final Map<String, List<PlacedReservation>> nodeReservationsMap;
  private final Map<UUID, ClientInfo> clientInfoMap;
  private final Set<UUID> hasBeenBackedOff;
  private final LlamaAMServer llamaAMServer;

  private ObjectMapper createJsonMapper() {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("LlamaModule",
        new Version(1, 0, 0, null));
    module.addSerializer(new UUIDSerializer());
    module.addSerializer(new ClientInfoImplSerializer());
    module.addSerializer(new PlacedReservationSerializer());
    module.addSerializer(new PlacedResourceSerializer());
    mapper.registerModule(module);
    mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
    return mapper;
  }

  public RestData(LlamaAMServer llamaAMServer) {
    jsonMapper = createJsonMapper();
    lock = new ReentrantReadWriteLock(true);
    reservationsMap = new LinkedHashMap<UUID, PlacedReservation>();
    handleReservationsMap = new LinkedHashMap<UUID, List<PlacedReservation>>();
    queueReservationsMap = new TreeMap<String, List<PlacedReservation>>();
    nodeReservationsMap = new TreeMap<String, List<PlacedReservation>>();
    clientInfoMap = new LinkedHashMap<UUID, ClientInfo>();
    hasBeenBackedOff = new HashSet<UUID>();
    this.llamaAMServer = llamaAMServer;
  }

  public void onRegister(ClientInfo clientInfo) {
    lock.writeLock().lock();
    try {
      clientInfoMap.put(clientInfo.getHandle(), clientInfo);
    } finally {
      lock.writeLock().unlock();
    }
  }

  public void onUnregister(ClientInfo clientInfo) {
    lock.writeLock().lock();
    try {
      if (clientInfoMap.remove(clientInfo.getHandle()) != null) {
        List<PlacedReservation> list =
            new ArrayList<PlacedReservation>(reservationsMap.values());
        int count = 0;
        for (PlacedReservation reservation : list) {
          if (reservation.getHandle().equals(clientInfo.getHandle())) {
            delete(reservation, true);
            count++;
          }
        }
        LOG.debug("onUnregister({}), dropped '{}' reservations",
            clientInfo.getHandle(), count);
      }
    } finally {
      lock.writeLock().unlock();
    }
  }

  @Override
  public void onEvent(LlamaAMEvent event) {
    lock.writeLock().lock();
    try {
      for (PlacedReservation reservation : event.getReservationChanges()) {
        LOG.debug("onEvent({})", reservation);
        if (verifyHandle(reservation)) {
          if (!reservation.getStatus().isFinal()) {
            if (!reservationsMap.containsKey(reservation.getReservationId())) {
              add(reservation);
            } else {
              update(reservation);
            }
            if (reservation.getStatus() == PlacedReservation.Status.BACKED_OFF) {
              hasBeenBackedOff.add(reservation.getReservationId());
            }
          } else {
            delete(reservation, true);
            hasBeenBackedOff.remove(reservation.getReservationId());
          }
        } else {
          delete(reservation, false);
          LOG.debug("Handle not known anymore for reservation '{}'",
              reservation);
        }
      }
      for (PlacedResource resource : event.getResourceChanges()) {
        LOG.debug("onEvent({})", resource);
        update(resource);
      }
    } finally {
      lock.writeLock().unlock();
    }
  }

  private boolean verifyHandle(PlacedReservation reservation) {
    return clientInfoMap.containsKey(reservation.getHandle());
  }

  private <K,V> void addToMapList(Map<K, List<V>> map, K key, V value) {
    List<V> list = map.get(key);
    if (list == null) {
      list = new ArrayList<V>();
      map.put(key, list);
    }
    list.add(value);
  }

  private void add(PlacedReservation reservation) {
    reservationsMap.put(reservation.getReservationId(), reservation);
    addToMapList(handleReservationsMap, reservation.getHandle(), reservation);
    addToMapList(queueReservationsMap, reservation.getQueue(), reservation);
    for (PlacedResource resource : reservation.getPlacedResources()) {
      addToMapList(nodeReservationsMap, resource.getLocationAsk(), reservation);
    }
  }

  private <K, V> void updateToMapList(Map<K, List<V>> map, K key, V value,
      String msg) {
    List<V> list = map.get(key);
    if (list != null) {
      int index = list.indexOf(value);
      if (index >= 0) {
        list.set(index, value);
      } else {
        LOG.error("RestData update inconsistency, key '{}' not found in {}",
            key, msg);
      }
    } else {
      LOG.error("RestData update inconsistency, value '{}' not found in {}",
          value, msg);
    }
  }

  private void updateResource( PlacedResource resource,
      PlacedReservation reservation) {
    boolean actualLocation = false;
    List<PlacedReservation> list =
        nodeReservationsMap.get(resource.getLocationAsk());
    if (list == null) {
      list = nodeReservationsMap.get(resource.getLocation());
      actualLocation = true;
    }
    if (list != null) {
      int index = list.indexOf(reservation);
      if (index >= 0) {
        PlacedReservation oldReservation = list.get(index);
        PlacedResource oldResource = null;
        List<PlacedResource> oldResources = oldReservation.getPlacedResources();
        for (int i = 0; oldResource == null && i < oldResources.size(); i++) {
          if (oldResources.get(i).getResourceId().
              equals(resource.getResourceId())) {
            oldResource = oldResources.get(i);
          }
        }
        if (oldResource == null) {
          LOG.error("RestData update inconsistency resource '{}' not found " +
              "in nodeReservations", resource);
        } else {
          if (actualLocation ||
              resource.getLocation() == null ||
              oldResource.getLocationAsk().equals(resource.getLocation())) {
            list.set(index, reservation);
          } else {
            list.remove(index);
            if (list.isEmpty()) {
              nodeReservationsMap.remove(resource.getLocationAsk());
            }
            list = nodeReservationsMap.get(resource.getLocation());
            if (list == null) {
              list = new ArrayList<PlacedReservation>();
              nodeReservationsMap.put(resource.getLocation(), list);
            }
            list.add(reservation);
          }
        }
      } else {
        LOG.error("RestData update inconsistency, key '{}' not found " +
            "in nodeReservations", reservation.getReservationId());
      }
    } else {
      LOG.error("RestData update inconsistency, value '{}' not found " +
            "in nodeReservations", reservation);
    }
  }

  private void update(PlacedReservation reservation) {
    reservationsMap.put(reservation.getReservationId(), reservation);
    updateToMapList(handleReservationsMap, reservation.getHandle(), reservation,
        "handleReservationsMap");
    updateToMapList(queueReservationsMap, reservation.getQueue(), reservation,
        "queueReservationsMap");
    for (PlacedResource resource : reservation.getPlacedResources()) {
      updateResource(resource, reservation);
    }
  }

  private void update(PlacedResource resource) {
    PlacedReservation reservation = reservationsMap.get(resource.getReservationId());
    if (reservation != null) {
      int idx = reservation.getPlacedResources().indexOf(resource);
      if (idx > -1) {
        reservation.getPlacedResources().set(idx, resource);
        updateResource(resource, reservation);
      } else{
        LOG.error("RestData update inconsistency, resource '{}' not found " +
            "in reservation '{}'", resource, reservation);
      }
    }
  }

  private <K, V> boolean deleteFromMapList(Map<K, List<V>> map, K key, V value) {
    boolean deleted = true;
    List<V> list = map.get(key);
    if (list != null) {
      int index = list.indexOf(value);
      if (index >= 0) {
        list.remove(index);
      } else {
        deleted = false;
      }
      if (list.isEmpty()) {
        map.remove(key);
      }
    } else {
      deleted = false;
    }
    return deleted;
  }

  private void delete(PlacedReservation reservation, boolean log) {
    reservationsMap.remove(reservation.getReservationId());
    if (!deleteFromMapList(handleReservationsMap, reservation.getHandle(),
        reservation)) {
      if (log) {
        LOG.warn(
            "RestData delete inconsistency, reservation '{}' not found in handle",
            reservation);
      }
    }
    if (!deleteFromMapList(queueReservationsMap, reservation.getQueue(),
        reservation)) {
      if (log) {
        LOG.warn(
            "RestData delete inconsistency, reservation '{}' not found in queue",
            reservation);
      }
    }
    for (PlacedResource resource : reservation.getPlacedResources()) {
      boolean deleted = deleteFromMapList(nodeReservationsMap,
          resource.getLocationAsk(), reservation);
      if (resource.getLocation() != null) {
        deleted = deleteFromMapList(nodeReservationsMap,
            resource.getLocation(), reservation) || deleted;
      }
      if (!deleted) {
        if (log) {
          LOG.warn(
              "RestData delete inconsistency, reservation '{}' not found in " +
                  "location nor actualLocation",
              reservation);
        }
      }
    }
  }

  public static class UUIDSerializer extends
      SerializerBase<UUID> {

    protected UUIDSerializer() {
      super(UUID.class);
    }

    @Override
    public void serialize(UUID value, JsonGenerator jgen,
        SerializerProvider provider)
        throws IOException {
      jgen.writeString(value.toString());
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint)
        throws JsonMappingException {
      return createSchemaNode("string");
    }
  }

  public static class ClientInfoImplSerializer extends
      SerializerBase<ClientInfoImpl> {

    protected ClientInfoImplSerializer() {
      super(ClientInfoImpl.class);
    }

    @Override
    public void serialize(ClientInfoImpl value, JsonGenerator jgen,
        SerializerProvider provider)
        throws IOException {
      jgen.writeStartObject();
      jgen.writeObjectField("clientId", value.getClientId());
      jgen.writeObjectField("handle", value.getHandle());
      jgen.writeStringField("callbackAddress", value.getCallbackAddress());
      jgen.writeNumberField("reservations", value.getReservations());
      jgen.writeEndObject();
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint)
        throws JsonMappingException {
      return createSchemaNode("object");
    }
  }
  public class PlacedReservationSerializer extends
      SerializerBase<PlacedReservation> {

    protected PlacedReservationSerializer() {
      super(PlacedReservation.class);
    }

    @Override
    public void serialize(PlacedReservation value, JsonGenerator jgen,
        SerializerProvider provider)
        throws IOException {
      jgen.writeStartObject();
      jgen.writeObjectField("reservationId", value.getReservationId());
      jgen.writeObjectField("expansionOfId", value.getExpansionOf());
      jgen.writeStringField("placedOn", formatDateTime(value.getPlacedOn()));
      jgen.writeObjectField("handle", value.getHandle());
      jgen.writeStringField("queue", value.getQueue());
      jgen.writeBooleanField("gang", value.isGang());
      jgen.writeBooleanField("queued", value.isQueued());
      jgen.writeStringField("status", value.getStatus().toString());
      jgen.writeBooleanField("hasBeenBackedOff",
          hasBeenBackedOff.contains(value.getReservationId()));
      jgen.writeObjectField("resources", value.getResources());
      jgen.writeEndObject();
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint)
        throws JsonMappingException {
      return createSchemaNode("object");
    }
  }

  private static String flattenToString(List<Object> list) {
    StringBuilder sb = new StringBuilder();
    String separator = "";
    for (Object o : list) {
      sb.append(separator).append(o);
      separator = ", ";
    }
    return sb.toString();
  }

  public static class PlacedResourceSerializer extends
      SerializerBase<PlacedResource> {

    public PlacedResourceSerializer() {
      super(PlacedResource.class);
    }

    @Override
    public void serialize(PlacedResource value, JsonGenerator jgen,
        SerializerProvider provider)
        throws IOException {
      jgen.writeStartObject();
      jgen.writeObjectField("resourceId", value.getResourceId());
      jgen.writeStringField("locationAsk", value.getLocationAsk());
      jgen.writeStringField("locality", value.getLocalityAsk().toString());
      jgen.writeNumberField("cpuVCoresAsk", value.getCpuVCoresAsk());
      jgen.writeNumberField("memoryMbsAsk", value.getMemoryMbsAsk());
      jgen.writeObjectField("handle", value.getHandle());
      jgen.writeStringField("queue", value.getQueue());
      jgen.writeObjectField("reservationId", value.getReservationId());
      if (value.getRmResourceId() != null) {
        jgen.writeObjectField("rmResourceId", value.getRmResourceId().toString());
      }
      jgen.writeStringField("actualLocation", value.getLocation());
      jgen.writeNumberField("actualCpuVCores", value.getCpuVCores());
      jgen.writeNumberField("actualMemoryMb", value.getMemoryMbs());
      jgen.writeStringField("status", value.getStatus().toString());
      jgen.writeEndObject();
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint)
        throws JsonMappingException {
      return createSchemaNode("object");
    }
  }

  public static class NotFoundException extends Exception {
    public NotFoundException() {
    }
  }

  @SuppressWarnings("unchecked")
  void writeAsJson(String payloadType, Object obj, Writer out)
      throws IOException, NotFoundException {
    if (obj != null) {
      Map map = new LinkedHashMap();
      map.put(REST_VERSION_KEY, REST_VERSION_VALUE);
      map.put(payloadType, obj);
      jsonMapper.defaultPrettyPrintingWriter().writeValue(out, map);
    } else {
      throw new NotFoundException();
    }
  }

  @SuppressWarnings("unchecked")
  private <K, V> List<Map> createMapSummaryList(String itemName, Map<K,
      List<V>> map) {
    List<Map> summary = new ArrayList<Map>();
    for (Map.Entry<K, List<V>> entry : map.entrySet()) {
      Map item = new LinkedHashMap();
      item.put(itemName, entry.getKey());
      item.put(COUNT, entry.getValue().size());
      summary.add(item);
    }
    return summary;
  }

  public static class ClientInfoImpl implements ClientInfo {
    private ClientInfo clientInfo;
    private int reservations;

    public ClientInfoImpl(ClientInfo clientInfo, int reservations) {
      this.clientInfo = clientInfo;
      this.reservations = reservations;
    }
    @Override
    public UUID getClientId() {
      return clientInfo.getClientId();
    }

    @Override
    public UUID getHandle() {
      return clientInfo.getHandle();
    }

    @Override
    public String getCallbackAddress() {
      return clientInfo.getCallbackAddress();
    }

    public int getReservations() {
      return reservations;
    }
  }

  private List<ClientInfoImpl> createClientInfoSummary() {
    Map<UUID, Integer> summary = new LinkedHashMap<UUID, Integer>();
    for (Map.Entry<UUID, List<PlacedReservation>> entry :
        handleReservationsMap.entrySet()) {
      summary.put(entry.getKey(), entry.getValue().size());
    }
    List<ClientInfoImpl> list = new ArrayList<ClientInfoImpl>(
        clientInfoMap.size());
    for (Map.Entry<UUID, ClientInfo> entry : clientInfoMap.entrySet()) {
      Integer count = summary.get(entry.getKey());
      count = (count != null) ? count : 0;
      list.add(new ClientInfoImpl(entry.getValue(), count));
    }
    return list;
  }

  @SuppressWarnings("unchecked")
  public void writeSummaryAsJson(Writer out)
      throws IOException, NotFoundException {
    lock.readLock().lock();
    try {
      Map summary = new LinkedHashMap();
      summary.put(VERSION_INFO_KEY, VERSION_INFO);
      summary.put(RESERVATIONS_COUNT_KEY, reservationsMap.size());
      summary.put(QUEUES_SUMMARY_KEY, createMapSummaryList(QUEUE,
          queueReservationsMap));
      summary.put(CLIENTS_SUMMARY_KEY, createClientInfoSummary());
      summary.put(NODES_SUMMARY_KEY, createMapSummaryList(NODE,
          nodeReservationsMap));
      if (llamaAMServer != null) {
        if (llamaAMServer instanceof LlamaHAServer) {
          // HA enabled
          summary.put(HA_SERVER_STATUS,
              ((LlamaHAServer) llamaAMServer).isActive() ? "active" : "standby");
        } else {
          // HA disabled
          summary.put(HA_SERVER_STATUS, "active");
        }
      }
      writeAsJson(SUMMARY_DATA, summary, out);
    } finally {
      lock.readLock().unlock();
    }
  }

  @SuppressWarnings("unchecked")
  private <K> Map<K, List<UUID>> createCrossRef(Map<K, List<PlacedReservation>>
      map) {
    Map<K, List<UUID>> crossRef = new LinkedHashMap<K, List<UUID>>();
    for (Map.Entry<K, List<PlacedReservation>> entry : map.entrySet()) {
      K key = entry.getKey();
      List<UUID> list = crossRef.get(key);
      if (list == null) {
        list = new ArrayList<UUID>();
        crossRef.put(key, list);
      }
      for (PlacedReservation value : entry.getValue()) {
        list.add(value.getReservationId());
      }
    }
    return crossRef;
  }

  @SuppressWarnings("unchecked")
  public void writeAllAsJson(Writer out)
      throws IOException, NotFoundException {
    lock.readLock().lock();
    try {
      Map all = new LinkedHashMap();
      all.put(VERSION_INFO_KEY, VERSION_INFO);
      all.put(RESERVATIONS, reservationsMap);
      all.put(CLIENT_INFOS, createClientInfoSummary());
      all.put(QUEUES_CROSSREF, createCrossRef(queueReservationsMap));
      all.put(HANDLES_CROSSREF, createCrossRef(handleReservationsMap));
      all.put(NODES_CROSSREF, createCrossRef(nodeReservationsMap));
      if (llamaAMServer != null) {
        if (llamaAMServer instanceof LlamaHAServer) {
          // HA enabled
          all.put(HA_SERVER_STATUS,
              ((LlamaHAServer) llamaAMServer).isActive() ? "active" : "standby");
        } else {
          // HA disabled
          all.put(HA_SERVER_STATUS, "active");
        }
      }
      writeAsJson(ALL_DATA, all, out);
    } finally {
      lock.readLock().unlock();
    }
  }

  public void writeReservationAsJson(UUID reservationId, Writer out)
      throws IOException, NotFoundException {
    lock.readLock().lock();
    try {
      PlacedReservation r = reservationsMap.get(reservationId);
      if (r == null) {
        throw new NotFoundException();
      }
      writeAsJson(RESERVATION_DATA, r, out);
    } finally {
      lock.readLock().unlock();
    }
  }

  @SuppressWarnings("unchecked")
  public void writeHandleReservationsAsJson(UUID handle, Writer out)
      throws IOException, NotFoundException {
    lock.readLock().lock();
    try {
      ClientInfo ci = clientInfoMap.get(handle);
      if (ci == null) {
        throw new NotFoundException();
      }
      List<PlacedReservation> prs = handleReservationsMap.get(handle);
      prs = (prs != null) ? prs : Collections.EMPTY_LIST;
      Map map = new LinkedHashMap();
      map.put(CLIENT_INFO, ci);
      map.put(RESERVATIONS, prs);
      writeAsJson(HANDLE_DATA, map, out);
    } finally {
      lock.readLock().unlock();
    }
  }

  public void writeQueueReservationsAsJson(String queue, Writer out)
      throws IOException, NotFoundException {
    lock.readLock().lock();
    try {
      List<PlacedReservation> l = queueReservationsMap.get(queue);
      if (l == null) {
        throw new NotFoundException();
      }
      writeAsJson(QUEUE_DATA, l, out);
    } finally {
      lock.readLock().unlock();
    }
  }

  public void writeNodeResourcesAsJson(String node, Writer out)
      throws IOException, NotFoundException {
    lock.readLock().lock();
    try {
      List<PlacedReservation> l = nodeReservationsMap.get(node);
      if (l == null) {
        throw new NotFoundException();
      }
      writeAsJson(NODE_DATA, l, out);
    } finally {
      lock.readLock().unlock();
    }
  }

  private static final String ISO8601_UTC_MASK = "yyyy-MM-dd'T'HH:mm'Z'";
  private static final TimeZone UTC = TimeZone.getTimeZone("UTC");

  private static String formatDateTime(long epoc) {
    DateFormat dateFormat = new SimpleDateFormat(ISO8601_UTC_MASK);
    dateFormat.setTimeZone(UTC);
    Date date = new Date(epoc);
    return dateFormat.format(date);
  }

}


text:
package org.jboss.weld.bootstrap.event;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Function;

import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.Instance;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.inject.spi.BeanAttributes;
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.enterprise.inject.spi.Prioritized;
import jakarta.enterprise.inject.spi.configurator.BeanConfigurator;
import jakarta.enterprise.util.TypeLiteral;
import jakarta.interceptor.Interceptor.Priority;

/**
 * Represents an enhanced version of {@link BeanConfigurator}
 *
 * @author Matej Novotny
 */
public interface WeldBeanConfigurator<T> extends BeanConfigurator<T> {

    @Override
    WeldBeanConfigurator<T> alternative(boolean value);

    @Override
    WeldBeanConfigurator<T> name(String name);

    @Override
    WeldBeanConfigurator<T> stereotypes(Set<Class<? extends Annotation>> stereotypes);

    @Override
    WeldBeanConfigurator<T> addStereotypes(Set<Class<? extends Annotation>> stereotypes);

    @Override
    WeldBeanConfigurator<T> addStereotype(Class<? extends Annotation> stereotype);

    @Override
    WeldBeanConfigurator<T> qualifiers(Set<Annotation> qualifiers);

    @Override
    WeldBeanConfigurator<T> qualifiers(Annotation... qualifiers);

    @Override
    WeldBeanConfigurator<T> addQualifiers(Set<Annotation> qualifiers);

    @Override
    WeldBeanConfigurator<T> addQualifiers(Annotation... qualifiers);

    @Override
    WeldBeanConfigurator<T> addQualifier(Annotation qualifier);

    @Override
    WeldBeanConfigurator<T> scope(Class<? extends Annotation> scope);

    @Override
    WeldBeanConfigurator<T> types(Set<Type> types);

    @Override
    WeldBeanConfigurator<T> types(Type... types);

    @Override
    WeldBeanConfigurator<T> addTransitiveTypeClosure(Type type);

    @Override
    WeldBeanConfigurator<T> addTypes(Set<Type> types);

    @Override
    WeldBeanConfigurator<T> addTypes(Type... types);

    @Override
    WeldBeanConfigurator<T> addType(TypeLiteral<?> typeLiteral);

    @Override
    WeldBeanConfigurator<T> addType(Type type);

    @Override
    WeldBeanConfigurator<T> read(BeanAttributes<?> beanAttributes);

    @Override
     WeldBeanConfigurator read(AnnotatedType type);

    @Override
    WeldBeanConfigurator<T> disposeWith(BiConsumer<T, Instance<Object>> callback);

    @Override
    WeldBeanConfigurator<T> destroyWith(BiConsumer<T, CreationalContext<T>> callback);

    @Override
     WeldBeanConfigurator produceWith(Function<Instance<Object>, U> callback);

    @Override
     WeldBeanConfigurator createWith(Function<CreationalContext, U> callback);

    @Override
    WeldBeanConfigurator<T> id(String id);

    @Override
    WeldBeanConfigurator<T> injectionPoints(Set<InjectionPoint> injectionPoints);

    @Override
    WeldBeanConfigurator<T> injectionPoints(InjectionPoint... injectionPoints);

    @Override
    WeldBeanConfigurator<T> addInjectionPoints(Set<InjectionPoint> injectionPoints);

    @Override
    WeldBeanConfigurator<T> addInjectionPoints(InjectionPoint... injectionPoints);

    @Override
    WeldBeanConfigurator<T> addInjectionPoint(InjectionPoint injectionPoint);

    @Override
    WeldBeanConfigurator<T> beanClass(Class<?> beanClass);

    /**
     * NOTE: Since CDI 4.0, this is now part of standard API!
     *

     * Allows to set a priority to an alternative bean hence selecting it globally.
     * Has the same effect as putting {@link Priority} annotation on an actual bean class
     * or implementing {@link Prioritized} interface with custom bean classes.
     * This method has no effect on custom beans which are not alternatives.
     *
     * @param priority the priority of this bean
     * @return self
     */
    @Override
    WeldBeanConfigurator<T> priority(int priority);
}

redpajama_set_name: RedPajamaGithub


text:
This library provides easy access to the [Message Events](https://developers.sparkpost.com/api/message-events) resource.

*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).*

## Methods
* **search([params, callback])**<br />
  Search for message events using the given parameters (NOTE: all params are optional):
  * `params` - a hash of [Message Events URI Parameters](https://developers.sparkpost.com/api/message-events.html#message-events-message-events-get)

## Date/Time Parameter Format

The `from` and `to` search parameters accept date stamps of the form:

  `YYYY-MM-DDTHH:MM`

For example: `2016-11-14T16:15`.

Note: timestamps are expressed in the timezone specified by the `timezone` parameter or UTC by default.

## Examples

Visit our examples section to see all of [our message events resource examples](/examples/messageEvents).


text:
package name.lenmar;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Lenmar Abdurayimov on 5/2/2017.
 */

/*
    -agentlib:jdwp=transport=dt_socket,address=14000,server=y,suspend=n
    -Xms512m
    -Xmx512m
    -XX:MaxMetaspaceSize=256m
    -XX:+UseConcMarkSweepGC
    -XX:+CMSParallelRemarkEnabled
    -XX:+UseCMSInitiatingOccupancyOnly
    -XX:CMSInitiatingOccupancyFraction=70
    -XX:+ScavengeBeforeFullGC
    -XX:+CMSScavengeBeforeRemark
    -XX:+UseParNewGC
    -verbose:gc
    -Xloggc:./logs/gc_pid_%p.log
    -XX:+PrintGCDateStamps
    -XX:+PrintGCDetails
    -XX:+UseGCLogFileRotation
    -XX:NumberOfGCLogFiles=10
    -XX:GCLogFileSize=1M
    -Dcom.sun.management.jmxremote.port=15000
    -Dcom.sun.management.jmxremote.authenticate=false
    -Dcom.sun.management.jmxremote.ssl=false
    -XX:+HeapDumpOnOutOfMemoryError
    -XX:HeapDumpPath=./dumps/
    -XX:OnOutOfMemoryError="kill -3 %p"

    jps -- list VMs
    jstack <pid> >> threaddumps.log -- get dump from pid
    jinfo -- list VM parameters
    jhat / jvisualvm -- analyze heap dump
*/

public class Main {

    private static final int BOUND = 10_000_000;
    private static final int DELAY = 5_000;

    public static void main(String[] args) throws InterruptedException {
        System.out.println("Starting pid: " + ManagementFactory.getRuntimeMXBean().getName());

        GCMonitor.registerGCMonitor();

        List<Integer> list = new ArrayList<>();
        Random rand = new Random();

        try {
            for (int i = 1; i < Integer.MAX_VALUE; i++) {
                list.add(rand.nextInt(BOUND));

                if ((i % 2) == 0) {
                    list.remove(list.size() - 1);
                }

                if ((i % BOUND) == 0) {
                    Thread.sleep(DELAY);

                    System.out.println("\n" + i + " objects are added to list");
                    System.out.println(list.size() + " objects left after removing");
                }
            }
        }
        finally {
            //printGCStats();
        }
    }

    private static void printGCStats() {
        long totalGarbageCollections = 0L;
        long garbageCollectionTime   = 0L;

        List<GarbageCollectorMXBean> gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
        for(GarbageCollectorMXBean gc : gcMXBeans) {
            long count = gc.getCollectionCount();
            totalGarbageCollections += (count >= 0) ? count : 0L;

            long time = gc.getCollectionTime();
            garbageCollectionTime += (time >= 0) ? time : 0L;
        }

        System.out.println("Total Garbage Collections: " + totalGarbageCollections);
        System.out.println("Total Garbage Collection Time (ms): " + garbageCollectionTime);
        System.out.println();
        System.out.println("Minor GC count: " + gcMXBeans.get(0).getCollectionCount());
        System.out.println("Minor GC Time (ms): " + gcMXBeans.get(0).getCollectionTime());
        System.out.println("Major GC count: " + gcMXBeans.get(1).getCollectionCount());
        System.out.println("Major GC Time (ms): " + gcMXBeans.get(1).getCollectionTime());
    }
}


text:
The PlayerFillBucket Event is fired whenever a player fills a bucket.

## Event Class

You will need to cast the event in the function header as this class:
`crafttweaker.event.PlayerFillBucketEvent`
You can, of course, also [import](/AdvancedFunctions/Import/) the class before and use that name then.

## Event interface extensions

PlayerFillBucket Events implement the following interfaces and are able to call all of their methods/getters/setters as well:

- [IEventCancelable](/Vanilla/Events/Events/IEventCancelable/)
- [IPlayerEvent](/Vanilla/Events/Events/IPlayerEvent/)
- [IProcessableEvent](/Vanilla/Events/Events/IProcessableEvent/)
- [IEventPositionable](/Vanilla/Events/Events/IEventPositionable/)

## ZenGetters

The following information can be retrieved from the event:

| ZenGetter        | Return Type                                        |
| ---------------- | -------------------------------------------------- |
| `canceled`       | boolean                                            |
| `player`         | [IPlayer](/Vanilla/Players/IPlayer/)               |
| `result`         | [IItemStack](/Vanilla/Items/IItemStack/)           |
| `emptyBucket`    | [IItemStack](/Vanilla/Items/IItemStack/)           |
| `x`              | int                                                |
| `y`              | int                                                |
| `z`              | int                                                |
| `world`          | [IWorld](/Vanilla/World/IWorld/)                   |
| `blockState`     | [IBlockState](/Vanilla/Blocks/IBlockState/)        |
| `block`          | [IBlock](/Vanilla/Blocks/IBlock/)                  |
| `dimension`      | int                                                |
| `rayTraceResult` | [IRayTraceResult](/Vanilla/World/IRayTraceResult/) |

## ZenMethods

- `event.cancel()` sets the event as cancelled.

## Setters

- `event.result = <minecraft:ender_pearl>` This will also process the event!


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/ads/googleads/v11/errors/criterion_error.proto

namespace Google\Ads\GoogleAds\V11\Errors;

if (false) {
    /**
     * This class is deprecated. Use Google\Ads\GoogleAds\V11\Errors\CriterionErrorEnum\CriterionError instead.
     * @deprecated
     */
    class CriterionErrorEnum_CriterionError {}
}
class_exists(CriterionErrorEnum\CriterionError::class);
@trigger_error('Google\Ads\GoogleAds\V11\Errors\CriterionErrorEnum_CriterionError is deprecated and will be removed in the next major release. Use Google\Ads\GoogleAds\V11\Errors\CriterionErrorEnum\CriterionError instead', E_USER_DEPRECATED);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cystopus convolvulacearum var. minor Speg.

### Remarks
null


text:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <grp.h>
#include <string.h>

/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/*

compile instructions (using c static library, for security, to eliminate
shared library that could be manipulated):

    g++ -static untrusted_execute.c -o untrusted_execute

change permissions & set suid: (must be root)

    chown root untrusted_execute
    chgrp DAEMON_USER untrusted_execute
    chmod 4550 untrusted_execute
*/
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */

int main(int argc, char* argv[]) {

  /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
  /* Verify that we have at least two arguments, which untrusted user
     to run as, and the name of the program to run... */

  if (argc < 3) {
    fprintf(stderr,"untrusted_execute: ERROR! WRONG NUMBER OF ARGUMENTS\n");
    exit(1);
  }
  int length = strnlen(argv[1], 16);

  /* verify the untrusted username which must be of the form "untrustedNN" */
  if (length != 11 || strstr(argv[1],"untrusted") != argv[1]) {
    fprintf(stderr,"untrusted_execute: ERROR! Invalid untrusted user %s\n", argv[1]);
    exit(1);
  }

  char which_untrusted_string[3];
  strncpy(which_untrusted_string,argv[1]+9,2);
  which_untrusted_string[2]='\0';
  int which_untrusted = atoi(which_untrusted_string);

  int res;
  uid_t euid;

  /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
  /* THIS PROGRAM ASSUMES THAT A SPECIAL UNTRUSTED USER & GROUP EXISTS IN THE SYSTEM
     IF THEIR IDS CHANGE THIS PROGRAM MUST BE EDITED
     THE SUID BIT & PERMISSIONS MUST BE SET CORRECTLY ON THE EXECUTABLE
  */
  static const uid_t ROOT_UID = 0;         /* root's user id & group id */

  static const uid_t NUM_UNTRUSTED       = __INSTALL__FILLIN__NUM_UNTRUSTED__;       /* num untrusted users */
  static const uid_t FIRST_UNTRUSTED_UID = __INSTALL__FILLIN__FIRST_UNTRUSTED_UID__; /* untrusted's user id */
  static const uid_t FIRST_UNTRUSTED_GID = __INSTALL__FILLIN__FIRST_UNTRUSTED_GID__; /* untrusted's group id */

  static const uid_t DAEMON_UID    = __INSTALL__FILLIN__DAEMON_UID__;    /* submitty_daemon's user id */
  static const uid_t DAEMON_GID    = __INSTALL__FILLIN__DAEMON_GID__;    /* submitty_daemon's group id */

  if (which_untrusted < 0 || which_untrusted >= NUM_UNTRUSTED) {
    fprintf(stderr,"untrusted_execute: INVALID UNTRUSTED ID %d\n", which_untrusted);
    exit(1);
  }

  uid_t MY_UNTRUSTED_UID = FIRST_UNTRUSTED_UID + which_untrusted;
  uid_t MY_UNTRUSTED_GID = FIRST_UNTRUSTED_GID + which_untrusted;

  /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */

  /* Sanity check, this program must be run by submitty_daemon, with
     effective uid root (suid root bit must be set) */
  if (geteuid() != ROOT_UID || getuid() != DAEMON_UID) {
    fprintf(stderr,"INTERNAL ERROR: BAD USER\n");
    fprintf(stderr,"uid:%d euid:%d",getuid(),geteuid());
    exit(1);
  }

  /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
  /* Check the file permissions of this program
     owner of this file: root
     group of this file: DAEMON_GROUP
     suid bit should be set
     user(root) rx
     group(DAEMON_GROUP) rx
     other nothing
  */
  /* We assume we're on Linux! */
  struct stat stat_data;
  res = stat("/proc/self/exe", &stat_data);
  if (res != 0) {
    fprintf(stderr,"INTERNAL ERROR: FAILED TO STAT SELF\n");
    perror("stat error: ");
    exit(1);
  }
  static const int CORRECT_PERMS = S_IFREG|S_ISUID|S_IRUSR|S_IXUSR|S_IRGRP|S_IXGRP;
  if (stat_data.st_mode != CORRECT_PERMS) {
    fprintf(stderr,"INTERNAL ERROR: file permissions 0x%x (vs 0x%x) are invalid!\n", stat_data.st_mode,
	    CORRECT_PERMS);
    exit(1);
  }
  if (stat_data.st_uid != ROOT_UID ||
      stat_data.st_gid != DAEMON_GID) {
    fprintf(stderr,"INTERNAL ERROR: file uid %d gid %d are invalid\n", stat_data.st_uid, stat_data.st_gid);
    exit(1);
  }

  /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
  /* Drop privileges (groups, gid, uid) */

  /* make sure to clear out the secondary groups first */
  gid_t my_gid = MY_UNTRUSTED_GID;
  res = setgroups (1,&my_gid);
  if (res != 0) {
    fprintf(stderr,"INTERNAL ERROR: FAILED TO DROP GROUPS (setgroups)\n");
    perror("setgroups error: ");
    exit(1);
  }

  /* switch the group id to the untrusted group id */
  res = setresgid(MY_UNTRUSTED_GID, MY_UNTRUSTED_GID, MY_UNTRUSTED_GID);
  if (res != 0) {
    fprintf(stderr,"INTERNAL ERROR: FAILED TO DROP GROUP PRIVS\n");
    perror("setresgid error: ");
    exit(1);
  }

  /* switch the user id to the untrusted user id */
  res = setresuid(MY_UNTRUSTED_UID, MY_UNTRUSTED_UID, MY_UNTRUSTED_UID);
  if (res != 0) {
    fprintf(stderr,"INTERNAL ERROR: FAILED TO DROP USER PRIVS\n");
    perror("setresuid error: ");
    exit(1);
  }

  /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */

  /* chop off this executable, and run the the program specified by the rest of the args */
  char *envp[1] = {NULL};
  /* clears the environment variables, etc. */
  execve(argv[2], argv+2, envp);
  perror("exec");
  fprintf(stderr,"INTERNAL ERROR: exec failed\n");
  fprintf(stderr,"%s\n",argv[1]);
  exit (1);
}


text:
================
Transcriptions
================

Show all Transcribed Messages
=============================

.. code-block:: php

    $client = new Services_Twilio('AC123', '123');
    foreach ($client->account->transcriptions as $t) {
      print $t->transcription_text;
    }


text:
package org.netmelody.neoclassycle.dependency;

import org.netmelody.neoclassycle.graph.Attributes;
import org.netmelody.neoclassycle.graph.NameAttributes;
import org.netmelody.neoclassycle.graph.Vertex;
import org.netmelody.neoclassycle.graph.VertexCondition;
import org.netmelody.neoclassycle.util.StringPattern;

/**
 * @author Franz-Josef Elmer
 */
public final class PatternVertexCondition implements VertexCondition {
    private final StringPattern _pattern;

    public PatternVertexCondition(final StringPattern pattern) {
        _pattern = pattern;
    }

    @Override
    public boolean isFulfilled(final Vertex vertex) {
        boolean result = false;
        if (vertex != null) {
            final Attributes attributes = vertex.getAttributes();
            if (attributes instanceof NameAttributes) {
                result = _pattern.matches(((NameAttributes) attributes).getName());
            }
        }
        return result;
    }

    @Override
    public String toString() {
        return _pattern.toString();
    }
}


text:
<i-layout>
    <i-layout-header>
        Header
    </i-layout-header>

    <i-layout-content>
        Content
    </i-layout-content>
</i-layout>


text:
double square(double in);

#endif  // __SQUARE_H__


text:
package org.apache.camel.component.file.remote;

import org.apache.camel.CamelContext;
import org.apache.camel.ComponentConfiguration;
import org.apache.camel.EndpointConfiguration;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class FtpComponentConfigurationAndDocumentationTest extends CamelTestSupport {

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    @Test
    public void testComponentConfiguration() throws Exception {
        FtpComponent comp = context.getComponent("ftp", FtpComponent.class);
        EndpointConfiguration conf = comp.createConfiguration("ftp:127.0.0.1?username=foo&password=secret");

        assertEquals("foo", conf.getParameter("username"));
        assertEquals("secret", conf.getParameter("password"));

        ComponentConfiguration compConf = comp.createComponentConfiguration();
        String json = compConf.createParameterJsonSchema();
        assertNotNull(json);

        assertTrue(json.contains("\"host\": { \"kind\": \"path\", \"type\": \"string\""));
        assertTrue(json.contains("\"port\": { \"kind\": \"path\", \"type\": \"integer\""));
        assertTrue(json.contains("\"maximumReconnectAttempts\": { \"kind\": \"parameter\", \"type\": \"integer\""));
        assertTrue(json.contains("\"dataTimeout\": { \"kind\": \"parameter\", \"type\": \"integer\""));
    }

    @Test
    public void testComponentDocumentation() throws Exception {
        CamelContext context = new DefaultCamelContext();
        String html = context.getComponentDocumentation("ftp");
        assertNotNull("Should have found some auto-generated HTML", html);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<extension version="2.5" type="plugin" group="search" method="upgrade" >
	<name>Search - ZOO</name>
	<author>YOOtheme</author>
	<creationDate>January 2015</creationDate>
	<copyright>Copyright (C) YOOtheme GmbH</copyright>
	<license>http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only</license>
	<assetsLicense>YOOtheme Proprietary Use License (http://www.yootheme.com/license)</assetsLicense>
	<authorEmail>info@yootheme.com</authorEmail>
	<authorUrl>http://www.yootheme.com</authorUrl>
	<version>3.3.2</version>
	<description>Search plugin for ZOO developed by YOOtheme (http://www.yootheme.com)</description>
	<files>
		<filename plugin="zoosearch">zoosearch.php</filename>
		<filename>changelog.php</filename>
		<filename>file.script.php</filename>
		<folder>renderer</folder>
	</files>
	<scriptfile>file.script.php</scriptfile>
	<config>
		<fields name="params" >
			<fieldset name="basic">
				<field name="search_fulltext" type="radio" default="0" label="Full-text Search" description="Uses MySQL's search feature for natural language full-text searches">
					<option value="0">JNO</option>
					<option value="1">JYES</option>
				</field>
				<field name="search_limit" type="text" size="5" default="50" label="Search Limit" description="Number of Search items to return"/>
			</fieldset>
		</fields>
	</config>
</extension>


text:
Please don't use in production environments YET!! We still need some tests && feedback.

#### Why
Mysql does not allow wrapping table operations in transactions (Postgresql does), that's
why when you screw one of your migrations, you are basically left in an irreparable broken
state.

So the main idea behind this package is the following:
- We create a testing database for every connection specified by the user (or use the default one).
- We switch the configuration to the new database at runtime, replacing the real database.
- We refresh the connection so that Laravel can use the new configuration.
- We run ``` php artisan migrate ``` against the testing database.
- When done, we drop the testing database.
- Any eventual errors are displayed to the user.
- The real database stays intact.

#### Sqlite not supported
Sqlite databases are not supported for the time being. If someone has an idea that would be great.

#### Install
``` composer require shincoder/harmless-migration:dev-master ```

#### Add the service provider
Edit your ``` config/app.php ``` providers array, add the following:
```php
'Shincoder\Harmless\HarmlessServiceProvider',
```

#### Migrate away
The package has no way to guess which connections you are using.
So if you use multiple database connections you **Must** specify them all using the ``` --database=db1,db2 ``` option.
If not, the command will use the default connection in ``` config/database.php ```.

If you don't specify all your connections, some of you migrations will still be run against your real database.
This shouldn't be an issue if you only use your default connection.

- Default database connection
``` php artisan migrate:test ```

- Multiple database connections
``` php artisan migrate:test --database=defaultConnection1,connection2 ```


text:
/*	$NetBSD: mc146818var.h,v 1.7 2008/05/14 13:29:29 tsutsui Exp $	*/

/*-
 * Copyright (c) 2003 Izumi Tsutsui.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

struct mc146818_softc {
	device_t sc_dev;

	bus_space_tag_t sc_bst;			/* bus space tag */
	bus_space_handle_t sc_bsh;		/* bus space handle */

	struct todr_chip_handle sc_handle;	/* TODR handle */
	u_int sc_year0;				/* year counter offset */
	u_int sc_flag;				/* MD flags */
#define MC146818_NO_CENT_ADJUST	0x0001		/* don't adjust century */
#define MC146818_BCD		0x0002		/* use BCD mode */
#define MC146818_12HR		0x0004		/* use AM/PM mode */

	/* MD chip register read/write functions */
	u_int (*sc_mcread)(struct mc146818_softc *, u_int);
	void (*sc_mcwrite)(struct mc146818_softc *, u_int, u_int);
	/* MD century get/set functions */
	u_int (*sc_getcent)(struct mc146818_softc *);
	void (*sc_setcent)(struct mc146818_softc *, u_int);
};

void mc146818_attach(struct mc146818_softc *);


text:
/* global it */
const iterator = tests =>
  tests.forEach(({ name, test }, indx) => {
    const index = indx + 1;
    it(`${index}. ${name.toLowerCase()}`, () => test());
  });

export default iterator;


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CodeActions
{
    /// <summary>
    /// A <see cref="CodeAction"/> that can vary with user specified options.
    /// </summary>
    public abstract class CodeActionWithOptions : CodeAction
    {
        /// <summary>
        /// Gets the options to use with this code action.
        /// This method is guaranteed to be called on the UI thread.
        /// </summary>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>An implementation specific object instance that holds options for applying the code action.</returns>
        public abstract object GetOptions(CancellationToken cancellationToken);

        /// <summary>
        /// Gets the <see cref="CodeActionOperation"/>'s for this <see cref="CodeAction"/> given the specified options.
        /// </summary>
        /// <param name="options">An object instance returned from a prior call to <see cref="GetOptions(CancellationToken)"/>.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        public async Task<IEnumerable<CodeActionOperation>> GetOperationsAsync(object options, CancellationToken cancellationToken)
        {
            if (options == null)
            {
                return SpecializedCollections.EmptyEnumerable<CodeActionOperation>();
            }

            var operations = await this.ComputeOperationsAsync(options, cancellationToken).ConfigureAwait(false);

            if (operations != null)
            {
                operations = await this.PostProcessAsync(operations, cancellationToken).ConfigureAwait(false);
            }

            return operations;
        }

        internal override async Task<ImmutableArray<CodeActionOperation>> GetOperationsCoreAsync(CancellationToken cancellationToken)
        {
            var options = this.GetOptions(cancellationToken);
            return (await this.GetOperationsAsync(options, cancellationToken).ConfigureAwait(false)).ToImmutableArray();
        }

        /// <summary>
        /// Override this method to compute the operations that implement this <see cref="CodeAction"/>.
        /// </summary>
        /// <param name="options">An object instance returned from a call to <see cref="GetOptions(CancellationToken)"/>.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        protected abstract Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken);

        protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
        {
            return SpecializedTasks.EmptyEnumerable<CodeActionOperation>();
        }
    }
}


text:
package sqlhelper

import (
	"strings"
	"time"

	"log"
	"os"

	_ "github.com/go-sql-driver/mysql" // SQL Driver
	"github.com/jmoiron/sqlx"
	"golang.org/x/crypto/bcrypt"
)

// Hash a password with bcrypt
func Hash(pwd string) (string, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(pwd), 10)
	return string(hash), err
}

// CompareHash of a bcrypt hash
func CompareHash(pwd string, hash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd))
	return err == nil
}

// NewTestDatabase creates a connection to a test database on 127.0.0.1:3306 with no password
func NewTestDatabase() *sqlx.DB {
	database, err := setupDatabase("mysql", "root@tcp(127.0.0.1:3306)/eve?allowOldPasswords=1&parseTime=true&tls=false")
	if err != nil {
		log.Fatalln(err)
	}
	return database
}

// NewDatabase creates a new connection for sql.storage
func NewDatabase() *sqlx.DB {
	database, err := setupDatabase("mysql", os.Getenv("SQLAUTH")+"@tcp(sql.storage.svc.cluster.local:3306)/eve?allowOldPasswords=1&parseTime=true&tls=false")
	if err != nil {
		log.Fatalln(err)
	}
	return database
}

func setupDatabase(driver string, spec string) (*sqlx.DB, error) {
	var err error

	// Build Connection Pool
	database, err := sqlx.Connect(driver, spec)
	if err != nil {
		return nil, err
	}

	// Check we can connect
	if err = database.Ping(); err != nil {
		return nil, err
	}

	// Put some finite limits to prevent opening too many connections
	database.SetConnMaxLifetime(time.Minute * 1)
	database.SetMaxIdleConns(5)
	database.SetMaxOpenConns(30)

	return database, nil
}

// DoSQL executes a sql statement
func DoSQL(db *sqlx.DB, stmt string, args ...interface{}) error {
	for {
		_, err := RetryExec(db, stmt, args...)
		if err != nil {
			if !strings.Contains(err.Error(), "1213") && !strings.Contains(err.Error(), "1205") {
				return err
			}
			time.Sleep(50 * time.Millisecond)
			continue
		} else {
			return err
		}
	}
}

// RetryExecTillNoRows retries the exec until we get no error (deadlocks) and no results are returned
func RetryExecTillNoRows(db *sqlx.DB, sql string, args ...interface{}) error {
	for {
		rows, err := RetryExec(db, sql, args...)
		if err != nil {
			return err
		}
		if rows == 0 {
			break
		}
	}
	return nil
}

// RetryExec retries the exec until we get no error (deadlocks)
func RetryExec(db *sqlx.DB, sql string, args ...interface{}) (int64, error) {
	var rows int64
	for {
		res, err := db.Exec(sql, args...)
		if err == nil {
			rows, err = res.RowsAffected()
			return rows, err
		} else if !strings.Contains(err.Error(), "1213") && !strings.Contains(err.Error(), "1205") {
			return rows, err
		}
	}
}

// RetryTransaction on deadlocks
func RetryTransaction(tx *sqlx.Tx) error {
	for {
		err := tx.Commit()
		if err != nil {
			if !strings.Contains(err.Error(), "1213") && !strings.Contains(err.Error(), "1205") {
				return err
			}
			time.Sleep(50 * time.Millisecond)
			continue
		} else {
			return err
		}
	}
}

// IToB converts a boolean to integer
func IToB(b bool) int {
	if b {
		return 1
	}
	return 0
}


text: Draw some lines


text:
/**
 * Defines root namespace of Kekule.js.
 */

/**
 * @namespace
 * @description Root namespace of Kekule library.
 */
var Kekule = {
	LIBNAME: 'Kekule.js',
	LIBNAME_CORE: 'Kekule',
	VERSION: '0.9.9.22090700',
	/**
	 * A flag that indicate whether all essential Kekule modules are loaded into document.
	 * @ignore
	 */
	LOADED: false,
	/**
	 * An array of functions that need be called after load all Kekule modules.
	 * @private
	 */
	_afterLoadSysProcedures: [],
	/**
	 * An array of user functions that need be called after load all Kekule modules.
	 * @private
	 */
	_afterLoadUserProcedures: [],
	// Whether auto find title and description text for object property
	/** @ignore */
	PROP_AUTO_TITLE: true
};

/**
 * Called when all essential modules is loaded.
 * User should not call this function directly.
 * @private
 */
Kekule._loaded = function()
{
	if (Kekule.LOADED)
		return;
	Kekule.LOADED = true;
	var procs = Kekule._afterLoadSysProcedures;
	while (procs.length)
	{
		var proc = procs.shift();
		if (proc)
		{
			proc();
		}
	}

	var procs = Kekule._afterLoadUserProcedures;
	while (procs.length)
	{
		var proc = procs.shift();
		if (proc)
			proc();
	}

	// at last try fire a custom event
	var doc = Kekule.$jsRoot && Kekule.$jsRoot.document;
	if (doc && doc.createEvent && doc.body && doc.body.dispatchEvent)
	{
		var event = doc.createEvent('Event');
		event.initEvent('kekuleload', true, true);
		doc.body.dispatchEvent(event);
	}
};
/**
 * Return whether the whole lib is loaded.
 * @returns {boolean}
 * @private
 */
Kekule._isLoaded = function()
{
	return Kekule.LOADED;
};
/**
 * Register system procedure that need to be called after all modules are loaded.
 * User should not call this method directly.
 * @param {Func} proc
 * @private
 */
Kekule._registerAfterLoadSysProc = function(proc)
{
	if (proc)
	{
		if (Kekule.LOADED)
			proc();
		else
			Kekule._afterLoadSysProcedures.push(proc);
	}
};
/**
 * Register procedure that need to be called after all modules are loaded and all initial operations has been done.
 * @param {Func} proc
 * @private
 */
Kekule._ready = function(proc)
{
	if (proc)
	{
		if (Kekule.LOADED)
			proc();
		else
			Kekule._afterLoadUserProcedures.push(proc);
	}
};
Kekule._registerAfterLoadProc = Kekule._ready;  // for backward

/**
 * Root object of JavaScript environment, usually window.
 */
Kekule.$jsRoot = this;

if (typeof(self) === 'object')
	Kekule.$jsRoot = self;
else if (typeof(window) === 'object' && window && window.document)
	Kekule.$jsRoot = window;
else if (typeof(global) === 'object')  // node env
	Kekule.$jsRoot = global;

Kekule.$jsRoot.Kekule = Kekule;

if (typeof(window) === 'object' && window && window.document)
	Kekule.window = window;

/**
 * Root document of JavaScript environment.
 * Can be null in Node.js.
 */
Kekule.$document = (this && this.document) || null;

if (!Kekule.scriptSrcInfo)  // scriptSrcInfo maybe set already in node.js environment
{
	Kekule.scriptSrcInfo = Kekule.$jsRoot['__$kekule_load_info__'];
}
if (Kekule.scriptSrcInfo && Kekule.scriptSrcInfo.language)  // force Language
{
	Kekule.language = Kekule.scriptSrcInfo.language;
}
if (!Kekule.scriptSrcInfo && Kekule.$jsRoot.document)  // script info not found, may be use Kekule.min.js directly
{
	Kekule.scriptSrcInfo = (function (doc)
	{
		var matchResult;
		var scriptSrcPattern = /^(.*[\/\\])[^\/\\]*\.js(\?.*)?$/;
		var entranceSrc = /^(.*\/?)kekule\..*\.js(\?.*)?$/;
		var scriptSrc;
		if (doc && doc.currentScript && doc.currentScript.src)
		{
			scriptSrc = decodeURIComponent(doc.currentScript.src);  // sometimes the URL is escaped, ',' becomes '%2C'(e.g. in Moodle)
			if (scriptSrc)
			{
				matchResult = scriptSrc.match(scriptSrcPattern);
			}
		}
		else
		{
			var scriptElems = document.getElementsByTagName('script');
			var loc;
			for (var i = scriptElems.length - 1; i >= 0; --i)
			{
				var elem = scriptElems[i];
				scriptSrc = decodeURIComponent(elem.src);
				if (scriptSrc)
				{
					var matchResult = scriptSrc.match(entranceSrc);
					if (matchResult)
					{
						break;
					}
				}
			}
		}

		if (matchResult)
		{
			var pstr = matchResult[2];
			if (pstr)
				pstr = pstr.substr(1);  // eliminate starting '?'
			var result = {
				'src': scriptSrc,
				'path': matchResult[1],
				'paramStr': pstr,
				'useMinFile': true
			};
			return result;
		}

		return null;
	})(Kekule.$jsRoot.document);
}

if (!Kekule.scriptSrcInfo)
{
	Kekule.scriptSrcInfo = {useMinFile: true};
}

Kekule.environment = {
	scriptInfo: Kekule.scriptSrcInfo,
	isNode: !!((typeof process === 'object') && (typeof process.versions === 'object') && (typeof process.versions.node !== 'undefined')),
	isWeb: !!(typeof window === 'object' && window.document),
	variables: {},
	getEnvVar: function(key)
	{
		return Kekule.environment.variables[key] || (Kekule.$jsRoot['_kekule_environment_'] && Kekule.$jsRoot['_kekule_environment_'][key]);
	},
	setEnvVar: function(key, value)
	{
		Kekule.environment.variables[key] = value;
	}
};  // current runtime environment details

if (Kekule.scriptSrcInfo)
{
	Kekule.environment.nodeModule = Kekule.scriptSrcInfo.nodeModule;
	Kekule.environment.nodeRequire = Kekule.scriptSrcInfo.nodeRequire;
	Kekule.environment.setEnvVar('kekule.path', Kekule.scriptSrcInfo.path);
	Kekule.environment.setEnvVar('kekule.scriptSrc', Kekule.scriptSrcInfo.src);
	Kekule.environment.setEnvVar('kekule.useMinJs', Kekule.scriptSrcInfo.useMinFile);
	Kekule.environment.setEnvVar('kekule.language', Kekule.scriptSrcInfo.language);
}

if (Kekule.$jsRoot['__$kekule_scriptfile_utils__'])  // script file util methods
{
	Kekule._ScriptFileUtils_ = Kekule.$jsRoot['__$kekule_scriptfile_utils__'];
	Kekule.ScriptFileUtils = Kekule._ScriptFileUtils_;  // a default ScriptFileUtils impl, overrided by domUtils.js file
	Kekule.modules = function(modules, callback)   // util function to load additional modules in a existing Kekule environment, useful in node.js
	{
		var actualModules = [];
		if (typeof(modules) === 'string')  // a single string module param
			actualModules = [modules];
		else
			actualModules = modules;  // array param

		var scriptSrcInfo = Kekule.scriptSrcInfo;
		if (scriptSrcInfo)
		{
			var details = Kekule._ScriptFileUtils_.loadModuleScriptFiles(actualModules,
				Kekule.isUsingMinJs(), Kekule.getScriptPath(),
				scriptSrcInfo, function(error){
				if (callback)
					callback(error);
			});
			//console.log(details);
			return this;
		}
		else
			return this;
	};
	Kekule.loadModules = Kekule.modules;  // alias of function Kekule.modules
}

// add some util methods about Kekule.scriptSrcInfo
if (Kekule.scriptSrcInfo)
{
	Kekule.scriptSrcInfo.getValue = function(key)
	{
		return Kekule.scriptSrcInfo[key];
	};
	Kekule.scriptSrcInfo.setValue = function(key, value)
	{
		Kekule.scriptSrcInfo[key] = value;
	}
}

Kekule.getScriptPath = function()
{
	return Kekule.environment.getEnvVar('kekule.path') || Kekule.scriptSrcInfo.path;
};
Kekule.getScriptSrc = function()
{
	return Kekule.environment.getEnvVar('kekule.scriptSrc') || Kekule.scriptSrcInfo.src;
};
Kekule.isUsingMinJs = function()
{
	return Kekule.environment.getEnvVar('kekule.useMinJs') || Kekule.scriptSrcInfo.useMinFile;
};
Kekule.getLanguage = function()
{
	return Kekule.environment.getEnvVar('kekule.language') || Kekule.scriptSrcInfo.language;
};

Kekule._getStyleSheetBasePath = function()
{
	//var cssFileName = 'themes/default/kekule.css';
	var cssPath;
	//var scriptInfo = Kekule.scriptSrcInfo;
	//if (scriptInfo.useMinFile)
	if (Kekule.isUsingMinJs())
		cssPath = Kekule.getScriptPath(); // scriptInfo.path;
	else
		cssPath = Kekule.getScriptPath() + 'widgets/';  // scriptInfo.path + 'widgets/';
	return cssPath;
};
Kekule.getStyleSheetUrl = function()
{
	// TODO: current fixed to default theme
	var result = Kekule.environment.getEnvVar('kekule.themeUrl');
	if (!result)
	{
		var path = Kekule._getStyleSheetBasePath();
		result = path + 'themes/default/kekule.css';
	}
	return result;
};

if (Kekule.$jsRoot && Kekule.$jsRoot.addEventListener && Kekule.$jsRoot.postMessage)
{
	// response to special message, returns Kekule sys info.
	// This query is usually requested by browser addon to check
	// if Kekule lib is loaded into a web page
	Kekule.$jsRoot.addEventListener('message', function(event)
	{
		if (event.data === 'kekule-sys-info-query')
		{
			Kekule.$jsRoot.postMessage({
				'msg': 'kekule-sys-info-result',
				'libName': Kekule.LIBNAME,
				'version': Kekule.VERSION
				//'scriptSrcInfo': Kekule.scriptSrcInfo
			}, '*');
		}
	}, false);
}

/**
 * A namespace for development tools.
 * @namespace
 */
Kekule.Dev = {};

// Also store Class/ClassEx/ObjectEx/DataType in Kekule namespace
/** @ignore */
Kekule.Class = Class;
Kekule.ClassEx = ClassEx;
Kekule.ObjectEx = ObjectEx;
Kekule.DataType = DataType;


text:
require 'uri'
require 'json'

module Jekyll
  module Filters
    # Convert a Textile string into HTML output.
    #
    # input - The Textile String to convert.
    #
    # Returns the HTML formatted String.
    def textilize(input)
      site = @context.registers[:site]
      converter = site.getConverterImpl(Jekyll::Converters::Textile)
      converter.convert(input)
    end

    # Convert a Markdown string into HTML output.
    #
    # input - The Markdown String to convert.
    #
    # Returns the HTML formatted String.
    def markdownify(input)
      site = @context.registers[:site]
      converter = site.getConverterImpl(Jekyll::Converters::Markdown)
      converter.convert(input)
    end

    # Convert a Sass string into CSS output.
    #
    # input - The Sass String to convert.
    #
    # Returns the CSS formatted String.
    def sassify(input)
      site = @context.registers[:site]
      converter = site.getConverterImpl(Jekyll::Converters::Sass)
      converter.convert(input)
    end

    # Convert a Scss string into CSS output.
    #
    # input - The Scss String to convert.
    #
    # Returns the CSS formatted String.
    def scssify(input)
      site = @context.registers[:site]
      converter = site.getConverterImpl(Jekyll::Converters::Scss)
      converter.convert(input)
    end

    # Format a date in short format e.g. "27 Jan 2011".
    #
    # date - the Time to format.
    #
    # Returns the formatting String.
    def date_to_string(date)
      time(date).strftime("%d %b %Y")
    end

    # Format a date in long format e.g. "27 January 2011".
    #
    # date - The Time to format.
    #
    # Returns the formatted String.
    def date_to_long_string(date)
      time(date).strftime("%d %B %Y")
    end

    # Format a date for use in XML.
    #
    # date - The Time to format.
    #
    # Examples
    #
    #   date_to_xmlschema(Time.now)
    #   # => "2011-04-24T20:34:46+08:00"
    #
    # Returns the formatted String.
    def date_to_xmlschema(date)
      time(date).xmlschema
    end

    # Format a date according to RFC-822
    #
    # date - The Time to format.
    #
    # Examples
    #
    #   date_to_rfc822(Time.now)
    #   # => "Sun, 24 Apr 2011 12:34:46 +0000"
    #
    # Returns the formatted String.
    def date_to_rfc822(date)
      time(date).rfc822
    end

    # XML escape a string for use. Replaces any special characters with
    # appropriate HTML entity replacements.
    #
    # input - The String to escape.
    #
    # Examples
    #
    #   xml_escape('foo "bar" <baz>')
    #   # => "foo "bar" <baz>"
    #
    # Returns the escaped String.
    def xml_escape(input)
      CGI.escapeHTML(input.to_s)
    end

    # CGI escape a string for use in a URL. Replaces any special characters
    # with appropriate %XX replacements.
    #
    # input - The String to escape.
    #
    # Examples
    #
    #   cgi_escape('foo,bar;baz?')
    #   # => "foo%2Cbar%3Bbaz%3F"
    #
    # Returns the escaped String.
    def cgi_escape(input)
      CGI::escape(input)
    end

    # URI escape a string.
    #
    # input - The String to escape.
    #
    # Examples
    #
    #   uri_escape('foo, bar \\baz?')
    #   # => "foo,%20bar%20%5Cbaz?"
    #
    # Returns the escaped String.
    def uri_escape(input)
      URI.escape(input)
    end

    # Count the number of words in the input string.
    #
    # input - The String on which to operate.
    #
    # Returns the Integer word count.
    def number_of_words(input)
      input.split.length
    end

    # Join an array of things into a string by separating with commas and the
    # word "and" for the last one.
    #
    # array - The Array of Strings to join.
    #
    # Examples
    #
    #   array_to_sentence_string(["apples", "oranges", "grapes"])
    #   # => "apples, oranges, and grapes"
    #
    # Returns the formatted String.
    def array_to_sentence_string(array)
      connector = "and"
      case array.length
      when 0
        ""
      when 1
        array[0].to_s
      when 2
        "#{array[0]} #{connector} #{array[1]}"
      else
        "#{array[0...-1].join(', ')}, #{connector} #{array[-1]}"
      end
    end

    # Convert the input into json string
    #
    # input - The Array or Hash to be converted
    #
    # Returns the converted json string
    def jsonify(input)
      as_liquid(input).to_json
    end

    # Group an array of items by a property
    #
    # input - the inputted Enumerable
    # property - the property
    #
    # Returns an array of Hashes, each looking something like this:
    #  {"name"  => "larry"
    #   "items" => [...] } # all the items where `property` == "larry"
    def group_by(input, property)
      if groupable?(input)
        input.group_by do |item|
          item_property(item, property).to_s
        end.inject([]) do |memo, i|
          memo << {"name" => i.first, "items" => i.last}
        end
      else
        input
      end
    end

    # Filter an array of objects
    #
    # input - the object array
    # key - key within each object to filter by
    # value - desired value
    #
    # Returns the filtered array of objects
    def where(input, property, value)
      return input unless input.is_a?(Array)
      input.select { |object| item_property(object, property) == value }
    end

    # Sort an array of objects
    #
    # input - the object array
    # property - property within each object to filter by
    # nils ('first' | 'last') - nils appear before or after non-nil values
    #
    # Returns the filtered array of objects
    def sort(input, property = nil, nils = "first")
      if property.nil?
        input.sort
      else
        case
        when nils == "first"
          order = - 1
        when nils == "last"
          order = + 1
        else
          raise ArgumentError.new("Invalid nils order: " +
            "'#{nils}' is not a valid nils order. It must be 'first' or 'last'.")
        end

        input.sort { |apple, orange|
          apple_property = item_property(apple, property)
          orange_property = item_property(orange, property)

          if !apple_property.nil? && orange_property.nil?
            - order
          elsif apple_property.nil? && !orange_property.nil?
            + order
          else
            apple_property <=> orange_property
          end
        }
      end
    end

    private
    def time(input)
      case input
      when Time
        input
      when String
        Time.parse(input) rescue Time.at(input.to_i)
      when Numeric
        Time.at(input)
      else
        Jekyll.logger.error "Invalid Date:", "'#{input}' is not a valid datetime."
        exit(1)
      end
    end

    def groupable?(element)
      element.respond_to?(:group_by)
    end

    def item_property(item, property)
      if item.respond_to?(:to_liquid)
        item.to_liquid[property.to_s]
      elsif item.respond_to?(:data)
        item.data[property.to_s]
      else
        item[property.to_s]
      end
    end

    def as_liquid(item)
      item.respond_to?(:to_liquid) ? item.to_liquid : item
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using Hapikit;
using Hapikit.Links;
using Hapikit.Links.IANA;

using Xunit;

namespace LinkTests
{
    public class LinkHeaderTests
    {

        [Fact]
        public void CreateALinkHeader()
        {
            var request = new HttpRequestMessage();
            var about = new AboutLink() { Target = new Uri("http://example.org/about")};

            request.Headers.AddLinkHeader(about);

            var header = request.Headers.GetValues("Link").First().ToString();
            Assert.Equal("<http://example.org/about>;rel=\"about\"",header);
        }

        [Fact]
        public void CreateTwoLinkHeaders()
        {
            var request = new HttpRequestMessage();
            var about = new AboutLink() { Target = new Uri("http://example.org/about") };
            var help = new HelpLink() { Target = new Uri("http://example.org/help") };

            request.Headers.AddLinkHeader(about);
            request.Headers.AddLinkHeader(help);

            var headers = request.Headers.GetValues("Link");

            Assert.Equal("<http://example.org/about>;rel=\"about\"", headers.First().ToString());
            Assert.Equal("<http://example.org/help>;rel=\"help\"", headers.Last().ToString());
        }

        [Fact]
        public void ParseLinkHeaders()
        {
            var linkRegistry = new LinkFactory();

            var response = new HttpResponseMessage();
            response.RequestMessage = new HttpRequestMessage() { RequestUri = new Uri("http://example.org/") };
            response.Headers.AddLinkHeader(new AboutLink() { Target = new Uri("http://example.org/about") });
            response.Headers.AddLinkHeader(new HelpLink() { Target = new Uri("http://example.org/help") });

            var links = response.ParseLinkHeaders(linkRegistry);

            Assert.Equal(2,links.Count);
            Assert.NotNull(links.Where(l => l is AboutLink).FirstOrDefault());
            Assert.NotNull(links.Where(l => l is HelpLink).FirstOrDefault());
        }

        [Fact]
        public void ParseLinkHeaders2()
        {
            var linkRegistry = new LinkFactory();
            var response = new HttpResponseMessage();
            response.RequestMessage = new HttpRequestMessage() { RequestUri = new Uri("http://example.org/") };
            response.Headers.TryAddWithoutValidation("Link", "<http://example.org/about>;rel=\"about\", "
                                + "<http://example.org/help>;rel=\"help\"");
            var links = response.ParseLinkHeaders(linkRegistry);

            Assert.NotNull(links.Where(l => l is AboutLink).FirstOrDefault());
            Assert.NotNull(links.Where(l => l is HelpLink).FirstOrDefault());

        }

        [Fact]
        public void ParseLinkHeaders3()
        {
            var linkRegistry = new LinkFactory();
            var response = new HttpResponseMessage();
            response.RequestMessage = new HttpRequestMessage() { RequestUri = new Uri("http://example.org/") };
            var list = new List<ILink>() {
                new AboutLink() { Target = new Uri("http://example.org/about")},
                new HelpLink() { Target = new Uri("http://example.org/help") }
            };
            response.Headers.AddLinkHeaders(list);

            var links = response.ParseLinkHeaders(linkRegistry);

            Assert.NotNull(links.Where(l => l is AboutLink).FirstOrDefault());
            Assert.NotNull(links.Where(l => l is HelpLink).FirstOrDefault());

        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Crocynia nipharga Ach.

### Remarks
null


text:
package storage

import (
	. "github.com/onsi/ginkgo/v2"
)

func SIGDescribe(text string, args ...interface{}) bool {
	return Describe("[sig-storage] "+text, args)
}

func FSIGDescribe(text string, args ...interface{}) bool {
	return FDescribe("[sig-storage] "+text, args)
}

func PSIGDescribe(text string, args ...interface{}) bool {
	return PDescribe("[sig-storage] "+text, args)
}


text:
package org.apache.struts2.convention;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.FileManager;
import com.opensymphony.xwork2.FileManagerFactory;
import com.opensymphony.xwork2.XWorkException;
import com.opensymphony.xwork2.util.finder.ClassFinder;
import com.opensymphony.xwork2.util.finder.ClassLoaderInterface;
import com.opensymphony.xwork2.util.finder.Test;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

/**
 * Copy of {@link com.opensymphony.xwork2.util.finder.DefaultClassFinder} with proper support for Java8
 */
public class Java8ClassFinder implements ClassFinder {

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

    private final Map<String, List<Info>> annotated = new HashMap<String, List<Info>>();
    private final Map<String, ClassInfo> classInfos = new LinkedHashMap<String, ClassInfo>();

    private final List<String> classesNotLoaded = new ArrayList<String>();

    private boolean extractBaseInterfaces;
    private ClassLoaderInterface classLoaderInterface;
    private FileManager fileManager;

    public Java8ClassFinder(ClassLoaderInterface classLoaderInterface, Collection<URL> urls, boolean extractBaseInterfaces, Set<String> protocols, Test<String> classNameFilter) {
        this.classLoaderInterface = classLoaderInterface;
        this.extractBaseInterfaces = extractBaseInterfaces;
        this.fileManager = ActionContext.getContext().getInstance(FileManagerFactory.class).getFileManager();

        List<String> classNames = new ArrayList<String>();
        for (URL location : urls) {
            try {
                if (protocols.contains(location.getProtocol())) {
                    classNames.addAll(jar(location));
                } else if ("file".equals(location.getProtocol())) {
                    try {
                        // See if it's actually a jar
                        URL jarUrl = new URL("jar", "", location.toExternalForm() + "!/");
                        JarURLConnection juc = (JarURLConnection) jarUrl.openConnection();
                        juc.getJarFile();
                        classNames.addAll(jar(jarUrl));
                    } catch (IOException e) {
                        classNames.addAll(file(location));
                    }
                }
            } catch (Exception e) {
                if (LOG.isErrorEnabled())
                    LOG.error("Unable to read URL [#0]", e, location.toExternalForm());
            }
        }

        for (String className : classNames) {
            try {
                if (classNameFilter.test(className))
                    readClassDef(className);
            } catch (Throwable e) {
                if (LOG.isErrorEnabled())
                    LOG.error("Unable to read class [#0]", e, className);
            }
        }
    }

    public Java8ClassFinder(Class... classes){
        this(Arrays.asList(classes));
    }

    public Java8ClassFinder(List<Class> classes){
        this.classLoaderInterface = null;
        List<Info> infos = new ArrayList<Info>();
        List<Package> packages = new ArrayList<Package>();
        for (Class clazz : classes) {

            Package aPackage = clazz.getPackage();
            if (aPackage != null && !packages.contains(aPackage)){
                infos.add(new PackageInfo(aPackage));
                packages.add(aPackage);
            }

            ClassInfo classInfo = new ClassInfo(clazz, this);
            infos.add(classInfo);
            classInfos.put(classInfo.getName(), classInfo);
            for (Method method : clazz.getDeclaredMethods()) {
                infos.add(new MethodInfo(classInfo, method));
            }

            for (Constructor constructor : clazz.getConstructors()) {
                infos.add(new MethodInfo(classInfo, constructor));
            }

            for (Field field : clazz.getDeclaredFields()) {
                infos.add(new FieldInfo(classInfo, field));
            }
        }

        for (Info info : infos) {
            for (AnnotationInfo annotation : info.getAnnotations()) {
                List<Info> annotationInfos = getAnnotationInfos(annotation.getName());
                annotationInfos.add(info);
            }
        }
    }

    public ClassLoaderInterface getClassLoaderInterface() {
        return classLoaderInterface;
    }

    public boolean isAnnotationPresent(Class<? extends Annotation> annotation) {
        List<Info> infos = annotated.get(annotation.getName());
        return infos != null && !infos.isEmpty();
    }

    public List<String> getClassesNotLoaded() {
        return Collections.unmodifiableList(classesNotLoaded);
    }

    public List<Package> findAnnotatedPackages(Class<? extends Annotation> annotation) {
        classesNotLoaded.clear();
        List<Package> packages = new ArrayList<Package>();
        List<Info> infos = getAnnotationInfos(annotation.getName());
        for (Info info : infos) {
            if (info instanceof PackageInfo) {
                PackageInfo packageInfo = (PackageInfo) info;
                try {
                    Package pkg = packageInfo.get();
                    // double check via proper reflection
                    if (pkg.isAnnotationPresent(annotation)) {
                        packages.add(pkg);
                    }
                } catch (ClassNotFoundException e) {
                    classesNotLoaded.add(packageInfo.getName());
                }
            }
        }
        return packages;
    }

    public List<Class> findAnnotatedClasses(Class<? extends Annotation> annotation) {
        classesNotLoaded.clear();
        List<Class> classes = new ArrayList<Class>();
        List<Info> infos = getAnnotationInfos(annotation.getName());
        for (Info info : infos) {
            if (info instanceof ClassInfo) {
                ClassInfo classInfo = (ClassInfo) info;
                try {
                    Class clazz = classInfo.get();
                    // double check via proper reflection
                    if (clazz.isAnnotationPresent(annotation)) {
                        classes.add(clazz);
                    }
                } catch (Throwable e) {
                    if (LOG.isErrorEnabled())
                        LOG.error("Error loading class [#0]", e, classInfo.getName());
                    classesNotLoaded.add(classInfo.getName());
                }
            }
        }
        return classes;
    }

    public List<Method> findAnnotatedMethods(Class<? extends Annotation> annotation) {
        classesNotLoaded.clear();
        List<ClassInfo> seen = new ArrayList<ClassInfo>();
        List<Method> methods = new ArrayList<Method>();
        List<Info> infos = getAnnotationInfos(annotation.getName());
        for (Info info : infos) {
            if (info instanceof MethodInfo && !"<init>".equals(info.getName())) {
                MethodInfo methodInfo = (MethodInfo) info;
                ClassInfo classInfo = methodInfo.getDeclaringClass();

                if (seen.contains(classInfo)) continue;

                seen.add(classInfo);

                try {
                    Class clazz = classInfo.get();
                    for (Method method : clazz.getDeclaredMethods()) {
                        if (method.isAnnotationPresent(annotation)) {
                            methods.add(method);
                        }
                    }
                } catch (Throwable e) {
                    if (LOG.isErrorEnabled())
                        LOG.error("Error loading class [#0]", e, classInfo.getName());
                    classesNotLoaded.add(classInfo.getName());
                }
            }
        }
        return methods;
    }

    public List<Constructor> findAnnotatedConstructors(Class<? extends Annotation> annotation) {
        classesNotLoaded.clear();
        List<ClassInfo> seen = new ArrayList<ClassInfo>();
        List<Constructor> constructors = new ArrayList<Constructor>();
        List<Info> infos = getAnnotationInfos(annotation.getName());
        for (Info info : infos) {
            if (info instanceof MethodInfo && "<init>".equals(info.getName())) {
                MethodInfo methodInfo = (MethodInfo) info;
                ClassInfo classInfo = methodInfo.getDeclaringClass();

                if (seen.contains(classInfo)) continue;

                seen.add(classInfo);

                try {
                    Class clazz = classInfo.get();
                    for (Constructor constructor : clazz.getConstructors()) {
                        if (constructor.isAnnotationPresent(annotation)) {
                            constructors.add(constructor);
                        }
                    }
                } catch (Throwable e) {
                    if (LOG.isErrorEnabled())
                        LOG.error("Error loading class [#0]", e, classInfo.getName());
                    classesNotLoaded.add(classInfo.getName());
                }
            }
        }
        return constructors;
    }

    public List<Field> findAnnotatedFields(Class<? extends Annotation> annotation) {
        classesNotLoaded.clear();
        List<ClassInfo> seen = new ArrayList<ClassInfo>();
        List<Field> fields = new ArrayList<Field>();
        List<Info> infos = getAnnotationInfos(annotation.getName());
        for (Info info : infos) {
            if (info instanceof FieldInfo) {
                FieldInfo fieldInfo = (FieldInfo) info;
                ClassInfo classInfo = fieldInfo.getDeclaringClass();

                if (seen.contains(classInfo)) continue;

                seen.add(classInfo);

                try {
                    Class clazz = classInfo.get();
                    for (Field field : clazz.getDeclaredFields()) {
                        if (field.isAnnotationPresent(annotation)) {
                            fields.add(field);
                        }
                    }
                } catch (Throwable e) {
                    if (LOG.isErrorEnabled())
                        LOG.error("Error loading class [#0]", e, classInfo.getName());
                    classesNotLoaded.add(classInfo.getName());
                }
            }
        }
        return fields;
    }

    public List<Class> findClassesInPackage(String packageName, boolean recursive) {
        classesNotLoaded.clear();
        List<Class> classes = new ArrayList<Class>();
        for (ClassInfo classInfo : classInfos.values()) {
            try {
                if (recursive && classInfo.getPackageName().startsWith(packageName)){
                    classes.add(classInfo.get());
                } else if (classInfo.getPackageName().equals(packageName)){
                    classes.add(classInfo.get());
                }
            } catch (Throwable e) {
                if (LOG.isErrorEnabled())
                    LOG.error("Error loading class [#0]", e, classInfo.getName());
                classesNotLoaded.add(classInfo.getName());
            }
        }
        return classes;
    }

    public List<Class> findClasses(Test<ClassInfo> test) {
        classesNotLoaded.clear();
        List<Class> classes = new ArrayList<Class>();
        for (ClassInfo classInfo : classInfos.values()) {
            try {
                if (test.test(classInfo)) {
                    classes.add(classInfo.get());
                }
            } catch (Throwable e) {
                if (LOG.isErrorEnabled())
                    LOG.error("Error loading class [#0]", e, classInfo.getName());
                classesNotLoaded.add(classInfo.getName());
            }
        }
        return classes;
    }

    public List<Class> findClasses() {
        classesNotLoaded.clear();
        List<Class> classes = new ArrayList<Class>();
        for (ClassInfo classInfo : classInfos.values()) {
            try {
                classes.add(classInfo.get());
            } catch (Throwable e) {
                if (LOG.isErrorEnabled())
                    LOG.error("Error loading class [#0]", e, classInfo.getName());
                classesNotLoaded.add(classInfo.getName());
            }
        }
        return classes;
    }

    private static List<URL> getURLs(ClassLoaderInterface classLoader, String[] dirNames) {
        List<URL> urls = new ArrayList<URL>();
        for (String dirName : dirNames) {
            try {
                Enumeration<URL> classLoaderURLs = classLoader.getResources(dirName);
                while (classLoaderURLs.hasMoreElements()) {
                    URL url = classLoaderURLs.nextElement();
                    urls.add(url);
                }
            } catch (IOException ioe) {
                if (LOG.isErrorEnabled())
                    LOG.error("Could not read driectory [#0]", ioe, dirName);
            }
        }

        return urls;
    }

    private List<String> file(URL location) {
        List<String> classNames = new ArrayList<String>();
        File dir = new File(URLDecoder.decode(location.getPath()));
        if ("META-INF".equals(dir.getName())) {
            dir = dir.getParentFile(); // Scrape "META-INF" off
        }
        if (dir.isDirectory()) {
            scanDir(dir, classNames, "");
        }
        return classNames;
    }

    private void scanDir(File dir, List<String> classNames, String packageName) {
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                scanDir(file, classNames, packageName + file.getName() + ".");
            } else if (file.getName().endsWith(".class")) {
                String name = file.getName();
                name = name.replaceFirst(".class$", "");
                // Classes packaged in an exploded .war (e.g. in a VFS file system) should not
                // have WEB-INF.classes in their package name.
                classNames.add(StringUtils.removeStart(packageName, "WEB-INF.classes.") + name);
            }
        }
    }

    private List<String> jar(URL location) throws IOException {
        URL url = fileManager.normalizeToFileProtocol(location);
        if (url != null) {
            InputStream in = url.openStream();
            try {
                JarInputStream jarStream = new JarInputStream(in);
                return jar(jarStream);
            } finally {
                in.close();
            }
        } else if (LOG.isDebugEnabled())
            LOG.debug("Unable to read [#0]", location.toExternalForm());

        return Collections.emptyList();
    }

    private List<String> jar(JarInputStream jarStream) throws IOException {
        List<String> classNames = new ArrayList<String>();

        JarEntry entry;
        while ((entry = jarStream.getNextJarEntry()) != null) {
            if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
                continue;
            }
            String className = entry.getName();
            className = className.replaceFirst(".class$", "");

            //war files are treated as .jar files, so takeout WEB-INF/classes
            className = StringUtils.removeStart(className, "WEB-INF/classes/");

            className = className.replace('/', '.');
            classNames.add(className);
        }

        return classNames;
    }

    private List<Info> getAnnotationInfos(String name) {
        List<Info> infos = annotated.get(name);
        if (infos == null) {
            infos = new ArrayList<Info>();
            annotated.put(name, infos);
        }
        return infos;
    }

    private void readClassDef(String className) {
        if (!className.endsWith(".class")) {
            className = className.replace('.', '/') + ".class";
        }
        try {
            URL resource = classLoaderInterface.getResource(className);
            if (resource != null) {
                InputStream in = resource.openStream();
                try {
                    ClassReader classReader = new ClassReader(in);
                    classReader.accept(new InfoBuildingClassVisitor(this), ClassReader.SKIP_DEBUG);
                } finally {
                    in.close();
                }
            } else {
                throw new XWorkException("Could not load " + className);
            }
        } catch (IOException e) {
            throw new XWorkException("Could not load " + className, e);
        }

    }

    public class InfoBuildingClassVisitor extends ClassVisitor {
        private Info info;
        private ClassFinder classFinder;

        public InfoBuildingClassVisitor(ClassFinder classFinder) {
            super(Opcodes.ASM5);
            this.classFinder = classFinder;
        }

        public InfoBuildingClassVisitor(Info info, ClassFinder classFinder) {
            this(classFinder);
            this.info = info;
        }

        @Override
        public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
            if (name.endsWith("package-info")) {
                info = new PackageInfo(javaName(name), classFinder);
            } else {
                ClassInfo classInfo = new ClassInfo(javaName(name), javaName(superName), classFinder);

                for (String interfce : interfaces) {
                    classInfo.getInterfaces().add(javaName(interfce));
                }
                info = classInfo;
                classInfos.put(classInfo.getName(), classInfo);

                if (extractBaseInterfaces)
                    extractSuperInterfaces(classInfo);
            }
        }

        private void extractSuperInterfaces(ClassInfo classInfo) {
            String superType = classInfo.getSuperType();

            if (superType != null) {
                ClassInfo base = classInfos.get(superType);

                if (base == null) {
                    //try to load base
                    String resource = superType.replace('.', '/') + ".class";
                    readClassDef(resource);
                    base = classInfos.get(superType);
                }

                if (base != null) {
                    List<String> interfaces = classInfo.getSuperInterfaces();
                    interfaces.addAll(base.getSuperInterfaces());
                    interfaces.addAll(base.getInterfaces());
                }
            }
        }

        private String javaName(String name) {
            return (name == null)? null:name.replace('/', '.');
        }

        @Override
        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
            AnnotationInfo annotationInfo = new AnnotationInfo(desc);
            info.getAnnotations().add(annotationInfo);
            getAnnotationInfos(annotationInfo.getName()).add(info);
            return null;
        }

        @Override
        public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
            ClassInfo classInfo = ((ClassInfo) info);
            FieldInfo fieldInfo = new FieldInfo(classInfo, name, desc);
            classInfo.getFields().add(fieldInfo);
            return null;
        }

        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
            ClassInfo classInfo = ((ClassInfo) info);
            MethodInfo methodInfo = new MethodInfo(classInfo, name, desc);
            classInfo.getMethods().add(methodInfo);
            return new InfoBuildingMethodVisitor(methodInfo);
        }
    }

    public class InfoBuildingMethodVisitor extends MethodVisitor {
        private Info info;

        public InfoBuildingMethodVisitor() {
            super(Opcodes.ASM5);
        }

        public InfoBuildingMethodVisitor(Info info) {
            this();
            this.info = info;
        }

        @Override
        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
            AnnotationInfo annotationInfo = new AnnotationInfo(desc);
            info.getAnnotations().add(annotationInfo);
            getAnnotationInfos(annotationInfo.getName()).add(info);
            return null;
        }

        @Override
        public AnnotationVisitor visitParameterAnnotation(int param, String desc, boolean visible) {
            MethodInfo methodInfo = ((MethodInfo) info);
            List<AnnotationInfo> annotationInfos = methodInfo.getParameterAnnotations(param);
            AnnotationInfo annotationInfo = new AnnotationInfo(desc);
            annotationInfos.add(annotationInfo);
            return null;
        }
    }

    private static final class DefaultClassnameFilterImpl implements Test<String> {
        public boolean test(String className) {
            return true;
        }
    }
}


text:
public class ScreenView
{
    private static int BUF_SIZE = 1024;
    private Screen screen;

    public void notify(Change change) {
        boolean restart = false;
        if (change.equals(Change.MOVE)
            || v.equals(Change.REPAINT)
            || (restart = v.equals(Change.RESTART))  // AVOID: Confusing assignment in condition
            || v.equals(Change.FLIP))
        {
            if (restart)
                WindowManager.restart();
            screen.update();
        }
    }

    // ...

    public void readConfiguration(InputStream config) {
        byte[] buf = new byte[BUF_SIZE];
        int read;
        while ((read = config.read(buf)) > 0) {  // OK: Assignment whose result is compared to
                                                 // another value
            // ...
        }
        // ...
    }
}