text:
package inputOutput;

import inputOutput.Attributes.AttributeName;
import inputOutput.Attributes.ExchangeIn;
import inputOutput.Attributes.ExchangeOut;
import inputOutput.Attributes.NodeAttributeName;
import inputOutput.Attributes.NodeIn;
import inputOutput.Attributes.NodeOut;
import inputOutput.Attributes.PersonAttributeName;
import inputOutput.Attributes.PersonIn;
import inputOutput.Attributes.ReceiverIn;
import inputOutput.core.Attribute;
import inputOutput.core.AttributeConverter;
import inputOutput.core.Converters;
import inputOutput.core.CsvFormatUtil;
import inputOutput.core.DoubleTimeDifferenceCalculator;
import inputOutput.core.JodaTimeDifference;
import inputOutput.core.Report;
import inputOutput.core.TimeDifferenceCalc;
import inputOutput.node.NodeInputAttributeDefaultConverters;
import inputOutput.node.NodeInputAttributes;
import inputOutput.node.NodeOutputAttributeDefaultConverters;
import inputOutput.node.NodeOutputAttributes;
import inputOutput.node.exchangeUnit.ExchangeInputAttributeDefaultConverters;
import inputOutput.node.exchangeUnit.ExchangeInputAttributes;
import inputOutput.node.exchangeUnit.ExchangeOutputAttributeDefaultConverters;
import inputOutput.node.exchangeUnit.ExchangeOutputAttributes;
import inputOutput.node.exchangeUnit.PersonInputAttributeDefaultConverters;
import inputOutput.node.exchangeUnit.PersonInputAttributes;
import inputOutput.node.exchangeUnit.ReceiverInputAttributeDefaultConverters;
import inputOutput.node.exchangeUnit.ReceiverInputAttributes;
import inputOutput.node.unosExchangeUnit.UnosDonorInputAttributes;
import inputOutput.node.unosExchangeUnit.UnosNodeInputAttributes;
import inputOutput.node.unosExchangeUnit.UnosPatientInputAttributes;

import java.util.ArrayList;
import java.util.List;

import kepModeler.ExchangeUnitAuxiliaryInputStatistics;
import multiPeriod.DynamicMatching;
import multiPeriod.MultiPeriodCyclePacking;
import multiPeriod.MultiPeriodCyclePacking.MultiPeriodCyclePackingInputs;

import org.joda.time.Interval;
import org.joda.time.ReadableInstant;

import protoModeler.UnosPredicateBuilder.UnosHistoricData;
import replicator.DonorEdge;
import unosData.UnosDonorEdge;
import unosData.UnosExchangeUnit;
import data.Donor;
import data.ExchangeUnit;
import data.Receiver;

public class Reports {

  public static enum DonorOptions {
    matchedDonorOnly, matchedDonorOrFirst, donorsInOrder;
  }

  public static interface NodeColumn {
    public String getName();

    public void setName(String name);

    public NodeAttributeName getAttributeName();
  }

  public static class PersonColumn implements NodeColumn {
    private boolean isDonor;
    private DonorOptions donorOption;
    private int donorIndex;
    private PersonAttributeName personAttributeName;
    private String name;

    public static PersonColumn receiverColumn(PersonIn personIn) {
      return new PersonColumn(personIn);
    }

    public static PersonColumn receiverColumn(ReceiverIn receiverIn) {
      return new PersonColumn(receiverIn);
    }

    public static PersonColumn donorColumn(PersonIn personIn,
        DonorOptions donorOption, int donorNumber) {
      String prefix;
      if (donorOption == null) {
        throw new NullPointerException();
      } else if (donorOption == DonorOptions.donorsInOrder) {
        prefix = "Donor " + donorNumber + " ";
      } else if (donorOption == DonorOptions.matchedDonorOnly) {
        prefix = "Matched Donor ";
      } else if (donorOption == DonorOptions.matchedDonorOrFirst) {
        prefix = "Matched/First Donor ";
      } else {
        throw new UnsupportedOperationException();
      }
      return new PersonColumn(true, donorOption, donorNumber, personIn, prefix
          + personIn.getDefaultName());
    }

    private PersonColumn(PersonAttributeName personAttributeName) {
      this(false, null, 0, personAttributeName, "Receiver "
          + personAttributeName.getDefaultName());
    }

    private PersonColumn(boolean isDonor, DonorOptions donorOption,
        int donorIndex, PersonAttributeName personAttributeName, String name) {
      super();
      this.isDonor = isDonor;
      this.donorOption = donorOption;
      this.donorIndex = donorIndex;
      this.personAttributeName = personAttributeName;
      this.name = name;
    }

    @Override
    public String getName() {
      return this.name;
    }

    @Override
    public PersonAttributeName getAttributeName() {
      return personAttributeName;
    }

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

    public boolean isDonor() {
      return isDonor;
    }

    public DonorOptions getDonorOption() {
      return donorOption;
    }

    public int getDonorIndex() {
      return donorIndex;
    }

  }

  public static class AttributeColumn implements NodeColumn {
    private NodeAttributeName attributeName;
    private String name;

    public AttributeColumn(ExchangeIn exchangeIn) {
      this(exchangeIn, exchangeIn.getDefaultName());
    }

    public AttributeColumn(ExchangeOut exchangeOut) {
      this(exchangeOut, exchangeOut.getDefaultName());
    }

    public AttributeColumn(NodeIn nodeIn) {
      this(nodeIn, nodeIn.getDefaultName());
    }

    public AttributeColumn(NodeOut nodeOut) {
      this(nodeOut, nodeOut.getDefaultName());
    }

    private AttributeColumn(NodeAttributeName nodeAttributeName, String name) {
      this.attributeName = nodeAttributeName;
      this.name = name;
    }

    @Override
    public String getName() {
      return name;
    }

    @Override
    public NodeAttributeName getAttributeName() {
      return this.attributeName;
    }

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

  public static Report<ExchangeUnit> makeOutputReport(
      Iterable<? extends NodeAttributeName> attributes, TitleMode titleMode,
      ExchangeOutputConverterSet converterSet, DonorOptions donorOptions,
      int numDonors) {
    List<NodeAttributeName> exchangeUnitAttributes = new ArrayList<NodeAttributeName>();
    List<PersonAttributeName> receiverAttributes = new ArrayList<PersonAttributeName>();
    List<PersonAttributeName> donorAttributes = new ArrayList<PersonAttributeName>();
    for (NodeAttributeName attributeName : attributes) {
      if (attributeName instanceof ExchangeIn
          || attributeName instanceof ExchangeOut
          || attributeName instanceof NodeIn
          || attributeName instanceof NodeOut) {
        exchangeUnitAttributes.add(attributeName);
      } else if (attributeName instanceof PersonIn) {
        receiverAttributes.add((PersonIn) attributeName);
        donorAttributes.add((PersonIn) attributeName);
      } else if (attributeName instanceof ReceiverIn) {
        receiverAttributes.add((ReceiverIn) attributeName);
      } else {
        throw new UnsupportedOperationException("attribute "
            + attributeName.getDefaultName() + " is of unsupported Type "
            + AttributeName.class.getName());
      }
    }
    return makeOutputReport(exchangeUnitAttributes, receiverAttributes,
        donorAttributes, titleMode, converterSet, donorOptions, numDonors);
  }

  private static <T extends NodeAttributeName> void processAttribute(
      List<AttributeConverter<ExchangeUnit>> converters,
      Converters<T, ExchangeUnit> converterMap, T attributeName) {
    converters.add(converterMap.get(attributeName));
  }

  public static Report<ExchangeUnit> makeOutputReport(
      Iterable<? extends NodeColumn> columns, TitleMode titleMode,
      ExchangeOutputConverterSet converterSet) {
    List<String> titles = new ArrayList<String>();
    List<AttributeConverter<ExchangeUnit>> converters = new ArrayList<AttributeConverter<ExchangeUnit>>();
    for (NodeColumn column : columns) {
      if (column instanceof AttributeColumn) {
        if (titleMode == TitleMode.CAMEL_CASE) {
          column.setName(column.getAttributeName().toString());
        }
        titles.add(column.getName());
        NodeAttributeName attributeName = column.getAttributeName();
        if (attributeName instanceof ExchangeIn) {
          processAttribute(converters,
              converterSet.getExchangeInputDefaultConverter(),
              (ExchangeIn) attributeName);
        } else if (attributeName instanceof ExchangeOut) {
          processAttribute(converters,
              converterSet.getExchangeOutputDefaultConverter(),
              (ExchangeOut) attributeName);
        } else if (attributeName instanceof NodeIn) {
          processAttribute(converters, converterSet.getNodeInputConverters(),
              (NodeIn) attributeName);
        } else if (attributeName instanceof NodeOut) {
          processAttribute(converters, converterSet.getNodeOutputConverters(),
              (NodeOut) attributeName);
        } else {
          throw new UnsupportedOperationException("attribute "
              + attributeName.getDefaultName() + " is of unsupported Type "
              + AttributeName.class.getName());
        }
      } else if (column instanceof PersonColumn) {
        PersonColumn personColumn = (PersonColumn) column;
        if (personColumn.isDonor()) {

          titles.add(personColumn.getName());
          AttributeConverter<? super Donor> converter;
          if (personColumn.getAttributeName() instanceof PersonIn) {
            converter = converterSet.getPersonInputAttributeDefaultConverters()
                .get((PersonIn) personColumn.getAttributeName());
          } else {
            throw new UnsupportedOperationException();
          }
          Attribute<ExchangeUnit, Donor> donor;
          if (personColumn.getDonorOption() == DonorOptions.matchedDonorOnly) {
            if (titleMode == TitleMode.CAMEL_CASE) {
              column.setName("matchedDonor-"
                  + column.getAttributeName().toString());
            }
            donor = converterSet.getExchangeOutputDefaultConverter()
                .getExchangeOutAttributes().getMatchedDonor();
          } else if (personColumn.getDonorOption() == DonorOptions.matchedDonorOrFirst) {
            if (titleMode == TitleMode.CAMEL_CASE) {
              column.setName("matchedOrFirstDonor-"
                  + column.getAttributeName().toString());
            }
            donor = converterSet.getExchangeOutputDefaultConverter()
                .getExchangeOutAttributes().getMatchedOrFirstDonor();
          } else if (personColumn.getDonorOption() == DonorOptions.donorsInOrder) {
            if (titleMode == TitleMode.CAMEL_CASE) {
              column.setName("donor" + personColumn.getDonorIndex() + "-"
                  + column.getAttributeName().toString());
            }
            donor = converterSet.getExchangeInputDefaultConverter()
                .getInputAttributes().getIthDonor(personColumn.getDonorIndex());
          } else {
            throw new UnsupportedOperationException();
          }
          converters.add(ExchangeOutputAttributeDefaultConverters
              .makeCompositeDonorNodeAttribute(converter, donor));
        } else {
          if (titleMode == TitleMode.CAMEL_CASE) {
            column.setName("receiver-" + column.getAttributeName().toString());
          }
          titles.add(personColumn.getName());
          AttributeConverter<? super Receiver> converter;
          if (personColumn.getAttributeName() instanceof PersonIn) {
            converter = converterSet.getPersonInputAttributeDefaultConverters()
                .get((PersonIn) personColumn.getAttributeName());
          } else if (personColumn.getAttributeName() instanceof ReceiverIn) {
            converter = converterSet
                .getReceiverInputAttributeDefaultConverters().get(
                    (ReceiverIn) personColumn.getAttributeName());
          } else {
            throw new UnsupportedOperationException();
          }
          converters.add(ExchangeOutputAttributeDefaultConverters
              .receiverToUnit(converter));
        }
      } else {
        throw new UnsupportedOperationException(
            "node column of unrecognized type: " + column.getClass().getName());
      }
    }
    return new Report<ExchangeUnit>(titleMode == TitleMode.NO_TITLES ? null
        : titles, converters);
  }

  public static enum TitleMode {
    SPACES, CAMEL_CASE, NO_TITLES;
  }

  public static Report<ExchangeUnit> makeOutputReport(
      Iterable<? extends NodeAttributeName> exchangeUnitAttributes,
      Iterable<? extends PersonAttributeName> receiverAttributes,
      Iterable<? extends PersonAttributeName> donorAttributes,
      TitleMode titleMode, ExchangeOutputConverterSet converterSet,
      DonorOptions donorOptions, int numDonors) {
    List<NodeColumn> nodeColumns = new ArrayList<NodeColumn>();
    for (NodeAttributeName attributeName : exchangeUnitAttributes) {
      if (attributeName instanceof ExchangeIn) {
        nodeColumns.add(new AttributeColumn((ExchangeIn) attributeName));
      } else if (attributeName instanceof ExchangeOut) {
        nodeColumns.add(new AttributeColumn((ExchangeOut) attributeName));
      } else if (attributeName instanceof NodeIn) {
        nodeColumns.add(new AttributeColumn((NodeIn) attributeName));
      } else if (attributeName instanceof NodeOut) {
        nodeColumns.add(new AttributeColumn((NodeOut) attributeName));
      } else {
        throw new UnsupportedOperationException();
      }
    }
    for (PersonAttributeName receiverName : receiverAttributes) {
      if (receiverName instanceof PersonIn) {
        nodeColumns.add(PersonColumn.receiverColumn((PersonIn) receiverName));
      } else if (receiverName instanceof ReceiverIn) {
        nodeColumns.add(PersonColumn.receiverColumn((ReceiverIn) receiverName));
      } else {
        throw new UnsupportedOperationException();
      }
    }
    for (PersonAttributeName donorName : donorAttributes) {
      if (donorOptions == DonorOptions.donorsInOrder) {
        if (numDonors < 0) {
          throw new RuntimeException();
        }
        for (int i = 0; i < numDonors; i++) {
          if (donorName instanceof PersonIn) {
            nodeColumns.add(PersonColumn.donorColumn((PersonIn) donorName,
                donorOptions, i));
          } else {
            throw new UnsupportedOperationException();
          }
        }
      } else if (donorOptions == DonorOptions.matchedDonorOnly
          || donorOptions == DonorOptions.matchedDonorOrFirst) {
        if (donorName instanceof PersonIn) {
          nodeColumns.add(PersonColumn.donorColumn((PersonIn) donorName,
              donorOptions, 0));
        } else {
          throw new UnsupportedOperationException();
        }
      } else {
        throw new UnsupportedOperationException();
      }

    }
    return Reports.makeOutputReport(nodeColumns, titleMode, converterSet);
  }

  public static class ExchangeOutputConverterSet {

    private NodeInputAttributeDefaultConverters<ExchangeUnit, DonorEdge, ReadableInstant> nodeInputConverters;
    private NodeOutputAttributeDefaultConverters<ExchangeUnit, DonorEdge, ReadableInstant, Interval> nodeOutputConverters;
    private ExchangeInputAttributeDefaultConverters exchangeInputDefaultConverter;
    private ExchangeOutputAttributeDefaultConverters exchangeOutputDefaultConverter;
    private PersonInputAttributeDefaultConverters personInputAttributeDefaultConverters;
    private ReceiverInputAttributeDefaultConverters receiverInputAttributeDefaultConverters;

    public ExchangeOutputConverterSet(
        ExchangeUnitOutputAttributeSet attributeSet) {

      nodeInputConverters = new NodeInputAttributeDefaultConverters<ExchangeUnit, DonorEdge, ReadableInstant>(
          attributeSet.getNodeInputAttributes(),
          CsvFormatUtil.mmddyyyyFormatTimeInstant);
      nodeOutputConverters = new NodeOutputAttributeDefaultConverters<ExchangeUnit, DonorEdge, ReadableInstant, Interval>(
          attributeSet.getNodeOutputAttributes(),
          CsvFormatUtil.mmddyyyyFormatTimeInstant, CsvFormatUtil.numDays);
      exchangeInputDefaultConverter = new ExchangeInputAttributeDefaultConverters(
          attributeSet.getExchangeInputAttributes());
      exchangeOutputDefaultConverter = new ExchangeOutputAttributeDefaultConverters(
          attributeSet.getExchangeOutputAttributes());
      personInputAttributeDefaultConverters = new PersonInputAttributeDefaultConverters(
          attributeSet.getPersonInputAttributes());
      receiverInputAttributeDefaultConverters = new ReceiverInputAttributeDefaultConverters(
          attributeSet.getReceiverInputAttributes());
    }

    public NodeInputAttributeDefaultConverters<ExchangeUnit, DonorEdge, ReadableInstant> getNodeInputConverters() {
      return nodeInputConverters;
    }

    public NodeOutputAttributeDefaultConverters<ExchangeUnit, DonorEdge, ReadableInstant, Interval> getNodeOutputConverters() {
      return nodeOutputConverters;
    }

    public ExchangeInputAttributeDefaultConverters getExchangeInputDefaultConverter() {
      return exchangeInputDefaultConverter;
    }

    public ExchangeOutputAttributeDefaultConverters getExchangeOutputDefaultConverter() {
      return exchangeOutputDefaultConverter;
    }

    public PersonInputAttributeDefaultConverters getPersonInputAttributeDefaultConverters() {
      return personInputAttributeDefaultConverters;
    }

    public ReceiverInputAttributeDefaultConverters getReceiverInputAttributeDefaultConverters() {
      return receiverInputAttributeDefaultConverters;
    }

  }

  public static class ExchangeInputConverterSet {
    private NodeInputAttributeDefaultConverters<ExchangeUnit, DonorEdge, ReadableInstant> nodeInputConverters;
    private ExchangeInputAttributeDefaultConverters exchangeInputDefaultConverter;
    private PersonInputAttributeDefaultConverters personInputAttributeDefaultConverters;
    private ReceiverInputAttributeDefaultConverters receiverInputAttributeDefaultConverters;

    public ExchangeInputConverterSet(ExchangeUnitInputAttributeSet attributeSet) {
      nodeInputConverters = new NodeInputAttributeDefaultConverters<ExchangeUnit, DonorEdge, ReadableInstant>(
          attributeSet.getNodeInputAttributes(),
          CsvFormatUtil.mmddyyyyFormatTimeInstant);
      exchangeInputDefaultConverter = new ExchangeInputAttributeDefaultConverters(
          attributeSet.getExchangeInputAttributes());
      personInputAttributeDefaultConverters = new PersonInputAttributeDefaultConverters(
          attributeSet.getPersonInputAttributes());
      receiverInputAttributeDefaultConverters = new ReceiverInputAttributeDefaultConverters(
          attributeSet.getReceiverInputAttributes());
    }

    public NodeInputAttributeDefaultConverters<ExchangeUnit, DonorEdge, ReadableInstant> getNodeInputConverters() {
      return nodeInputConverters;
    }

    public ExchangeInputAttributeDefaultConverters getExchangeInputDefaultConverter() {
      return exchangeInputDefaultConverter;
    }

    public PersonInputAttributeDefaultConverters getPersonInputAttributeDefaultConverters() {
      return personInputAttributeDefaultConverters;
    }

    public ReceiverInputAttributeDefaultConverters getReceiverInputAttributeDefaultConverters() {
      return receiverInputAttributeDefaultConverters;
    }
  }

  // TODO(rander): this whole class is just kind of a hack so
  // ExchangeUnitOutputAttributeSet has something to extend. It really contains
  // no new information from NodeOutputAttributes<V, E, T, D>. Maybe there is a
  // way to get rid of this class.
  public static class NodeOutputAttributeSet<V, E, T extends Comparable<T>, D> {
    protected NodeInputAttributes<V, E, T> nodeInputAttributes;
    protected NodeOutputAttributes<V, E, T, D> nodeOutputAttributes;

    public NodeOutputAttributeSet(
        MultiPeriodCyclePacking<V, E, T> cyclePacking,
        TimeDifferenceCalc<T, D> timeDifferenceCalc) {
      this(cyclePacking.getInputs(), cyclePacking.getDynamicMatching(),
          timeDifferenceCalc);
    }

    public NodeOutputAttributeSet(
        MultiPeriodCyclePackingInputs<V, E, T> cyclePackingInputs,
        DynamicMatching<V, E, T> dynamicMatching,
        TimeDifferenceCalc<T, D> timeDifferenceCalc) {
      this.nodeInputAttributes = new NodeInputAttributes<V, E, T>(
          cyclePackingInputs);
      this.nodeOutputAttributes = new NodeOutputAttributes<V, E, T, D>(
          cyclePackingInputs, dynamicMatching, timeDifferenceCalc,
          this.nodeInputAttributes);
    }

    public NodeInputAttributes<V, E, T> getNodeInputAttributes() {
      return nodeInputAttributes;
    }

    public NodeOutputAttributes<V, E, T, D> getNodeOutputAttributes() {
      return nodeOutputAttributes;
    }

    public NodeInputAttributeSet<V, E, T> deriveInputAttributeSet() {
      return new NodeInputAttributeSet<V, E, T>(this.nodeInputAttributes);

    }
  }

  public static class UnosOutputAttributeSet extends
      NodeOutputAttributeSet<UnosExchangeUnit, UnosDonorEdge, Double, Double> {

    private UnosHistoricData unosHistoricData;
    private MultiPeriodCyclePackingInputs<UnosExchangeUnit, UnosDonorEdge, Double> cyclePacking;

    public UnosOutputAttributeSet(
        MultiPeriodCyclePackingInputs<UnosExchangeUnit, UnosDonorEdge, Double> cyclePacking,
        DynamicMatching<UnosExchangeUnit, UnosDonorEdge, Double> dynamicMatching,
        UnosHistoricData unosHistoricData) {
      super(cyclePacking, dynamicMatching,
          DoubleTimeDifferenceCalculator.instance);
      this.unosHistoricData = unosHistoricData;
      this.cyclePacking = cyclePacking;
    }

    @Override
    public UnosNodeAttributeSet deriveInputAttributeSet() {
      return new UnosNodeAttributeSet(cyclePacking, unosHistoricData);
    }

  }

  public static class ExchangeUnitOutputAttributeSet
      extends
      NodeOutputAttributeSet<ExchangeUnit, DonorEdge, ReadableInstant, Interval> {

    private ExchangeInputAttributes exchangeInputAttributes;
    private ExchangeOutputAttributes exchangeOutputAttributes;
    private PersonInputAttributes personInputAttributes;
    // private PersonOutputAttributes personOutputAttributes;
    private ReceiverInputAttributes receiverInputAttributes;

    // private ReceiverOutputAttributes receiverOutputAttributes;

    public ExchangeUnitOutputAttributeSet(
        MultiPeriodCyclePacking<ExchangeUnit, DonorEdge, ReadableInstant> cyclePacking) {
      super(cyclePacking, JodaTimeDifference.instance);
      MultiPeriodCyclePackingInputs<ExchangeUnit, DonorEdge, ReadableInstant> inputs = cyclePacking
          .getInputs();

      this.exchangeInputAttributes = new ExchangeInputAttributes(inputs);
      this.exchangeOutputAttributes = new ExchangeOutputAttributes(cyclePacking);
      this.personInputAttributes = new PersonInputAttributes(inputs);
      this.receiverInputAttributes = new ReceiverInputAttributes(
          (ExchangeUnitAuxiliaryInputStatistics) inputs
              .getAuxiliaryInputStatistics());
    }

    public ExchangeInputAttributes getExchangeInputAttributes() {
      return exchangeInputAttributes;
    }

    public ExchangeOutputAttributes getExchangeOutputAttributes() {
      return exchangeOutputAttributes;
    }

    public PersonInputAttributes getPersonInputAttributes() {
      return personInputAttributes;
    }

    public ReceiverInputAttributes getReceiverInputAttributes() {
      return receiverInputAttributes;
    }

    @Override
    public ExchangeUnitInputAttributeSet deriveInputAttributeSet() {
      return new ExchangeUnitInputAttributeSet(nodeInputAttributes,
          exchangeInputAttributes, personInputAttributes,
          receiverInputAttributes);
    }
  }

  // TODO(rander) this class is a hack so ExchangeUnitInputAttributeSet has
  // something to extend, it has no context beyond NodeInputAttributes, it
  // should be eliminated.
  public static class NodeInputAttributeSet<V, E, T extends Comparable<T>> {
    protected NodeInputAttributes<V, E, T> nodeInputAttributes;
    protected MultiPeriodCyclePackingInputs<V, E, T> inputs;

    public NodeInputAttributeSet(
        NodeInputAttributes<V, E, T> nodeInputAttributes) {
      this.inputs = nodeInputAttributes.getProblemInput();
      this.nodeInputAttributes = nodeInputAttributes;
    }

    public NodeInputAttributeSet(MultiPeriodCyclePackingInputs<V, E, T> inputs) {
      this.inputs = inputs;
      this.nodeInputAttributes = new NodeInputAttributes<V, E, T>(inputs);
    }

    public MultiPeriodCyclePackingInputs<V, E, T> getInputs() {
      return inputs;
    }

    public NodeInputAttributes<V, E, T> getNodeInputAttributes() {
      return nodeInputAttributes;
    }
  }

  public static class UnosNodeAttributeSet extends
      NodeInputAttributeSet<UnosExchangeUnit, UnosDonorEdge, Double> {
    public UnosNodeAttributeSet(
        MultiPeriodCyclePackingInputs<UnosExchangeUnit, UnosDonorEdge, Double> inputs,
        UnosHistoricData unosHistoricData) {
      super(inputs);
      this.unosDonorInputAttributes = new UnosDonorInputAttributes(
          unosHistoricData);
      this.unosPatientInputAttributes = new UnosPatientInputAttributes(
          unosHistoricData);
      this.unosNodeInputAttributes = new UnosNodeInputAttributes();
    }

    public UnosDonorInputAttributes getUnosDonorInputAttributes() {
      return unosDonorInputAttributes;
    }

    public UnosPatientInputAttributes getUnosPatientInputAttributes() {
      return unosPatientInputAttributes;
    }

    public UnosNodeInputAttributes getUnosNodeInputAttributes() {
      return unosNodeInputAttributes;
    }

    private UnosDonorInputAttributes unosDonorInputAttributes;
    private UnosPatientInputAttributes unosPatientInputAttributes;
    private UnosNodeInputAttributes unosNodeInputAttributes;

  }

  public static class ExchangeUnitInputAttributeSet extends
      NodeInputAttributeSet<ExchangeUnit, DonorEdge, ReadableInstant> {

    private ExchangeInputAttributes exchangeInputAttributes;
    private PersonInputAttributes personInputAttributes;
    private ReceiverInputAttributes receiverInputAttributes;

    ExchangeUnitInputAttributeSet(
        NodeInputAttributes<ExchangeUnit, DonorEdge, ReadableInstant> nodeInputAttributes,
        ExchangeInputAttributes exchangeInputAttributes,
        PersonInputAttributes personInputAttributes,
        ReceiverInputAttributes receiverInputAttributes) {
      super(nodeInputAttributes);

      this.exchangeInputAttributes = exchangeInputAttributes;
      this.personInputAttributes = personInputAttributes;
      this.receiverInputAttributes = receiverInputAttributes;
    }

    public ExchangeUnitInputAttributeSet(
        MultiPeriodCyclePackingInputs<ExchangeUnit, DonorEdge, ReadableInstant> inputs) {
      super(inputs);
      this.exchangeInputAttributes = new ExchangeInputAttributes(inputs);
      this.personInputAttributes = new PersonInputAttributes(inputs);
      this.receiverInputAttributes = new ReceiverInputAttributes(
          (ExchangeUnitAuxiliaryInputStatistics) inputs
              .getAuxiliaryInputStatistics());
    }

    public ExchangeInputAttributes getExchangeInputAttributes() {
      return exchangeInputAttributes;
    }

    public PersonInputAttributes getPersonInputAttributes() {
      return personInputAttributes;
    }

    public ReceiverInputAttributes getReceiverInputAttributes() {
      return receiverInputAttributes;
    }

  }

}


text:
/*
  Write a program that reads a file and displays a histogram to show the
  occurrences of each letter in the file. The file name is entered from a text
  field. Pressing the Enter key on the text field causes the program to start
  to read and process the file and displays the histogram. The histogram is
  displayed in the center of the window. Define a class named Histogram that
  extends Pane. The class contains the property counts that is an array of 26
  elements. counts[0] stores the number of A, counts[1] the number of B, and so
  on. The class also contains a setter method for setting a new counts and
  displaying the histogram for the new counts.
*/

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.BorderPane;
import javafx.geometry.Insets;
import java.io.File;
import java.net.URI;
import java.util.Scanner;

public class E16_11 extends Application {
  static int[] counts = new int[26];

  @Override
  public void start(Stage primaryStage) {
    Histogram hist = new Histogram();
    Label lbFilename = new Label("Filename");
    TextField tfFilename = new TextField();
    Button btView = new Button("View");

    btView.setOnAction(e -> {
      counts = new int[26];
      try {
        URI uri = new URI(tfFilename.getText());
        File file;
        if (uri.isAbsolute()) {
          file = new File(uri);
        } else {
          file = new File(uri.toString());
        }

        try (
          Scanner input = new Scanner(file);
        ) {
          StringBuilder sb = new StringBuilder();
          while (input.hasNext()) {
            sb.append(input.nextLine().toLowerCase() + "\n");
          }
          countLetters(sb.toString());
          hist.setCounts(counts);
        } catch (Exception ex) {
          System.out.println(ex);
        }
      } catch (Exception ex) {
        System.out.println(ex);
      }
    });

    HBox controlBox = new HBox(10);
    controlBox.getChildren().addAll(lbFilename, tfFilename, btView);

    BorderPane pane = new BorderPane();
    pane.setCenter(hist);
    pane.setBottom(controlBox);
    pane.setMargin(hist, new Insets(20));

    Scene scene = new Scene(pane);
    primaryStage.setTitle("E16_11");
    primaryStage.setScene(scene);
    primaryStage.setResizable(false);
    primaryStage.show();
  }

  public static void countLetters(String s) {
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (Character.isLetter(c)) {
        counts[(int)c - 97]++;
      }
    }
  }

  public static void main(String[] args) {
    launch(args);
  }
}

redpajama_set_name: RedPajamaGithub


text:
var db = require('../lib').getClient();

var instrument = {
  'riak.request.start': function(event) {
    console.log('[riak-js] ' + event.method.toUpperCase() + ' ' + event.path);
  }
}

db.registerListener(instrument);

db.get('airlines', 'KLM')
db.save('airlines', 'Lufthansa', {country: 'DE'})


text:
from django.utils.translation import ugettext_lazy as _

from horizon import tables

class CreateStorage(tables.LinkAction):
    name = "create"
    verbose_name = _("Add Local Storage")
    url = "horizon:admin:storage:storage:create"
    classes = ("ajax-modal",)
    icon = "plus"

class ClearLocalStorage(tables.LinkAction):
    name = 'clear'
    verbose_name = _("Clear Local Storage")
    url = "horizon:admin:storage:storage:clearstorage"
    classes = ("ajax-modal",)

class StorageTable(tables.DataTable):
    STATUS_CHOICES = (
        ("active", True),
        ("saving", None),
        ("queued", None),
        ("pending_delete", None),
        ("killed", False),
        ("deleted", False),
    )
    name = tables.Column("storage_name",
                         verbose_name=_("Host Name"))

    storage_type = tables.Column("storage_type",
                         verbose_name=_("Storage Type"))

    status = tables.Column("accelerate_status",
                           classes=["storage_css"],
                           verbose_name=_("Boot cache acceleration"))

    path = tables.Column("mount_path",
                         verbose_name=_("Mount Path"))

    accelerate = tables.Column("accelerate_disk",
                         verbose_name=_("SSD Accelerate Disk"))

    memor_chache = tables.Column("memory_cache",
                         verbose_name=_("Memory Cache"))

    data_disk = tables.Column("data_disk",
                         verbose_name=_("Data Disk"))

    class Meta:
        name = "storage"
        verbose_name = _("Storage")
        table_actions = (CreateStorage, ClearLocalStorage )


text:
//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.

#ifndef Patternist_AccelIterators_H
#define Patternist_AccelIterators_H

#include "qacceltree_p.h"
#include "qitem_p.h"

QT_BEGIN_HEADER

QT_BEGIN_NAMESPACE

namespace QPatternist
{
    /**
     * @short Abstract base class for Iterators for the AccelTree, that
     * contains common functions and members.
     *
     * @author Frans Englich<frans.englich@nokia.com>
     */
    class AccelIterator : public QXmlNodeModelIndex::Iterator
    {
    public:
        virtual xsInteger position() const;
        virtual QXmlNodeModelIndex current() const;

    protected:
        inline AccelIterator(const AccelTree *const doc,
                             const AccelTree::PreNumber pre,
                             const AccelTree::PreNumber currentPre) : m_document(doc)
                                                                    , m_preNumber(pre)
                                                                    , m_currentPre(currentPre)
                                                                    , m_position(0)

        {
            Q_ASSERT(m_document);
            Q_ASSERT(m_preNumber >= 0);
        }

        inline QXmlNodeModelIndex closedExit()
        {
            m_position = -1;
            m_current.reset();
            return QXmlNodeModelIndex();
        }

        /**
         * We do not own it.
         */
        const AccelTree *const      m_document;

        /**
         * The pre number of the node that should be navigated from.
         */
        const AccelTree::PreNumber  m_preNumber;
        AccelTree::PreNumber        m_currentPre;
        xsInteger                   m_position;
        QXmlNodeModelIndex          m_current;
    };

    /**
     * @short Iterates along the @c ancestor or @c ancestor-or-self axis in an AccelTree.
     *
     * @author Frans Englich<frans.englich@nokia.com>
     */
    template<const bool IncludeSelf>
    class AncestorIterator : public AccelIterator
    {
    public:
        /**
         * @p pre is the node from which iteration starts
         * from. In the @c ancestor axis it is excluded,
         * while in @c ancestor-or-self it is included. @p pre
         * must have at least one ancestor.
         */
        inline AncestorIterator(const AccelTree *const doc,
                                const AccelTree::PreNumber pre) : AccelIterator(doc, pre, IncludeSelf ? pre : doc->basicData.at(pre).parent())
        {
            Q_ASSERT(IncludeSelf || m_document->hasParent(pre));
        }

        virtual QXmlNodeModelIndex next()
        {
            if(m_currentPre == -1)
                return closedExit();
            else
            {
                ++m_position;
                m_current = m_document->createIndex(m_currentPre);
                m_currentPre = m_document->basicData.at(m_currentPre).parent();

                return m_current;
            }
        }

        virtual QXmlNodeModelIndex::Iterator::Ptr copy() const
        {
            return QXmlNodeModelIndex::Iterator::Ptr(new AncestorIterator<IncludeSelf>(m_document, m_preNumber));
        }
    };

    /**
     * @short Iterates along the @c child axis in an AccelTree.
     *
     * @author Frans Englich<frans.englich@nokia.com>
     */
    class ChildIterator : public AccelIterator
    {
    public:
        /**
         * @p pre must have at least one child.
         */
        inline ChildIterator(const AccelTree *const doc,
                             const AccelTree::PreNumber pre) : AccelIterator(doc, pre, pre + 1),
                                                               m_depth(m_document->depth(m_currentPre))
        {
            Q_ASSERT(m_document->hasChildren(pre));

            /* Skip the attributes, that are children in the pre/post plane, of
             * the node we're applying the child axis to. */
            while(m_document->kind(m_currentPre) == QXmlNodeModelIndex::Attribute)
            {
                ++m_currentPre;
                /* We check the depth here because we would otherwise include
                 * following siblings. */
                if(m_currentPre > m_document->maximumPreNumber() || m_document->depth(m_currentPre) != m_depth)
                {
                    m_currentPre = -1;
                    break;
                }
            }
        }

        virtual QXmlNodeModelIndex next();
        virtual QXmlNodeModelIndex::Iterator::Ptr copy() const;

    private:
        const AccelTree::Depth m_depth;
    };

    /**
     * @short Iterates along the sibling axes in an AccelTree.
     *
     * @author Frans Englich<frans.englich@nokia.com>
     */
    template<const bool IsFollowing>
    class SiblingIterator : public AccelIterator
    {
    public:
        inline SiblingIterator(const AccelTree *const doc,
                               const AccelTree::PreNumber pre) : AccelIterator(doc, pre, pre + (IsFollowing ? 0 : -1)),
                                                                 m_depth(doc->depth(pre))
        {
            Q_ASSERT_X(IsFollowing || pre != 0, "",
                       "When being preceding-sibling, the context node cannot be the first node in the document.");
            Q_ASSERT_X(!IsFollowing || pre != m_document->maximumPreNumber(), "",
                       "When being following-sibling, the context node cannot be the last node in the document.");
        }

        virtual QXmlNodeModelIndex next()
        {
            if(m_currentPre == -1)
                return QXmlNodeModelIndex();

            if(IsFollowing)
            {
                /* Skip the descendants, and jump to the next node. */
                m_currentPre += m_document->size(m_currentPre) + 1;

                if(m_currentPre > m_document->maximumPreNumber() || m_document->depth(m_currentPre) != m_depth)
                    return closedExit();
                else
                {
                    ++m_position;
                    m_current = m_document->createIndex(m_currentPre);
                    return m_current;
                }
            }
            else
            {
                while(m_document->depth(m_currentPre) > m_depth)
                    --m_currentPre;

                while(m_document->kind(m_currentPre) == QXmlNodeModelIndex::Attribute)
                    --m_currentPre;

                if(m_document->depth(m_currentPre) == m_depth &&
                   m_document->kind(m_currentPre) != QXmlNodeModelIndex::Attribute)
                {
                    m_current = m_document->createIndex(m_currentPre);
                    ++m_position;
                    --m_currentPre;
                    return m_current;
                }
                else
                {
                    m_currentPre = -1;
                    return closedExit();
                }
            }
        }

        virtual QXmlNodeModelIndex::Iterator::Ptr copy() const
        {
            return QXmlNodeModelIndex::Iterator::Ptr(new SiblingIterator<IsFollowing>(m_document, m_preNumber));
        }

    private:
        const AccelTree::Depth m_depth;
    };

    /**
     * @short Implements axis @c descendant and @c descendant-or-self for the
     * AccelTree.
     *
     * @author Frans Englich <frans.englich@nokia.com>
     */
    template<const bool IncludeSelf>
    class DescendantIterator : public AccelIterator
    {
    public:
        /**
         * @p pre must have at least one child.
         */
        inline DescendantIterator(const AccelTree *const doc,
                                  const AccelTree::PreNumber pre) : AccelIterator(doc, pre, pre + (IncludeSelf ? 0 : 1)),
                                                                    m_postNumber(doc->postNumber(pre))
        {
            Q_ASSERT(IncludeSelf || m_document->hasChildren(pre));

            /* Make sure that m_currentPre is the first node part of this axis.
             * Since we're not including ourself, advance to the node after our
             * attributes, if any. */
            if(!IncludeSelf)
            {
                while(m_document->kind(m_currentPre) == QXmlNodeModelIndex::Attribute)
                {
                    ++m_currentPre;
                    /* We check the depth here because we would otherwise include
                     * following siblings. */
                    if(m_currentPre > m_document->maximumPreNumber() || m_document->postNumber(m_currentPre) > m_postNumber)
                    {
                        m_currentPre = -1;
                        break;
                    }
                }
            }
        }

        virtual QXmlNodeModelIndex next()
        {
            if(m_currentPre == -1)
                return closedExit();

            ++m_position;
            m_current = m_document->createIndex(m_currentPre);

            ++m_currentPre;

            if(m_currentPre > m_document->maximumPreNumber())
            {
                m_currentPre = -1;
                return m_current;
            }

            if(m_document->postNumber(m_currentPre) < m_postNumber)
            {
                while(m_document->kind(m_currentPre) == QXmlNodeModelIndex::Attribute)
                {
                    ++m_currentPre;
                    if(m_currentPre > m_document->maximumPreNumber())
                    {
                        m_currentPre = -1;
                        break;
                    }
                }
            }
            else
                m_currentPre = -1;

            return m_current;
        }

        virtual QXmlNodeModelIndex::Iterator::Ptr copy() const
        {
            return QXmlNodeModelIndex::Iterator::Ptr(new DescendantIterator<IncludeSelf>(m_document, m_preNumber));
        }

    private:
        const AccelTree::PreNumber m_postNumber;
    };

    /**
     * @short Implements axis @c following for the AccelTree.
     *
     * @author Frans Englich <frans.englich@nokia.com>
     */
    class FollowingIterator : public AccelIterator
    {
    public:
        /**
         * @ pre must have at least one child.
         */
        inline FollowingIterator(const AccelTree *const doc,
                                 const AccelTree::PreNumber pre) : AccelIterator(doc, pre, pre)
        {
        }

        virtual QXmlNodeModelIndex next();
        virtual QXmlNodeModelIndex::Iterator::Ptr copy() const;
    };

    /**
     * @short Implements axis @c preceding for the AccelTree.
     *
     * @author Frans Englich <frans.englich@nokia.com>
     */
    class PrecedingIterator : public AccelIterator
    {
    public:
        /**
         * @ pre must have at least one child.
         */
        inline PrecedingIterator(const AccelTree *const doc,
                                 const AccelTree::PreNumber pre) : AccelIterator(doc, pre,
                                                                                pre - 1 /* currentPre */)
                                                                 , m_postNumber(m_document->postNumber(m_preNumber))
        {
        }

        virtual QXmlNodeModelIndex next();
        virtual QXmlNodeModelIndex::Iterator::Ptr copy() const;

    private:
        const AccelTree::PreNumber  m_postNumber;
    };

    /**
     * @short Implements axis @c attribute for the AccelTree.
     *
     * @author Frans Englich <frans.englich@nokia.com>
     */
    class AttributeIterator : public AccelIterator
    {
    public:
        /**
         * @p pre must have at least one child.
         */
        inline AttributeIterator(const AccelTree *const doc, const AccelTree::PreNumber pre) : AccelIterator(doc, pre, pre + 1)
        {
            Q_ASSERT(m_document->hasChildren(pre));
            Q_ASSERT(m_document->kind(m_currentPre) == QXmlNodeModelIndex::Attribute);
        }

        virtual QXmlNodeModelIndex next();
        virtual QXmlNodeModelIndex::Iterator::Ptr copy() const;
    };
}

QT_END_NAMESPACE

QT_END_HEADER

#endif


text:
'use strict';

var gulp = require('gulp');
var size = require('gulp-size');
var config = require('../tasks.config.json');

var gutil = require('gulp-util');
var plumber = require('gulp-plumber');
var include = require("gulp-include");
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('scripts', function () {

    return gulp.src(config.scripts.main)
    .pipe(include())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify().on('error', gutil.log))
    .pipe(sourcemaps.write('../maps'))
    .pipe(gulp.dest(config.scripts.dest))
    .pipe(size({ title: 'SCRIPTS' }));
});

gulp.task('scripts:copy', function () {

    return gulp.src(config.scripts.copy)
    .pipe(gulp.dest(config.scripts.dest + 'vendor'));
});


text:
package io.mewbase.router

import java.util.UUID

import com.typesafe.config.ConfigFactory
import io.mewbase.eventsource.impl.http.SubscriptionRequest
import io.mewbase.eventsource.{EventSink, EventSource}
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.{Channel, ChannelInitializer}
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.codec.http.{HttpObjectAggregator, HttpRequestDecoder, HttpResponseEncoder}
import io.netty.handler.logging.{LogLevel, LoggingHandler}
import org.slf4j.LoggerFactory

import scala.collection.mutable

object HttpEventRouter extends App {

  // key to find port number
  val PORT_CONFIG_PATH = "mewbase.http.router.port"

  // Configure the HttpRequestDecoder to handle 'small' line lengths
  // and headers and "large" payload chunks for large event encodings
  val initialLineLength = 4096
  val maxHeaderSize = 4096
  val maxPayloadFrameSize = 1024 * 1024

  // create an Event Source and Sink according to the local config
  val eventSink = EventSink.instance
  val eventSource = EventSource.instance

  // Remember initial subscription requests and their subsequently associated handlers
  val subscriptionRequests = mutable.Map[UUID, SubscriptionRequest]()
  val subscriptionHandlers  = mutable.Map[Channel, HttpSubscriptionHandler]()

  class LocalChannelInitializer extends ChannelInitializer[SocketChannel] {

    override def initChannel(ch: SocketChannel): Unit = {
      val p = ch.pipeline()
      val decoder = new HttpRequestDecoder(initialLineLength, maxHeaderSize, maxPayloadFrameSize, false)
      p.addLast("decoder", decoder)
      p.addLast("aggregator", new HttpObjectAggregator(65536))
      p.addLast("encoder", new HttpResponseEncoder())
      val evtHandler = new HttpEventRouterHandler(eventSink, eventSource, subscriptionRequests, subscriptionHandlers)
      p.addLast("handler", evtHandler)
    }
  }

  private val logger = LoggerFactory.getLogger(getClass().getName())

  private val PORT = ConfigFactory.load.getInt(PORT_CONFIG_PATH)

  val bossGroup : NioEventLoopGroup = new NioEventLoopGroup(1)
  val workerGroup : NioEventLoopGroup = new NioEventLoopGroup()

  try {
    val b = new ServerBootstrap()

    b.group(bossGroup, workerGroup)
      .channel(classOf[NioServerSocketChannel])
      .handler(new LoggingHandler(LogLevel.INFO))
      .childHandler(new LocalChannelInitializer() )

    // Start the server.
    val f = b.bind(PORT).sync
    logger.info("Http Event Router started")
    // Wait until the server socket is closed.
    f.channel.closeFuture.sync
    logger.info("Http Event Router closed")
  } finally {
    logger.info("Http Event Router shutdown started")
    // Shut down all event loops to terminate all threads.
    bossGroup.shutdownGracefully()
    workerGroup.shutdownGracefully()
    logger.info("Http Event Router shutdown completed")
  }

}


text:
define([
    '../rg-material',
    './md-toolbar.css',
    'angular-material/content/content.js',
    'angular-material/content/content.css',
    'angular-material/toolbar/toolbar.js',
    'angular-material/toolbar/toolbar.css'
], function (rgMaterial, contentJs, contentCss, toolbarJs, toolbarCss) {
    var mdToolbar = angular
        .module('md-toolbar', [
            rgMaterial.name,
            'material.components.content',
            'material.components.toolbar'
        ]);

    return mdToolbar;
});


text:
using System;

namespace Echo.Restriction
{
    public interface IReturnValueProvider
    {
        object GetReturnValue(Type returnType);
    }
}


text:
<?php

declare(strict_types=1);

namespace SciPhp\NumPhp;

use SciPhp\NdArray;
use Webmozart\Assert\Assert;

trait VanderTrait
{
    /**
     * Generate a Vandermonde matrix.
     *
     * @param    \SciPhp\NdArray|array $matrix A 1-dim array.
     * @param    int $num Number of columns for the output.
     * @return \SciPhp\NdArray A Vandermonde matrix
     * @throws \InvalidArgumentException
     * @link http://sciphp.org/numphp.vander Documentation
     * @api
     */
    final public static function vander($matrix, $num = null): NdArray
    {
        static::transform($matrix, true);

        $num = is_null($num)
            ? count($matrix->data)
            : $num;

        Assert::integer($num);
        Assert::greaterThan($num, 0);
        Assert::eq($matrix->ndim, 1, __METHOD__ . '() only accepts vectors.');

        return static::ar(
            array_map(
                self::itemVander($num),
                static::ones(count($matrix->data), $num)->data,
                $matrix->data
            )
        );
    }

    /**
     * Apply decreasing power on each row values
     *
     * @param    int $num Number of wanted columns
     */
    final protected static function itemVander(int $num): callable
    {
        return static function ($row, $value) use ($num): array {
            return array_map(
                static function($key) use ($value, $num) {
                    return pow($value, $num - $key - 1);
                },
                array_keys($row)
            );
        };
    }
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W23159_extracted</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans20.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">5(fllmg

    <p class="styleSans17.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">15156

    <p class="styleSans658.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Triangle USA Petroleum State 154-102-25-36-9TFH
Section 25 T154N R102W Williams County, North Dakota
Robert Koppel Wellsite Geologist
NESET N CONSULTING —' SERVICE
6844 Hwy 40 Tioga ND, 58852 701-664-1492

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
package org.ovirt.engine.core.vdsbroker.vdsbroker;

import org.ovirt.engine.core.common.vdscommands.CreateVolumeVDSCommandParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.vdsbroker.storage.StorageDomainHelper;

public class CreateVolumeContainerVDSCommand<P extends CreateVolumeVDSCommandParameters> extends StorageDomainMetadataCommand<P> {

    public CreateVolumeContainerVDSCommand(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeDomainCommand() {
        {
            StorageDomainHelper.checkNumberOfLVsForBlockDomain(getParameters().getStorageDomainId());
            setReturnValue(Guid.Empty);

            log.info("-- executeDomainCommand: calling 'createVolumeContainer'");

            status = getBroker().createVolumeContainer(
                    getParameters().getStorageDomainId().toString(),
                    getParameters().getNewImageGroupId().toString(),
                    (Long.valueOf(getParameters().getImageSizeInBytes())).toString(),
                    getParameters().getVolumeFormat().getValue(),
                    2,
                    getParameters().getNewImageID().toString(),
                    getParameters().getDescription(),
                    getParameters().getSrcImageGroupId() != null ? getParameters().getSrcImageGroupId().toString() : Guid.Empty.toString(),
                    getParameters().getSrcImageId() != null ? getParameters().getSrcImageId().toString() : Guid.Empty.toString());

            proceedProxyReturnValue();

            setReturnValue(getParameters().getNewImageID().toString());
        }
    }
}


text:
package org.apache.drill.exec.rpc;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.CorruptedFrameException;

import java.util.List;

import org.apache.drill.exec.memory.BufferAllocator;

import com.google.protobuf.CodedInputStream;
import org.apache.drill.exec.exception.OutOfMemoryException;

/**
 * Modified version of {@link io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder} that avoids bytebuf copy.
 * See the documentation there.
 */
public class ProtobufLengthDecoder extends ByteToMessageDecoder {
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ProtobufLengthDecoder.class);

  private BufferAllocator allocator;
  private OutOfMemoryHandler outOfMemoryHandler;

  public ProtobufLengthDecoder(BufferAllocator allocator, OutOfMemoryHandler outOfMemoryHandler) {
    super();
    this.allocator = allocator;
    this.outOfMemoryHandler = outOfMemoryHandler;
  }

  @Override
  protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!ctx.channel().isOpen()) {
      if (in.readableBytes() > 0) {
        logger.info("Channel is closed, discarding remaining {} byte(s) in buffer.", in.readableBytes());
      }
      in.skipBytes(in.readableBytes());
      return;
    }

    in.markReaderIndex();
    final byte[] buf = new byte[5];
    for (int i = 0; i < buf.length; i++) {
      if (!in.isReadable()) {
        in.resetReaderIndex();
        return;
      }

      buf[i] = in.readByte();
      if (buf[i] >= 0) {

        int length = CodedInputStream.newInstance(buf, 0, i + 1).readRawVarint32();

        if (length < 0) {
          throw new CorruptedFrameException("negative length: " + length);
        }
        if (length == 0) {
          throw new CorruptedFrameException("Received a message of length 0.");
        }

        if (in.readableBytes() < length) {
          in.resetReaderIndex();
          return;
        } else {
          // need to make buffer copy, otherwise netty will try to refill this buffer if we move the readerIndex forward...
          // TODO: Can we avoid this copy?
          ByteBuf outBuf;
          try {
            outBuf = allocator.buffer(length);
          } catch (OutOfMemoryException e) {
            logger.warn("Failure allocating buffer on incoming stream due to memory limits.  Current Allocation: {}.", allocator.getAllocatedMemory());
            in.resetReaderIndex();
            outOfMemoryHandler.handle();
            return;
          }
          outBuf.writeBytes(in, in.readerIndex(), length);

          in.skipBytes(length);

          if (RpcConstants.EXTRA_DEBUGGING) {
            logger.debug(String.format(
                "ReaderIndex is %d after length header of %d bytes and frame body of length %d bytes.",
                in.readerIndex(), i + 1, length));
          }

          out.add(outBuf);
          return;
        }
      }
    }

    // Couldn't find the byte whose MSB is off.
    throw new CorruptedFrameException("length wider than 32-bit");

  }

  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ctx.fireChannelReadComplete();
  }

}


text:
using UnityEngine;
using System.Collections;

public class AimState : State
{
    private Animation animation;

    private WeaponController weaponController;

    private string startAimAnimation = "";
    private string idleAimAnimation = "";
    private string finishAimAnimation = "";

    private float normalFieldOfView = 0.0f;
    private float zoomedFieldOfView = 0.0f;

    private bool aiming = false;

    public AimState(FiniteStateMachine controller)
	{
        stateID = (int)WeaponController.State.Aiming;

        weaponController = (WeaponController)controller;
        animation = weaponController.currentWeapon.GetComponent<Animation>();

        startAimAnimation = weaponController.currentWeapon.GetStartAim();
        idleAimAnimation = weaponController.currentWeapon.GetIdleAim();
        finishAimAnimation = weaponController.currentWeapon.GetFinishAim();

        normalFieldOfView = weaponController.thisCamera.fieldOfView;
        zoomedFieldOfView = normalFieldOfView * 0.6f;
    }

	public override void Transition()
	{
		if (animation.IsPlaying(finishAimAnimation) && aiming == false)
		{
            weaponController.PerformTransition((int)WeaponController.Transition.AimingReleased);
        }
		else if (Input.GetMouseButton(0))
		{
            if (weaponController.currentWeapon.currentAmmo > 0 && aiming == true && Input.GetMouseButton(1))
			{
                weaponController.PerformTransition((int)WeaponController.Transition.WeaponFired);
            }
			else if (weaponController.currentWeapon.currentAmmo == 0 && weaponController.currentWeapon.totalAmmo > 0)
			{
                weaponController.StartCoroutine(InterruptAiming());
                weaponController.PerformTransition((int)WeaponController.Transition.ReloadWeapon);
			}
		}
		else if (Input.GetKeyDown(KeyCode.R))
		{
            if (weaponController.currentWeapon.currentAmmo < weaponController.currentWeapon.clipMax && weaponController.currentWeapon.totalAmmo > 0)
			{
                weaponController.StartCoroutine(InterruptAiming());
                weaponController.PerformTransition((int)WeaponController.Transition.ReloadWeapon);
            }
		}
	}

	public override void Execute()
	{
		if (Input.GetMouseButton(1) && aiming == false)
        {
            weaponController.StartCoroutine(StartAiming());
        }
        else if (!Input.GetMouseButton(1) && aiming == true)
        {
            weaponController.StartCoroutine(ReleaseAiming());
        }
        else if (Input.GetMouseButton(1) && aiming == true)
        {
            animation.CrossFade(idleAimAnimation);
        }
	}

    private IEnumerator StartAiming()
    {
        animation.CrossFade(startAimAnimation);
        weaponController.StopCoroutine("ReleaseAiming");
        yield return weaponController.StartCoroutine(weaponController.ZoomFOVByAnimation(normalFieldOfView, zoomedFieldOfView, animation[startAimAnimation]));
        aiming = true;
    }

    private IEnumerator ReleaseAiming()
    {
        animation.CrossFade(finishAimAnimation);
        weaponController.StopCoroutine("StartAiming");
        yield return weaponController.StartCoroutine(weaponController.ZoomFOVByAnimation(zoomedFieldOfView, normalFieldOfView, animation[finishAimAnimation]));
        aiming = false;
    }

    private IEnumerator InterruptAiming()
    {
        weaponController.StopCoroutine("StartAiming");
        weaponController.StopCoroutine("ReleaseAiming");
        yield return weaponController.StartCoroutine(weaponController.ResetFieldOfView(zoomedFieldOfView, normalFieldOfView, animation[finishAimAnimation].length));
        aiming = false;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 26(3/4): 222 (1928)

#### Original name
Meliola horrida Ellis & Everh.

### Remarks
null


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Biatorinopsis pallidula Müll. Arg.

### Remarks
null


text:
echo "download caffemodel..."
dir=agent/model
if [ ! -d $dir ]; then
  mkdir $dir
fi
curl -o ${dir}/bvlc_alexnet.caffemodel http://dl.caffe.berkeleyvision.org/bvlc_alexnet.caffemodel

curl -f -L -o ${dir}/ilsvrc_2012_mean.npy https://github.com/BVLC/caffe/raw/master/python/caffe/imagenet/ilsvrc_2012_mean.npy


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

using Hyena;
using Hyena.Json;

namespace Lastfm
{
    public enum RequestType {
        Read,
        SessionRequest, // Needs the signature, but we don't have the session key yet
        AuthenticatedRead,
        Write
    }

    public enum ResponseFormat {
        Json,
        Raw
    }

    public delegate void SendRequestHandler ();

    public class LastfmRequest
    {
        private const string API_ROOT = "http://ws.audioscrobbler.com/2.0/";

        private Dictionary<string, string> parameters = new Dictionary<string, string> ();
        private Stream response_stream;
        private string response_string;

        public LastfmRequest ()
        {}

        public LastfmRequest (string method) : this (method, RequestType.Read, ResponseFormat.Json)
        {}

        public LastfmRequest (string method, RequestType request_type, ResponseFormat response_format)
        {
            this.method = method;
            this.request_type = request_type;
            this.response_format = response_format;
        }

        private string method;

        private RequestType request_type;

        private ResponseFormat response_format;

        public void AddParameter (string param_name, string param_value)
        {
            parameters.Add (param_name, param_value);
        }

        public Stream GetResponseStream ()
        {
            return response_stream;
        }

        public void Send ()
        {
            if (method == null) {
                throw new InvalidOperationException ("The method name should be set");
            }

            if (response_format == ResponseFormat.Json) {
                AddParameter ("format", "json");
            } else if (response_format == ResponseFormat.Raw) {
                AddParameter ("raw", "true");
            }

            if (request_type == RequestType.Write) {
                response_stream = Post (API_ROOT, BuildPostData ());
            } else {
                response_stream = Get (BuildGetUrl ());
            }
        }

        public JsonObject GetResponseObject ()
        {
            if (response_stream == null) {
                return null;
            }

            SetResponseString ();

            Deserializer deserializer = new Deserializer (response_string);
            object obj = deserializer.Deserialize ();
            JsonObject json_obj = obj as Hyena.Json.JsonObject;

            if (json_obj == null) {
                throw new ApplicationException ("Lastfm invalid response : not a JSON object");
            }

            return json_obj;
        }

        public IAsyncResult BeginSend (AsyncCallback callback)
        {
            return BeginSend (callback, null);
        }

        private SendRequestHandler send_handler;
        public IAsyncResult BeginSend (AsyncCallback callback, object context)
        {
            send_handler = new SendRequestHandler (Send);

            return send_handler.BeginInvoke (callback, context);
        }

        public void EndSend (IAsyncResult result)
        {
            send_handler.EndInvoke (result);
        }

        public StationError GetError ()
        {
            StationError error = StationError.None;

            SetResponseString ();

            if (response_string == null) {
                return StationError.Unknown;
            }

            if (response_string.Contains ("<lfm status=\"failed\">")) {
                // XML reply indicates an error
                Match match = Regex.Match (response_string, "<error code=\"(\\d+)\">");
                if (match.Success) {
                    error = (StationError) Int32.Parse (match.Value);
                    Log.WarningFormat ("Lastfm error {0}", error);
                } else {
                    error = StationError.Unknown;
                }
            }
            if (response_format == ResponseFormat.Json && response_string.Contains ("\"error\":")) {
                // JSON reply indicates an error
                Deserializer deserializer = new Deserializer (response_string);
                JsonObject json = deserializer.Deserialize () as JsonObject;
                if (json != null && json.ContainsKey ("error")) {
                    error = (StationError) json["error"];
                    Log.WarningFormat ("Lastfm error {0} : {1}", error, (string)json["message"]);
                }
            }

            return error;
        }

        private string BuildGetUrl ()
        {
            if (request_type == RequestType.AuthenticatedRead) {
                parameters.Add ("sk", LastfmCore.Account.SessionKey);
            }

            StringBuilder url = new StringBuilder (API_ROOT);
            url.AppendFormat ("?method={0}", method);
            url.AppendFormat ("&api_key={0}", LastfmCore.ApiKey);
            foreach (KeyValuePair<string, string> param in parameters) {
                url.AppendFormat ("&{0}={1}", param.Key, Uri.EscapeDataString (param.Value));
            }
            if (request_type == RequestType.AuthenticatedRead || request_type == RequestType.SessionRequest) {
                url.AppendFormat ("&api_sig={0}", GetSignature ());
            }

            return url.ToString ();
        }

        private string BuildPostData ()
        {
            parameters.Add ("sk", LastfmCore.Account.SessionKey);

            StringBuilder data = new StringBuilder ();
            data.AppendFormat ("method={0}", method);
            data.AppendFormat ("&api_key={0}", LastfmCore.ApiKey);

            foreach (KeyValuePair<string, string> param in parameters) {
                data.AppendFormat ("&{0}={1}",
                                   param.Key, param.Value != null ? Uri.EscapeDataString (param.Value) : null);
            }

            data.AppendFormat ("&api_sig={0}", GetSignature ());

            return data.ToString ();
        }

        private string GetSignature ()
        {
            // We need to have trackNumber[0] before track[0], so we use StringComparer.Ordinal
            var sorted_params = new SortedDictionary<string, string> (parameters, StringComparer.Ordinal);

            if (!sorted_params.ContainsKey ("api_key")) {
                sorted_params.Add ("api_key", LastfmCore.ApiKey);
            }
            if (!sorted_params.ContainsKey ("method")) {
                sorted_params.Add ("method", method);
            }
            StringBuilder signature = new StringBuilder ();
            foreach (var parm in sorted_params) {
                if (parm.Key.Equals ("format")) {
                    continue;
                }
                signature.Append (parm.Key);
                signature.Append (parm.Value);
            }
            signature.Append (LastfmCore.ApiSecret);

            return Hyena.CryptoUtil.Md5Encode (signature.ToString (), Encoding.UTF8);
        }

        public override string ToString ()
        {
            StringBuilder sb = new StringBuilder ();

            sb.Append (method);
            foreach (KeyValuePair<string, string> param in parameters) {
                sb.AppendFormat ("\n\t{0}={1}", param.Key, param.Value);
            }
            return sb.ToString ();
        }

        private void SetResponseString ()
        {
            if (response_string == null && response_stream != null) {
                using (StreamReader sr = new StreamReader (response_stream)) {
                    response_string = sr.ReadToEnd ();
                }
            }
        }

#region HTTP helpers

        private Stream Get (string uri)
        {
            return Get (uri, null);
        }

        private Stream Get (string uri, string accept)
        {
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create (uri);
            if (accept != null) {
                request.Accept = accept;
            }
            request.UserAgent = LastfmCore.UserAgent;
            request.Timeout = 10000;
            request.KeepAlive = false;
            request.AllowAutoRedirect = true;

            HttpWebResponse response = null;
            try {
                response = (HttpWebResponse) request.GetResponse ();
            } catch (WebException e) {
                Log.DebugException (e);
                response = (HttpWebResponse)e.Response;
            }
            return response != null ? response.GetResponseStream () : null;
        }

        private Stream Post (string uri, string data)
        {
            // Do not trust docs : it doesn't work if parameters are in the request body
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create (String.Concat (uri, "?", data));
            request.UserAgent = LastfmCore.UserAgent;
            request.Timeout = 10000;
            request.Method = "POST";
            request.KeepAlive = false;
            request.ContentType = "application/x-www-form-urlencoded";

            HttpWebResponse response = null;
            try {
                response = (HttpWebResponse) request.GetResponse ();
            } catch (WebException e) {
                Log.DebugException (e);
                response = (HttpWebResponse)e.Response;
            }
            return response != null ? response.GetResponseStream () : null;
        }

#endregion
    }
}


text:
import numpy as np
import os
import sys
import matplotlib.pyplot as plt
import copy
from mpl_toolkits.mplot3d import Axes3D

if '__file__' in globals(): sys.path.append(os.path.join(os.path.dirname(__file__),"../"))
from crowdsourcing.annotation_types.classification import *

DATASET_DIR = "data/classification/cub_40"
OUTPUT_DIR = "output/classification/cub_40"

ASSIGNMENT_DATA = os.path.join(DATASET_DIR, "class_labels_to_annotations.json")
MAX_ASSIGNMENTS_PER_IMAGE = 5
BATCH_SIZE = 108
ESTIMATE_PRIORS = False
USE_COMPUTER_VISION = True
NUM_RAND_PERMS = 5

IMAGE_DIR = os.path.join(DATASET_DIR, "images")
TMP_DIR = os.path.join(OUTPUT_DIR, "tmp")
HTML_DIR = os.path.join(OUTPUT_DIR, "html")

if not os.path.exists(os.path.dirname(OUTPUT_DIR)): os.mkdir(os.path.dirname(OUTPUT_DIR))
if not os.path.exists(OUTPUT_DIR): os.mkdir(OUTPUT_DIR)
if not os.path.exists(HTML_DIR): os.mkdir(HTML_DIR)
if not os.path.exists(OUTPUT_DIR+"/combined"): os.mkdir(OUTPUT_DIR+"/combined")

if USE_COMPUTER_VISION:
  if not os.path.exists(TMP_DIR): os.mkdir(TMP_DIR)
  if not os.path.exists(IMAGE_DIR): os.mkdir(IMAGE_DIR)

  CAFFE_ROOT = '/home/sbranson/code/other_peoples_code/caffe-master-git/caffe' #'/home/sbranson/caffe'
  MODEL_FILE = CAFFE_ROOT+'/models/bvlc_reference_caffenet/deploy.prototxt'
  PRETRAINED = CAFFE_ROOT+'/models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'
  USE_GPU=True
  caffe_model = FeatureExtractor(MODEL_FILE, PRETRAINED,np.load(CAFFE_ROOT + '/python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1), gpu=USE_GPU)

def generate_plots(plot_data, class_name):
  plots = ["full", "no-cv", "majority-vote", "no-online", "no-online-no-cv", "no-worker-image"]
  num = float(len(dataset.images))
  handles, labels = [], []
  plt.figure(1)
  plt.clf()
  for n in plots:
    h = plt.semilogy(plot_data[n]["x"], plot_data[n]["y"], plot_data[n]["line-style"], lw=3)
    handles.append(h[0])
    labels.append(n)
  plt.xlabel('# Annotations Per Image', fontsize=20)
  plt.ylabel('Annotation Loss', fontsize=20)
  a = plt.gca()
  plt.tick_params(axis='both', which='major', labelsize=16)
  plt.tick_params(axis='both', which='minor', labelsize=16)
  plt.legend(handles, labels, prop={'size':20})
  plt.savefig(os.path.join(OUTPUT_DIR, class_name, 'binary_method_comparison_online.pdf'))
  #plt.show()

  plots = ["no-online", "no-online-no-cv", "no-online-worker-image", "majority-vote"]
  num = float(len(dataset.images))
  handles, labels = [], []
  plt.figure(2)
  plt.clf()
  for n in plots:
    h = plt.semilogy(plot_data[n]["x"], plot_data[n]["y"], plot_data[n]["line-style"], lw=3)
    handles.append(h[0])
    labels.append(n)
  plt.xlabel('# Annotations Per Image', fontsize=20)
  plt.ylabel('Annotation Loss', fontsize=20)
  a = plt.gca()
  plt.tick_params(axis='both', which='major', labelsize=16)
  plt.tick_params(axis='both', which='minor', labelsize=16)
  plt.legend(handles, labels, prop={'size':20})
  plt.savefig(os.path.join(OUTPUT_DIR, class_name, 'binary_method_comparison.pdf'))

  if "risk" in plot_data[n] and len(plot_data[n]["risk"]):
    plt.figure(3)
    plt.clf()
    n = "no-online-no-cv"
    h1=plt.semilogy(plot_data[n]["x"], plot_data[n]["y"], plot_data[n]["line-style"], lw=3)[0]
    #h2=plt.semilogy(plot_data[n]["x"], [f+plot_data[n]["y"][-1] for f in plot_data[n]["risk"]], 'g--', lw=3)[0]
    h2=plt.semilogy(plot_data[n]["x"], plot_data[n]["risk"], 'g--', lw=3)[0]
    plt.xlabel('# Annotations Per Image', fontsize=20)
    plt.ylabel('Annotation Loss', fontsize=20)
    plt.tick_params(axis='both', which='major', labelsize=16)
    plt.tick_params(axis='both', which='minor', labelsize=16)
    plt.legend([h1,h2], ['actual test error','predicted error'], prop={'size':20})
    plt.savefig(os.path.join(OUTPUT_DIR, class_name, 'binary_risk_estimation.pdf'))
    #plt.show()

  n = "full"
  plt.figure(4)
  plt.clf()
  bins = [.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5]
  plt.hist(plot_data[n]["num_anno"], bins, histtype='bar', rwidth=0.8, color='g')
  plt.xlabel('# Annotations Per Image', fontsize=20)
  plt.ylabel('# Images', fontsize=20)
  plt.tick_params(axis='both', which='major', labelsize=16)
  plt.tick_params(axis='both', which='minor', labelsize=16)
  plt.savefig(os.path.join(OUTPUT_DIR, class_name, 'binary_annos_per_image.pdf'))
  #plt.show()

  fig = plt.figure(5)
  plt.clf()
  plt.scatter(np.asarray(plot_data[n]["skills"])[:,0].tolist(), np.asarray(plot_data[n]["skills"])[:,1].tolist())
  plt.savefig(os.path.join(OUTPUT_DIR, class_name, 'binary_worker_skills.pdf'))
  #fig.show()

def average_plots(all_plot_data):
  combined_plot_data = {}
  for c in all_plot_data.items()[0][1]:
    combined_plot_data[c] = copy.deepcopy(plot_data[c])
    for f in ["x","y","risk"]:
      l = np.asarray([len(all_plot_data[cn][c]["x"]) for cn in all_plot_data]).max()
      counts = np.zeros((l))
      combined_plot_data[c][f] = np.zeros((l))
      for cn in all_plot_data:
        if f in all_plot_data[cn][c]:
          counts[:len(all_plot_data[cn][c][f])] += np.ones((len(all_plot_data[cn][c][f])))
          combined_plot_data[c][f][:len(all_plot_data[cn][c][f])] += all_plot_data[cn][c][f]
      combined_plot_data[c][f] = (combined_plot_data[c][f]/counts).tolist()
  return combined_plot_data

all_plot_data, all_ave_plot_data = {}, {}
with open(ASSIGNMENT_DATA,"r") as f:
  json_data = json.load(f)
for class_name in json_data:
  if not os.path.exists(OUTPUT_DIR+"/"+class_name): os.mkdir(OUTPUT_DIR+"/"+class_name)
  if not os.path.exists(HTML_DIR+"/"+class_name): os.mkdir(HTML_DIR+"/"+class_name)

  plot_data_perms = {}
  for k in range(NUM_RAND_PERMS):
    data = [json_data[class_name]["worker_labels"][j] for j in np.random.permutation(len(json_data[class_name]["worker_labels"]))]
    expert_dataset = CrowdDatasetBinaryClassification()
    expert_dataset.parse_dataset_cub(data, expert=True, class_name=class_name)

    full_dataset = CrowdDatasetBinaryClassification(debug=2, learn_worker_params=True, learn_image_params=True)
    full_dataset.parse_dataset_cub(data, max_assignments=MAX_ASSIGNMENTS_PER_IMAGE, class_name=class_name)
    full_dataset.estimate_parameters()

    plot_data = {"full":{"x":[],"y":[],"risk":[], "line-style":"r-o", "use_cv":True, "worker_params":True, "image_params":True, "simple_crowdsourcing":False, "online":True}}
    plot_data["no-cv"] = {"x":[],"y":[],"risk":[], "line-style":"k-v", "use_cv":False, "worker_params":True, "image_params":True, "simple_crowdsourcing":False, "online":True}
    plot_data["no-worker-skill"] = {"x":[],"y":[],"risk":[], "line-style":"g--8", "use_cv":False, "worker_params":False, "image_params":True, "simple_crowdsourcing":False, "online":True}
    plot_data["no-image-difficulty"] = {"x":[],"y":[],"risk":[], "line-style":"k-*", "use_cv":False, "worker_params":True, "image_params":False, "simple_crowdsourcing":False, "online":True}
    plot_data["no-worker-image"] = {"x":[],"y":[],"risk":[], "line-style":"b--h", "use_cv":False, "worker_params":False, "image_params":False, "simple_crowdsourcing":False, "online":True}
    plot_data["no-online"] = {"x":[],"y":[],"risk":[], "line-style":"r:s", "use_cv":True, "worker_params":True, "image_params":True, "simple_crowdsourcing":False, "online":False}
    plot_data["no-online-no-cv"] = {"x":[],"y":[],"risk":[], "line-style":"c:s", "use_cv":False, "worker_params":True, "image_params":True, "simple_crowdsourcing":False, "online":False}

    plot_data["majority-vote"] = {"x":[],"y":[], "line-style":"m-.v", "use_cv":False, "worker_params":False, "image_params":False, "simple_crowdsourcing":True, "online":False}
    plot_data["no-online-worker-image"] = {"x":[],"y":[],"risk":[], "line-style":"y:s", "use_cv":False, "worker_params":False, "image_params":False, "simple_crowdsourcing":False, "online":False}

    for method in plot_data:
      if plot_data[method]["use_cv"] and not USE_COMPUTER_VISION: continue

      i = 0
      dataset = CrowdDatasetBinaryClassification(debug=0, learn_worker_params=plot_data[method]["worker_params"], learn_image_params=plot_data[method]["image_params"], min_risk=0.05)
      #dataset.copy_parameters_from(full_dataset)
      dataset.parse_dataset_cub(data, max_assignments=0, class_name=class_name)

      if plot_data[method]["use_cv"]:
        dataset.computer_vision_handles = caffe_model
        dataset.image_dir = IMAGE_DIR + "/" + class_name
        dataset.tmp_dir = TMP_DIR + "/" + class_name

      while dataset.num_unfinished(max_annos=MAX_ASSIGNMENTS_PER_IMAGE) > 0 and (i < MAX_ASSIGNMENTS_PER_IMAGE or plot_data[method]["online"]):
        dataset.estimate_priors_automatically = dataset.num_annotations() >= 2*len(dataset.images)
        dataset.augment_annotations_if_necessary(full_dataset, BATCH_SIZE if plot_data[method]["online"] else len(dataset.images))
        if plot_data[method]["simple_crowdsourcing"]:
          dataset.crowdsource_simple()
        else:
          dataset.estimate_parameters(avoid_if_finished=True)
          dataset.check_finished_annotations()
          risk = dataset.risk()
          plot_data[method]["risk"].append(risk)
        if not plot_data[method]["online"]:
          for ii in dataset.images:
            dataset.images[ii].finished = False
        err,num = dataset.compute_error(expert_dataset), dataset.num_annotations(),
        plot_data[method]["x"].append(num/float(len(dataset.images)))
        plot_data[method]["y"].append(err)
        i += 1
        print "Class " + class_name + " method " + method + " at iter " + str(i) + " ave error is " + str(err) + " with " +  str(num) + " annos"
        dataset.save_gallery(os.path.join(HTML_DIR, class_name, method+'_'+str(i)+'worker.json'))

      plot_data[method]['num_anno'] = [len(dataset.images[i].z) for i in dataset.images]
      if plot_data[method]["worker_params"]:
        plot_data[method]['skills'] = []
        for w in dataset.workers:
          plot_data[method]['skills'].append(dataset.workers[w].skill)

    plot_data_perms[k] = plot_data

  plot_data_ave = average_plots(plot_data_perms)

  generate_plots(plot_data_ave, class_name)
  all_plot_data[class_name] = plot_data_perms
  all_ave_plot_data[class_name] = plot_data_ave

with open(TMP_DIR + '/all_plot_data.pkl', 'wb') as f:
  pickle.dump(all_plot_data, f)

combined_plot_data = average_plots(all_ave_plot_data)
for c in plot_data:
  combined_plot_data[c] = copy.deepcopy(plot_data[c])
  for f in ["x","y","risk"]:
    l = np.asarray([len(all_ave_plot_data[cn][c]["x"]) for cn in all_ave_plot_data]).max()
    counts = np.zeros((l))
    combined_plot_data[c][f] = np.zeros((l))
    for cn in all_ave_plot_data:
      if f in all_ave_plot_data[cn][c]:
        counts[:len(all_ave_plot_data[cn][c][f])] += np.ones((len(all_ave_plot_data[cn][c][f])))
        combined_plot_data[c][f][:len(all_ave_plot_data[cn][c][f])] += all_ave_plot_data[cn][c][f]
    combined_plot_data[c][f] = (combined_plot_data[c][f]/counts).tolist()

generate_plots(combined_plot_data, "combined")


text:
namespace Google.Cloud.ResourceManager.V3.Snippets
{
    // [START cloudresourcemanager_v3_generated_Projects_SetIamPolicy_async_flattened_resourceNames]
    using Google.Api.Gax;
    using Google.Cloud.Iam.V1;
    using Google.Cloud.ResourceManager.V3;
    using System.Threading.Tasks;

    public sealed partial class GeneratedProjectsClientSnippets
    {
        /// <summary>Snippet for SetIamPolicyAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task SetIamPolicyResourceNamesAsync()
        {
            // Create client
            ProjectsClient projectsClient = await ProjectsClient.CreateAsync();
            // Initialize request argument(s)
            IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
            Policy policy = new Policy();
            // Make the request
            Policy response = await projectsClient.SetIamPolicyAsync(resource, policy);
        }
    }
    // [END cloudresourcemanager_v3_generated_Projects_SetIamPolicy_async_flattened_resourceNames]
}


text:
/**
 * Warning: Generated code! do not change!
 * Generated by: go/EntityDB.ftl
 */
package tables
import (
	"github.com/quintans/goSQL/db"
	"github.com/quintans/taskboard/go/entity"
	. "github.com/quintans/toolkit/ext"
)

var (
	LANE = db.TABLE("LANE")
	LANE_C_ID = LANE.KEY("ID")
	LANE_C_VERSION = LANE.VERSION("VERSION")
	// Audit
	LANE_C_CREATION = LANE.COLUMN("CREATION")
	LANE_C_MODIFICATION = LANE.COLUMN("MODIFICATION")
	LANE_C_USER_CREATION = LANE.COLUMN("USER_CREATION").As("UserCreationId")
	LANE_C_USER_MODIFICATION = LANE.COLUMN("USER_MODIFICATION").As("UserModificationId")
	// Atributos
	LANE_C_NAME = LANE.COLUMN("NAME")
	LANE_C_POSITION = LANE.COLUMN("POSITION")
	LANE_C_BOARD_ID = LANE.COLUMN("BOARD").As("BoardId")
	//FK's
	LANE_A_BOARD = LANE.
				ASSOCIATE(LANE_C_BOARD_ID).TO(BOARD_C_ID).
				As("Board")
	LANE_A_TASKS = LANE.
				ASSOCIATE(LANE_C_ID).TO(TASK_C_LANE_ID).
				As("Tasks")
	LANE_A_NOTIFICATIONS = LANE.
				ASSOCIATE(LANE_C_ID).TO(NOTIFICATION_C_LANE_ID).
				As("Notifications")
	LANE_A_USER_CREATION = LANE.ASSOCIATE(LANE_C_USER_CREATION).TO(USER_C_ID).As("UserCreation")
	LANE_A_USER_MODIFICATION = LANE.ASSOCIATE(LANE_C_USER_MODIFICATION).TO(USER_C_ID).As("UserModification")
)

func init() {
	LANE.PreInsertTrigger = func(ins *db.Insert) {
		ins.Set(LANE_C_VERSION, 1)
		ins.Set(LANE_C_CREATION, NOW())
		uid, ok := ins.GetDb().GetAttribute(entity.ATTR_USERID)
		if ok {
			ins.Set(LANE_C_USER_CREATION, uid.(int64))
		}
	}
	LANE.PreUpdateTrigger = func(upd *db.Update) {
		upd.Set(LANE_C_MODIFICATION, NOW())
		uid, ok := upd.GetDb().GetAttribute(entity.ATTR_USERID)
		if ok {
			upd.Set(LANE_C_USER_MODIFICATION, uid.(int64))
		}
	}
}


text:
{% load i18n static sekizai_tags cms_tags %}{% spaceless %}

{% addtoblock "js" %}{% endaddtoblock %}
{% add_data "ng-requires" "djng.forms" %}

{% if stylesheet_url %}{% addtoblock "css" %}<link href="{{ stylesheet_url }}" rel="stylesheet" type="text/css" />{% endaddtoblock %}{% endif %}

{% if many %}

{% blocktrans %}
		Please embed this plugin into a SegmentationPlugin with condition if not many.
	{% endblocktrans %}

{% else %}
	{% if show_history and data.extra.addenum %}
		{% trans "Previous annotations" %}

		{% for timestamp, annotation in data.extra.addenum %}

{{ annotation }}

		{% endfor %}

	{% endif %}
	{% with instance_css_classes=instance.css_classes instance_inline_styles=instance.inline_styles %}
	<form name="{{ addenum_form.form_name }}" djng-endpoint="{{ request.path_info }}" novalidate>
		{{ addenum_form.as_div }}
		<button ng-click="do(create()).then(showOK()).then(delay(333)).then(reloadPage()).finally(restore())" ng-disabled="isDisabled()"{% if instance_css_classes %} class="{{ instance_css_classes }}"{% endif %}{% if instance_inline_styles %} style="{{ instance_inline_styles }}"{% endif %}>
			{{ icon_left }}{{ button_label }}{{ icon_right }}
		</button>
	</form>
	{% endwith %}
{% endif %}
{% endspaceless %}


text:
function plotsarfields(direc, save)
% PLOTSARFIELDS  Plots SAR velocity fields from a block model run.
%   PLOTSARFIELDS(DIREC) plots the velocity fields contained in DIREC/Sar.pred.
%
%   PLOTSARFIELDS(DIREC, SAVE), where SAVE = 1, saves each figure to a .fig file
%   within DIREC.
%

% Load the SAR fields
b = load([direc filesep 'Sar.pred']);
% Load the model segment file, for plotting
Segment = ReadSegmentTri([direc filesep 'Mod.segment']);

% Set the figure titles
titles = {'Observed', 'Modeled', 'Residual', 'Elastic', 'Block', 'Ramp', 'Shift (Block + Ramp)', 'Triangle', 'Strain'};

% For each field (start at 3 because coordinates are in the first 2 columns
for i = 3:11
   figure
   % Establish the color scale; we need to do this before plotting because we're using plot3k
   ca = mean(b(:, i)) + [-2*std(b(:, i)) 2*std(b(:, i))];
   ca = [floor(ca(1)) ceil(ca(2))];
   % Special case for residual field: use bluewhitered instead of jet as the colormap
   if i == 5
      caxis(ca); colormap(bluewhitered)
   end
   % Plot using plot3k; the "ca" specification indicates the color range
   plot3k([b(:, 1:2) zeros(size(b, 1), 1)], b(:, i), ca); view(2);
   caxis(ca); colorbar
   aa = axis;
   hold on
   % Plot the segments for geographic reference
   line([Segment.lon1'; Segment.lon2'], [Segment.lat1'; Segment.lat2'], 'color', 0.5*[1 1 1]);
   axis equal; axis(aa);
   title(titles{i-2});
   % Save files if requested
   if exist('save', 'var')
      if save == 1
         fname = [direc filesep titles{i-2} '.fig'];
         saveas(gcf, fname, 'fig')
      end
   end
end


text:
package org.wso2.carbon.identity.user.endpoint.factories;

import org.wso2.carbon.identity.user.endpoint.IntrospectCodeApiService;
import org.wso2.carbon.identity.user.endpoint.impl.IntrospectCodeApiServiceImpl;

public class IntrospectCodeApiServiceFactory {

   private final static IntrospectCodeApiService service = new IntrospectCodeApiServiceImpl();

   public static IntrospectCodeApiService getIntrospectCodeApi()
   {
      return service;
   }
}


text:
package com.yin.myproject.demo.string;

import java.util.StringTokenizer;

/**
 * Created by XunzhiYin on 2016/7/21 14:16.
 */
public class StringTokenizerDemo {
    public static void main(String[] args) {
        new StringTokenizerDemo().demo1();
        new StringTokenizerDemo().demo2();
        new StringTokenizerDemo().demo3();
    }

    public void demo1() {
        String content = "Both sides reached consensus on market access and the text of free trade agreement, " +
                "making a substantive progress and a basic completion of the FTA negotiation.";
        StringTokenizer st = new StringTokenizer(content);
        System.out.println("分割后Token的个数-->" + st.countTokens());
        int i = 1;
        while (st.hasMoreElements()) {
            String token = st.nextToken();
            System.out.print(i + "." + token + " ");
            i++;
        }
    }

    public void demo2() {
        String content = "https://blog.jetbrains.com/idea/2009/04/global-unused-declaration-inspection/";
        StringTokenizer st = new StringTokenizer(content, "/");
        System.out.println("分割后Token的个数-->" + st.countTokens());
        int i = 1;
        while (st.hasMoreElements()) {
            String token = st.nextToken();
            System.out.print(i + "." + token + " ");
            i++;
        }
    }

    public void demo3() {
        String content = "https://blog.jetbrains.com/idea/2009/04/global-unused-declaration-inspection/";
        StringTokenizer st = new StringTokenizer(content, "/", true);
        System.out.println("分割后Token的个数-->" + st.countTokens());
        int i = 1;
        while (st.hasMoreElements()) {
            String token = st.nextToken();
            System.out.print(i + "." + token + " ");
            i++;
        }
    }
}


text:
/**
 * @author mrdoob / http://mrdoob.com/
 */

export var Config = function ( name ) {

	var storage = {
		'autosave': true,
		'theme': 'css/light.css',

		'project/renderer': 'WebGLRenderer',
		'project/renderer/antialias': true,
		'project/renderer/gammaInput': false,
		'project/renderer/gammaOutput': false,
		'project/renderer/shadows': true,
		'project/editable': false,
		'project/vr': false,

		'settings/history': false,

		'ui/sidebar/animation/collapsed': true,
		'ui/sidebar/script/collapsed': true
	};

	if ( window.localStorage[ name ] === undefined ) {

		window.localStorage[ name ] = JSON.stringify( storage );

	} else {

		var data = JSON.parse( window.localStorage[ name ] );

		for ( var key in data ) {

			storage[ key ] = data[ key ];

		}

	}

	return {

		getKey: function ( key ) {

			return storage[ key ];

		},

		setKey: function () { // key, value, key, value ...

			for ( var i = 0, l = arguments.length; i < l; i += 2 ) {

				storage[ arguments[ i ] ] = arguments[ i + 1 ];

			}

			window.localStorage[ name ] = JSON.stringify( storage );

			console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved config to LocalStorage.' );

		},

		clear: function () {

			delete window.localStorage[ name ];

		}

	};

};