text:
package org.locationtech.geomesa.tools.export.formats

import java.io.File
import java.net.URL

import org.geotools.data.Transaction
import org.geotools.data.shapefile.files.ShpFiles
import org.geotools.data.shapefile.{ShapefileDataStore, ShapefileDataStoreFactory}
import org.geotools.util.URLs
import org.locationtech.geomesa.utils.io.WithClose
import org.locationtech.jts.geom.Geometry
import org.opengis.feature.simple.{SimpleFeature, SimpleFeatureType}

class ShapefileExporter(file: File) extends FeatureExporter {

  import scala.collection.JavaConverters._

  private val url = URLs.fileToUrl(file)
  private var ds: ShapefileDataStore = _
  private var mappings: Map[Int, Int] = _

  override def start(sft: SimpleFeatureType): Unit = {
    // ensure that the parent directory exists, otherwise the data store will error out
    Option(file.getParentFile).filterNot(_.exists()).foreach(_.mkdirs())
    ds = new ShapefileDataStoreFactory().createDataStore(url).asInstanceOf[ShapefileDataStore]
    ds.createSchema(sft)

    var i = -1
    var j = 0
    // map attributes according to the shapefile data store
    // default geometry goes to attribute 0, other geometries are dropped
    // byte arrays are dropped, but everything else is kept or transformed
    // see: `org.geotools.data.shapefile.ShapefileDataStore.createDbaseHeader()`
    val attributes = sft.getAttributeDescriptors.asScala.flatMap { d =>
      i += 1
      val binding = d.getType.getBinding
      if (classOf[Geometry].isAssignableFrom(binding) || binding == classOf[Array[Byte]] ) { None } else {
        j += 1
        Some(i -> j)
      }
    }
    mappings = attributes.toMap + (sft.indexOf(sft.getGeometryDescriptor.getLocalName) -> 0)
  }

  override def export(features: Iterator[SimpleFeature]): Option[Long] = {
    var count = 0L

    WithClose(ds.getFeatureWriterAppend(Transaction.AUTO_COMMIT)) { writer =>
      features.foreach { feature =>
        val toWrite = writer.next()
        mappings.foreach { case (from, to) => toWrite.setAttribute(to, feature.getAttribute(from)) }
        // copy over the user data
        // note: shapefile doesn't support provided fid
        toWrite.getUserData.putAll(feature.getUserData)
        writer.write()
        count += 1L
      }
    }

    Some(count)
  }

  override def bytes: Long = {
    val files = new ShpFiles(url)
    try {
      var sum = 0L
      files.getFileNames.asScala.values.foreach { file =>
        sum += URLs.urlToFile(new URL(file)).length()
      }
      sum
    } finally {
      files.dispose()
    }
  }

  override def close(): Unit = Option(ds).foreach(_.dispose)
}


text:
package androidx.emoji.text;

import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;

import android.content.res.AssetManager;

import androidx.annotation.AnyThread;
import androidx.annotation.IntRange;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.text.emoji.flatbuffer.MetadataList;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Reads the emoji metadata from a given InputStream or ByteBuffer.
 *
 * @hide
 */
@RestrictTo(LIBRARY_GROUP)
@AnyThread
@RequiresApi(19)
class MetadataListReader {

    /**
     * Meta tag for emoji metadata. This string is used by the font update script to insert the
     * emoji meta into the font. This meta table contains the list of all emojis which are stored in
     * binary format using FlatBuffers. This flat list is later converted by the system into a trie.
     * {@code int} representation for "Emji"
     *
     * @see MetadataRepo
     */
    private static final int EMJI_TAG = 'E' << 24 | 'm' << 16 | 'j' << 8 | 'i';

    /**
     * Deprecated meta tag name. Do not use, kept for compatibility reasons, will be removed soon.
     */
    private static final int EMJI_TAG_DEPRECATED = 'e' << 24 | 'm' << 16 | 'j' << 8 | 'i';

    /**
     * The name of the meta table in the font. int representation for "meta"
     */
    private static final int META_TABLE_NAME = 'm' << 24 | 'e' << 16 | 't' << 8 | 'a';

    /**
     * Construct MetadataList from an input stream. Does not close the given InputStream, therefore
     * it is caller's responsibility to properly close the stream.
     *
     * @param inputStream InputStream to read emoji metadata from
     */
    static MetadataList read(InputStream inputStream) throws IOException {
        final OpenTypeReader openTypeReader = new InputStreamOpenTypeReader(inputStream);
        final OffsetInfo offsetInfo = findOffsetInfo(openTypeReader);
        // skip to where metadata is
        openTypeReader.skip((int) (offsetInfo.getStartOffset() - openTypeReader.getPosition()));
        // allocate a ByteBuffer and read into it since FlatBuffers can read only from a ByteBuffer
        final ByteBuffer buffer = ByteBuffer.allocate((int) offsetInfo.getLength());
        final int numRead = inputStream.read(buffer.array());
        if (numRead != offsetInfo.getLength()) {
            throw new IOException("Needed " + offsetInfo.getLength() + " bytes, got " + numRead);
        }

        return MetadataList.getRootAsMetadataList(buffer);
    }

    /**
     * Construct MetadataList from a byte buffer.
     *
     * @param byteBuffer ByteBuffer to read emoji metadata from
     */
    static MetadataList read(final ByteBuffer byteBuffer) throws IOException {
        final ByteBuffer newBuffer = byteBuffer.duplicate();
        final OpenTypeReader reader = new ByteBufferReader(newBuffer);
        final OffsetInfo offsetInfo = findOffsetInfo(reader);
        // skip to where metadata is
        newBuffer.position((int) offsetInfo.getStartOffset());
        return MetadataList.getRootAsMetadataList(newBuffer);
    }

    /**
     * Construct MetadataList from an asset.
     *
     * @param assetManager AssetManager instance
     * @param assetPath asset manager path of the file that the Typeface and metadata will be
     *                  created from
     */
    static MetadataList read(AssetManager assetManager, String assetPath)
            throws IOException {
        try (InputStream inputStream = assetManager.open(assetPath)) {
            return read(inputStream);
        }
    }

    /**
     * Finds the start offset and length of the emoji metadata in the font.
     *
     * @return OffsetInfo which contains start offset and length of the emoji metadata in the font
     *
     * @throws IOException
     */
    private static OffsetInfo findOffsetInfo(OpenTypeReader reader) throws IOException {
        // skip sfnt version
        reader.skip(OpenTypeReader.UINT32_BYTE_COUNT);
        // start of Table Count
        final int tableCount = reader.readUnsignedShort();
        if (tableCount > 100) {
            //something is wrong quit
            throw new IOException("Cannot read metadata.");
        }
        //skip to begining of tables data
        reader.skip(OpenTypeReader.UINT16_BYTE_COUNT * 3);

        long metaOffset = -1;
        for (int i = 0; i < tableCount; i++) {
            final int tag = reader.readTag();
            // skip checksum
            reader.skip(OpenTypeReader.UINT32_BYTE_COUNT);
            final long offset = reader.readUnsignedInt();
            // skip mLength
            reader.skip(OpenTypeReader.UINT32_BYTE_COUNT);
            if (META_TABLE_NAME == tag) {
                metaOffset = offset;
                break;
            }
        }

        if (metaOffset != -1) {
            // skip to the begining of meta tables.
            reader.skip((int) (metaOffset - reader.getPosition()));
            // skip minorVersion, majorVersion, flags, reserved,
            reader.skip(
                    OpenTypeReader.UINT16_BYTE_COUNT * 2 + OpenTypeReader.UINT32_BYTE_COUNT * 2);
            final long mapsCount = reader.readUnsignedInt();
            for (int i = 0; i < mapsCount; i++) {
                final int tag = reader.readTag();
                final long dataOffset = reader.readUnsignedInt();
                final long dataLength = reader.readUnsignedInt();
                if (EMJI_TAG == tag || EMJI_TAG_DEPRECATED == tag) {
                    return new OffsetInfo(dataOffset + metaOffset, dataLength);
                }
            }
        }

        throw new IOException("Cannot read metadata.");
    }

    /**
     * Start offset and length of the emoji metadata in the font.
     */
    private static class OffsetInfo {
        private final long mStartOffset;
        private final long mLength;

        OffsetInfo(long startOffset, long length) {
            mStartOffset = startOffset;
            mLength = length;
        }

        long getStartOffset() {
            return mStartOffset;
        }

        long getLength() {
            return mLength;
        }
    }

    private static int toUnsignedShort(final short value) {
        return value & 0xFFFF;
    }

    private static long toUnsignedInt(final int value) {
        return value & 0xFFFFFFFFL;
    }

    private interface OpenTypeReader {
        int UINT16_BYTE_COUNT = 2;
        int UINT32_BYTE_COUNT = 4;

        /**
         * Reads an {@code OpenType uint16}.
         *
         * @throws IOException
         */
        int readUnsignedShort() throws IOException;

        /**
         * Reads an {@code OpenType uint32}.
         *
         * @throws IOException
         */
        long readUnsignedInt() throws IOException;

        /**
         * Reads an {@code OpenType Tag}.
         *
         * @throws IOException
         */
        int readTag() throws IOException;

        /**
         * Skip the given amount of numOfBytes
         *
         * @throws IOException
         */
        void skip(int numOfBytes) throws IOException;

        /**
         * @return the position of the reader
         */
        long getPosition();
    }

    /**
     * Reads {@code OpenType} data from an {@link InputStream}.
     */
    private static class InputStreamOpenTypeReader implements OpenTypeReader {

        private final byte[] mByteArray;
        private final ByteBuffer mByteBuffer;
        private final InputStream mInputStream;
        private long mPosition = 0;

        /**
         * Constructs the reader with the given InputStream. Does not close the InputStream, it is
         * caller's responsibility to close it.
         *
         * @param inputStream InputStream to read from
         */
        InputStreamOpenTypeReader(final InputStream inputStream) {
            mInputStream = inputStream;
            mByteArray = new byte[UINT32_BYTE_COUNT];
            mByteBuffer = ByteBuffer.wrap(mByteArray);
            mByteBuffer.order(ByteOrder.BIG_ENDIAN);
        }

        @Override
        public int readUnsignedShort() throws IOException {
            mByteBuffer.position(0);
            read(UINT16_BYTE_COUNT);
            return toUnsignedShort(mByteBuffer.getShort());
        }

        @Override
        public long readUnsignedInt() throws IOException {
            mByteBuffer.position(0);
            read(UINT32_BYTE_COUNT);
            return toUnsignedInt(mByteBuffer.getInt());
        }

        @Override
        public int readTag() throws IOException {
            mByteBuffer.position(0);
            read(UINT32_BYTE_COUNT);
            return mByteBuffer.getInt();
        }

        @Override
        public void skip(int numOfBytes) throws IOException {
            while (numOfBytes > 0) {
                int skipped = (int) mInputStream.skip(numOfBytes);
                if (skipped < 1) {
                    throw new IOException("Skip didn't move at least 1 byte forward");
                }
                numOfBytes -= skipped;
                mPosition += skipped;
            }
        }

        @Override
        public long getPosition() {
            return mPosition;
        }

        private void read(@IntRange(from = 0, to = UINT32_BYTE_COUNT) final int numOfBytes)
                throws IOException {
            if (mInputStream.read(mByteArray, 0, numOfBytes) != numOfBytes) {
                throw new IOException("read failed");
            }
            mPosition += numOfBytes;
        }
    }

    /**
     * Reads OpenType data from a ByteBuffer.
     */
    private static class ByteBufferReader implements OpenTypeReader {

        private final ByteBuffer mByteBuffer;

        /**
         * Constructs the reader with the given ByteBuffer.
         *
         * @param byteBuffer ByteBuffer to read from
         */
        ByteBufferReader(final ByteBuffer byteBuffer) {
            mByteBuffer = byteBuffer;
            mByteBuffer.order(ByteOrder.BIG_ENDIAN);
        }

        @Override
        public int readUnsignedShort() throws IOException {
            return toUnsignedShort(mByteBuffer.getShort());
        }

        @Override
        public long readUnsignedInt() throws IOException {
            return toUnsignedInt(mByteBuffer.getInt());
        }

        @Override
        public int readTag() throws IOException {
            return mByteBuffer.getInt();
        }

        @Override
        public void skip(final int numOfBytes) throws IOException {
            mByteBuffer.position(mByteBuffer.position() + numOfBytes);
        }

        @Override
        public long getPosition() {
            return mByteBuffer.position();
        }
    }

    private MetadataListReader() {
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>
        <record id="is_paperformat_a4_plastigray" model="report.paperformat">
            <field name="name">A4 - Plastigray</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">55</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">50</field>
            <field name="dpi">90</field>
        </record>

        <record id="devis_commandes_paperformat" model="report.paperformat">
            <field name="name">A4 - AR de commande</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">65</field>
            <field name="margin_bottom">25</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">60</field>
            <field name="dpi">90</field>
        </record>

        <record id="ar_commandes_paperformat" model="report.paperformat">
            <field name="name">A4 - AR de commande</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">80</field>
            <field name="margin_bottom">25</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">75</field>
            <field name="dpi">90</field>
        </record>

        <record id="is_paperformat_bl" model="report.paperformat">
            <field name="name">A4 - Bon de livraison</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">55</field>
            <field name="margin_bottom">25</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">50</field>
            <field name="dpi">90</field>
        </record>

        <record id="is_paperformat_facture_client" model="report.paperformat">
            <field name="name">A4 - Facture Client</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">85</field>
            <field name="margin_bottom">25</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">80</field>
            <field name="dpi">90</field>
        </record>

        <record id="cde_ouverte_fournisseur_paperformat" model="report.paperformat">
            <field name="name">A4 - Commande ouverte fournisseur</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">88</field>
            <field name="margin_bottom">25</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">83</field>
            <field name="dpi">90</field>
        </record>

        <record id="cde_ferme_cadencee_paperformat" model="report.paperformat">
            <field name="name">A4 - Commande ferme cadencée</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">78</field>
            <field name="margin_bottom">25</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">73</field>
            <field name="dpi">90</field>
        </record>

        <record id="purchaseorder_paperformat" model="report.paperformat">
            <field name="name">A4 - Commande fournisseur</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">88</field>
            <field name="margin_bottom">25</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">83</field>
            <field name="dpi">90</field>
        </record>

        <record id="document_fabrication_landscape_paperformat" model="report.paperformat">
            <field name="name">Document de fabrication</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Landscape</field>
            <field name="margin_top">20</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">15</field>
            <field name="dpi">90</field>
        </record>

        <record id="document_livraison_gefbox" model="report.paperformat">
            <field name="name">Document de fabrication</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Landscape</field>
            <field name="margin_top">20</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">15</field>
            <field name="dpi">90</field>
        </record>

        <record id="plan_de_charge_portrait_paperformat" model="report.paperformat">
            <field name="name">Plan de charge Portrait</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">7</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">0</field>
            <field name="dpi">90</field>
        </record>
        <record id="plan_de_charge_landscape_paperformat" model="report.paperformat">
            <field name="name">Plan de charge Paysage</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Landscape</field>
            <field name="margin_top">7</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">0</field>
            <field name="dpi">90</field>
        </record>

        <record id="bon_transfert_paperformat" model="report.paperformat">
            <field name="name">Bon de transfert</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">55</field>
            <field name="margin_bottom">25</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">50</field>
            <field name="dpi">90</field>
        </record>

        <record id="liste_servir_paperformat" model="report.paperformat">
            <field name="name">A4 - Liste à servir</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Landscape</field>
            <field name="margin_top">50</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">45</field>
            <field name="dpi">90</field>
        </record>

        <record id="proforma_paperformat" model="report.paperformat">
            <field name="name">A4 - PROFORMA</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Landscape</field>
            <field name="margin_top">60</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">55</field>
            <field name="dpi">90</field>
        </record>

        <record id="liste_article_paperformat" model="report.paperformat">
            <field name="name">A4 - Liste des articles</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">15</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">10</field>
            <field name="dpi">90</field>
        </record>

        <record id="is_cout_paperformat" model="report.paperformat">
            <field name="name">A4 - Coût article</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">25</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">20</field>
            <field name="dpi">90</field>
        </record>

        <record id="pricelist_version_paperformat" model="report.paperformat">
            <field name="name">A4 - Liste des prix</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">25</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">20</field>
            <field name="dpi">90</field>
        </record>

        <record id="is_facture_pk_paperformat" model="report.paperformat">
            <field name="name">Facture PK</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">15</field>
            <field name="margin_bottom">25</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">10</field>
            <field name="dpi">90</field>
        </record>

        <record id="is_consigne_journaliere_paperformat" model="report.paperformat">
            <field name="name">A4 - Consignes journalières</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Landscape</field>
            <field name="margin_top">23</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">18</field>
            <field name="dpi">90</field>
        </record>

        <record id="is_bl_manuel_paperformat" model="report.paperformat">
            <field name="name">A4 - BL manuel</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">55</field>
            <field name="margin_bottom">25</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">50</field>
            <field name="dpi">90</field>
        </record>

        <record id="emballage_paperformat" model="report.paperformat">
            <field name="name">Emballage</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">7</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">0</field>
            <field name="dpi">90</field>
        </record>

        <record id="inventaire_paperformat" model="report.paperformat">
            <field name="name">Inventaire</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Landscape</field>
            <field name="margin_top">7</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">0</field>
            <field name="dpi">90</field>
        </record>

        <record id="inventaire_ecart_paperformat" model="report.paperformat">
            <field name="name">Feuilles écarts d'inventaire</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">40</field>
            <field name="margin_bottom">15</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">30</field>
            <field name="dpi">90</field>
        </record>

        <record id="reach_paperformat" model="report.paperformat">
            <field name="name">A4 - AR de commande</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">65</field>
            <field name="margin_bottom">25</field>
            <field name="margin_left">7</field>
            <field name="margin_right">7</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">60</field>
            <field name="dpi">90</field>
        </record>

        <record id="is_galia_base_paperformat" model="report.paperformat">
            <field name="name">A4 - Etiquette GALIA</field>
            <field name="default" eval="True" />
            <field name="format">A4</field>
            <field name="page_height">0</field>
            <field name="page_width">0</field>
            <field name="orientation">Portrait</field>
            <field name="margin_top">10</field>
            <field name="margin_bottom">10</field>
            <field name="margin_left">10</field>
            <field name="margin_right">10</field>
            <field name="header_line" eval="False" />
            <field name="header_spacing">10</field>
            <field name="dpi">90</field>
        </record>

    </data>
</openerp>


text:
import numpy as np
from numpy.testing import assert_array_almost_equal

from scipy.spatial import cKDTree

from sklearn import neighbors

# Note: simple tests of BallTree.query() and BallTree.query_radius()
# are contained within the tests of test_neighbors.py

def test_warning_flag(n_samples=100, n_features=3, k=3):
    """test that discarding identical distances triggers warning flag"""
    X = np.random.random(size=(n_samples, n_features))
    q = np.random.random(size=n_features)
    bt = neighbors.BallTree(X[:-1], leaf_size=5)
    dist, ind = bt.query(q, k=k)

    # make the last point identical to the furthest neighbor
    # querying this should set warning_flag to True
    X[-1:] = X[ind[0, k - 1]]

    bt = neighbors.BallTree(X, leaf_size=5)
    dist, ind = bt.query(q, k=k)

    assert bt.warning_flag

    # make the last point identical to the closest neighbor
    # though the distance is identical, there is no ambiguity, so there
    # should be no warning.  If k==1, this should not be done
    if k > 1:
        X[-1:] = X[ind[0, 0]]

        bt = neighbors.BallTree(X, leaf_size=5)
        dist, ind = bt.query(q, k=k)

        assert not bt.warning_flag

def test_ball_tree_query_radius(n_samples=100, n_features=10):
    X = 2 * np.random.random(size=(n_samples, n_features)) - 1
    query_pt = np.zeros(n_features, dtype=float)

    eps = 1E-15  # roundoff error can cause test to fail
    bt = neighbors.BallTree(X, leaf_size=5)
    rad = np.sqrt(((X - query_pt) ** 2).sum(1))

    for r in np.linspace(rad[0], rad[-1], 100):
        ind = bt.query_radius(query_pt, r + eps)[0]
        i = np.where(rad <= r + eps)[0]

        ind.sort()
        i.sort()

        assert np.all(i == ind)

def test_ball_tree_query_radius_distance(n_samples=100, n_features=10):
    X = 2 * np.random.random(size=(n_samples, n_features)) - 1
    query_pt = np.zeros(n_features, dtype=float)

    eps = 1E-15  # roundoff error can cause test to fail
    bt = neighbors.BallTree(X, leaf_size=5)
    rad = np.sqrt(((X - query_pt) ** 2).sum(1))

    for r in np.linspace(rad[0], rad[-1], 100):
        ind, dist = bt.query_radius(query_pt, r + eps, return_distance=True)

        ind = ind[0]
        dist = dist[0]

        d = np.sqrt(((query_pt - X[ind]) ** 2).sum(1))

        assert_array_almost_equal(d, dist)

def test_ball_tree_pickle():
    import pickle
    X = np.random.random(size=(10, 3))
    bt1 = neighbors.BallTree(X, leaf_size=1)
    ind1, dist1 = bt1.query(X)
    for protocol in (0, 1, 2):
        s = pickle.dumps(bt1, protocol=protocol)
        bt2 = pickle.loads(s)
        ind2, dist2 = bt2.query(X)
        assert np.all(ind1 == ind2)
        assert_array_almost_equal(dist1, dist2)

def test_ball_tree_p_distance():
    X = np.random.random(size=(100, 5))

    for p in (1, 2, 3, 4, np.inf):
        bt = neighbors.BallTree(X, leaf_size=10, p=p)
        kdt = cKDTree(X, leafsize=10)

        dist_bt, ind_bt = bt.query(X, k=5)
        dist_kd, ind_kd = kdt.query(X, k=5, p=p)

        assert_array_almost_equal(dist_bt, dist_kd)

if __name__ == '__main__':
    import nose
    nose.runmodule()


text:
package com.esri.core.geometry;

import java.nio.ByteBuffer;

import com.esri.core.geometry.Operator.Type;

/**
 *Import from ESRI shape format.
 */
public abstract class OperatorImportFromESRIShape extends Operator {
	@Override
	public Type getType() {
		return Type.ImportFromESRIShape;
	}

	/**
	 * Performs the ImportFromESRIShape operation on a stream of shape buffers
	 *
	 * @return Returns a GeometryCursor.
	 */
	abstract GeometryCursor execute(int importFlags, Geometry.Type type,
			ByteBufferCursor shapeBuffers);

	/**
	 * Performs the ImportFromESRIShape operation.
	 * @param importFlags Use the {@link ShapeImportFlags} interface.
	 * @param type Use the {@link Geometry.Type} enum.
	 * @param shapeBuffer The buffer holding the Geometry in ESRIShape format.
	 * @return Returns the imported Geometry.
	 */
	public abstract Geometry execute(int importFlags, Geometry.Type type,
			ByteBuffer shapeBuffer);

	public static OperatorImportFromESRIShape local() {
		return (OperatorImportFromESRIShape) OperatorFactoryLocal.getInstance()
				.getOperator(Type.ImportFromESRIShape);
	}

}


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

package client

import "strconv"

/// Collection of standard errors

// APINotImplemented - api not implemented
type APINotImplemented struct {
	API     string
	APIType string
}

func (e APINotImplemented) Error() string {
	return "'" + e.API + "' feature " + "is not implemented for '" + e.APIType + "'"
}

// UnexpectedError - unexpected error
type UnexpectedError GenericError

func (e UnexpectedError) Error() string {
	return "Unexpected error, please report this error at https://github.com/minio/mc/issues"
}

// InvalidArgument - bad arguments provided
type InvalidArgument GenericError

func (e InvalidArgument) Error() string {
	return "Invalid argument"
}

// InvalidRange - invalid range requested
type InvalidRange struct {
	Offset int64
}

func (e InvalidRange) Error() string {
	return "invalid range offset: " + strconv.FormatInt(e.Offset, 10)
}

// InvalidACLType - invalid acl type
type InvalidACLType struct {
	ACL string
}

func (e InvalidACLType) Error() string {
	return "invalid acl type: " + e.ACL
}

// InvalidMaxKeys - invalid maxkeys provided
type InvalidMaxKeys struct {
	MaxKeys int
}

func (e InvalidMaxKeys) Error() string {
	return "invalid maxkeys: " + strconv.Itoa(e.MaxKeys)
}

// GenericBucketError - generic bucket operations error
type GenericBucketError struct {
	Bucket string
}

// BucketExists - bucket exists
type BucketExists GenericBucketError

func (e BucketExists) Error() string {
	return "bucket " + e.Bucket + " exists"
}

// InvalidBucketName - bucket name invalid (http://goo.gl/wJlzDz)
type InvalidBucketName GenericBucketError

func (e InvalidBucketName) Error() string {
	return "Invalid bucketname [" + e.Bucket + "], please read http://goo.gl/wJlzDz"
}

// GenericObjectError - generic object operations error
type GenericObjectError struct {
	Bucket string
	Object string
}

// ObjectAlreadyExists - typed return for MethodNotAllowed
type ObjectAlreadyExists struct {
	Object string
}

func (e ObjectAlreadyExists) Error() string {
	return "Object #" + e.Object + " already exists."
}

// ObjectNotFound - object requested does not exist
type ObjectNotFound GenericObjectError

func (e ObjectNotFound) Error() string {
	return "object " + e.Object + " not found in bucket " + e.Bucket
}

// InvalidObjectName - object requested is invalid
type InvalidObjectName GenericObjectError

func (e InvalidObjectName) Error() string {
	return "object " + e.Object + "at" + e.Bucket + "is invalid"
}

// ObjectExists - object exists
type ObjectExists GenericObjectError

func (e ObjectExists) Error() string {
	return "object " + e.Object + " exists"
}

// GenericError - generic error
type GenericError struct{}

// InvalidQueryURL - generic error
type InvalidQueryURL struct {
	URL string
}

func (e InvalidQueryURL) Error() string {
	return "Invalid query URL: " + e.URL
}

// GenericFileError - generic file error
type GenericFileError struct {
	Path string
}

// NotFound (ENOENT) - file not found
type NotFound GenericFileError

func (e NotFound) Error() string {
	return "Requested file '" + e.Path + "' not found"
}

// ISFolder (EISDIR) - accessed file is a folder
type ISFolder GenericFileError

func (e ISFolder) Error() string {
	return "Requested file '" + e.Path + "' is a folder"
}

// NotFolder (ENOTDIR) - accessed file is not a folder
type NotFolder GenericFileError

func (e NotFolder) Error() string {
	return "Requested file '" + e.Path + "' is not a folder"
}

// ISBrokenSymlink (ENOTENT) - file has broken symlink
type ISBrokenSymlink GenericFileError

func (e ISBrokenSymlink) Error() string {
	return "Requested file '" + e.Path + "' has broken symlink"
}

// EmptyPath (EINVAL) - invalid argument
type EmptyPath struct{}

func (e EmptyPath) Error() string {
	return "Invalid path, path cannot be empty"
}


text:
package org.usfirst.frc4947.robot2015.commands;

import org.usfirst.frc4947.robot2015.subsystems.Elevator;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class AutonomousSimple extends CommandGroup {

    public  AutonomousSimple() {
    	addSequential(new ElevatorHome());
    	addSequential(new ElevatorPosition(Elevator.ACCEPT));
    	addSequential(new DriveBackward(0.7, 3.0));
    }
}


text:
package cms.ymb.utils;

import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

@Component
public class MysqlDMDSFactory implements DMDSFactory {

    private Properties conf;

    private void readConfigFile() {
        try {
            this.conf = new Properties();
            this.conf.load(new InputStreamReader(new FileInputStream("db.conf")));
        } catch (IOException e) {
            System.out.println("Configuration file 'db.conf' could not be loaded, aborting!");
            System.exit(0);
        }
    }

    public DriverManagerDataSource getDMDS() {
        this.readConfigFile();

        DriverManagerDataSource dmds = new DriverManagerDataSource(
                this.conf.getProperty("host"),
                this.conf.getProperty("login"),
                this.conf.getProperty("password")
        );
        dmds.setDriverClassName("com.mysql.jdbc.Driver");
        return dmds;
    }
}


text:
// -----------------------------------------------------------------------
// <copyright file="Primitives.cs">
// Original Triangle code by Jonathan Richard Shewchuk, http://www.cs.cmu.edu/~quake/triangle.html
// Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/
// </copyright>
// -----------------------------------------------------------------------

namespace TriangleNet
{
    using System;
    using TriangleNet.Data;
    using TriangleNet.Geometry;
    using TriangleNet.Tools;

    /// <summary>
    /// Provides some primitives regularly used in computational geometry.
    /// </summary>
    public static class Primitives
    {
        static double splitter;       // Used to split double factors for exact multiplication.
        static double epsilon;        // Floating-point machine epsilon.
        //static double resulterrbound;
        static double ccwerrboundA; // ccwerrboundB, ccwerrboundC;
        static double iccerrboundA; // iccerrboundB, iccerrboundC;

        /// <summary>
        /// Initialize the variables used for exact arithmetic.
        /// </summary>
        /// <remarks>
        /// 'epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in
        /// floating-point arithmetic. 'epsilon' bounds the relative roundoff
        /// error. It is used for floating-point error analysis.
        ///
        /// 'splitter' is used to split floating-point numbers into two half-
        /// length significands for exact multiplication.
        ///
        /// I imagine that a highly optimizing compiler might be too smart for its
        /// own good, and somehow cause this routine to fail, if it pretends that
        /// floating-point arithmetic is too much like real arithmetic.
        ///
        /// Don't change this routine unless you fully understand it.
        /// </remarks>
        public static void ExactInit()
        {
            double half;
            double check, lastcheck;
            bool every_other;

            every_other = true;
            half = 0.5;
            epsilon = 1.0;
            splitter = 1.0;
            check = 1.0;
            // Repeatedly divide 'epsilon' by two until it is too small to add to
            // one without causing roundoff. (Also check if the sum is equal to
            // the previous sum, for machines that round up instead of using exact
            // rounding.  Not that these routines will work on such machines.)
            do
            {
                lastcheck = check;
                epsilon *= half;
                if (every_other)
                {
                    splitter *= 2.0;
                }
                every_other = !every_other;
                check = 1.0 + epsilon;
            } while ((check != 1.0) && (check != lastcheck));
            splitter += 1.0;
            // Error bounds for orientation and incircle tests.
            //resulterrbound = (3.0 + 8.0 * epsilon) * epsilon;
            ccwerrboundA = (3.0 + 16.0 * epsilon) * epsilon;
            //ccwerrboundB = (2.0 + 12.0 * epsilon) * epsilon;
            //ccwerrboundC = (9.0 + 64.0 * epsilon) * epsilon * epsilon;
            iccerrboundA = (10.0 + 96.0 * epsilon) * epsilon;
            //iccerrboundB = (4.0 + 48.0 * epsilon) * epsilon;
            //iccerrboundC = (44.0 + 576.0 * epsilon) * epsilon * epsilon;
        }

        /// <summary>
        /// Check, if the three points appear in counterclockwise order. The result is
        /// also a rough approximation of twice the signed area of the triangle defined
        /// by the three points.
        /// </summary>
        /// <param name="pa">Point a.</param>
        /// <param name="pb">Point b.</param>
        /// <param name="pc">Point c.</param>
        /// <returns>Return a positive value if the points pa, pb, and pc occur in
        /// counterclockwise order; a negative value if they occur in clockwise order;
        /// and zero if they are collinear.</returns>
        /// <remarks>
        /// Uses exact arithmetic if necessary to ensure a correct answer. The
        /// result returned is the determinant of a matrix. This determinant is
        /// computed adaptively, in the sense that exact arithmetic is used only to
        /// the degree it is needed to ensure that the returned value has the
        /// correct sign. Hence, this function is usually quite fast, but will run
        /// more slowly when the input points are collinear or nearly so.
        ///
        /// See Robust Predicates paper for details.
        /// </remarks>
        public static double CounterClockwise(Point pa, Point pb, Point pc)
        {
            double detleft, detright, det;
            double detsum, errbound;

            Statistic.CounterClockwiseCount++;

            detleft = (pa.x - pc.x) * (pb.y - pc.y);
            detright = (pa.y - pc.y) * (pb.x - pc.x);
            det = detleft - detright;

            if (Behavior.NoExact)
            {
                return det;
            }

            if (detleft > 0.0)
            {
                if (detright <= 0.0)
                {
                    return det;
                }
                else
                {
                    detsum = detleft + detright;
                }
            }
            else if (detleft < 0.0)
            {
                if (detright >= 0.0)
                {
                    return det;
                }
                else
                {
                    detsum = -detleft - detright;
                }
            }
            else
            {
                return det;
            }

            errbound = ccwerrboundA * detsum;
            if ((det >= errbound) || (-det >= errbound))
            {
                return det;
            }

            return (double)CounterClockwiseDecimal(pa, pb, pc);
        }

        private static decimal CounterClockwiseDecimal(Point pa, Point pb, Point pc)
        {
            Statistic.CounterClockwiseCountDecimal++;

            decimal detleft, detright, det;

            detleft = ((decimal)pa.x - (decimal)pc.x) * ((decimal)pb.y - (decimal)pc.y);
            detright = ((decimal)pa.y - (decimal)pc.y) * ((decimal)pb.x - (decimal)pc.x);
            det = detleft - detright;

            if (detleft > 0.0m)
            {
                if (detright <= 0.0m)
                {
                    return det;
                }
                else
                {
                    //detsum = detleft + detright;
                }
            }
            else if (detleft < 0.0m)
            {
                if (detright >= 0.0m)
                {
                    return det;
                }
                else
                {
                    //detsum = -detleft - detright;
                }
            }

            return det;
        }

        /// <summary>
        /// Check if the point pd lies inside the circle passing through pa, pb, and pc. The
        /// points pa, pb, and pc must be in counterclockwise order, or the sign of the result
        /// will be reversed.
        /// </summary>
        /// <param name="pa">Point a.</param>
        /// <param name="pb">Point b.</param>
        /// <param name="pc">Point c.</param>
        /// <param name="pd">Point d.</param>
        /// <returns>Return a positive value if the point pd lies inside the circle passing through
        /// pa, pb, and pc; a negative value if it lies outside; and zero if the four points
        /// are cocircular.</returns>
        /// <remarks>
        /// Uses exact arithmetic if necessary to ensure a correct answer.  The
        /// result returned is the determinant of a matrix.  This determinant is
        /// computed adaptively, in the sense that exact arithmetic is used only to
        /// the degree it is needed to ensure that the returned value has the
        /// correct sign.  Hence, this function is usually quite fast, but will run
        /// more slowly when the input points are cocircular or nearly so.
        ///
        /// See Robust Predicates paper for details.
        /// </remarks>
        public static double InCircle(Point pa, Point pb, Point pc, Point pd)
        {
            double adx, bdx, cdx, ady, bdy, cdy;
            double bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
            double alift, blift, clift;
            double det;
            double permanent, errbound;

            Statistic.InCircleCount++;

            adx = pa.x - pd.x;
            bdx = pb.x - pd.x;
            cdx = pc.x - pd.x;
            ady = pa.y - pd.y;
            bdy = pb.y - pd.y;
            cdy = pc.y - pd.y;

            bdxcdy = bdx * cdy;
            cdxbdy = cdx * bdy;
            alift = adx * adx + ady * ady;

            cdxady = cdx * ady;
            adxcdy = adx * cdy;
            blift = bdx * bdx + bdy * bdy;

            adxbdy = adx * bdy;
            bdxady = bdx * ady;
            clift = cdx * cdx + cdy * cdy;

            det = alift * (bdxcdy - cdxbdy)
                + blift * (cdxady - adxcdy)
                + clift * (adxbdy - bdxady);

            if (Behavior.NoExact)
            {
                return det;
            }

            permanent = (Math.Abs(bdxcdy) + Math.Abs(cdxbdy)) * alift
                      + (Math.Abs(cdxady) + Math.Abs(adxcdy)) * blift
                      + (Math.Abs(adxbdy) + Math.Abs(bdxady)) * clift;
            errbound = iccerrboundA * permanent;
            if ((det > errbound) || (-det > errbound))
            {
                return det;
            }

            return (double)InCircleDecimal(pa, pb, pc, pd);
        }

        private static decimal InCircleDecimal(Point pa, Point pb, Point pc, Point pd)
        {
            Statistic.InCircleCountDecimal++;

            decimal adx, bdx, cdx, ady, bdy, cdy;
            decimal bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
            decimal alift, blift, clift;

            adx = (decimal)pa.x - (decimal)pd.x;
            bdx = (decimal)pb.x - (decimal)pd.x;
            cdx = (decimal)pc.x - (decimal)pd.x;
            ady = (decimal)pa.y - (decimal)pd.y;
            bdy = (decimal)pb.y - (decimal)pd.y;
            cdy = (decimal)pc.y - (decimal)pd.y;

            bdxcdy = bdx * cdy;
            cdxbdy = cdx * bdy;
            alift = adx * adx + ady * ady;

            cdxady = cdx * ady;
            adxcdy = adx * cdy;
            blift = bdx * bdx + bdy * bdy;

            adxbdy = adx * bdy;
            bdxady = bdx * ady;
            clift = cdx * cdx + cdy * cdy;

            return alift * (bdxcdy - cdxbdy)
                + blift * (cdxady - adxcdy)
                + clift * (adxbdy - bdxady);
        }

        /// <summary>
        /// Return a positive value if the point pd is incompatible with the circle
        /// or plane passing through pa, pb, and pc (meaning that pd is inside the
        /// circle or below the plane); a negative value if it is compatible; and
        /// zero if the four points are cocircular/coplanar. The points pa, pb, and
        /// pc must be in counterclockwise order, or the sign of the result will be
        /// reversed.
        /// </summary>
        /// <param name="pa">Point a.</param>
        /// <param name="pb">Point b.</param>
        /// <param name="pc">Point c.</param>
        /// <param name="pd">Point d.</param>
        /// <returns>Return a positive value if the point pd lies inside the circle passing through
        /// pa, pb, and pc; a negative value if it lies outside; and zero if the four points
        /// are cocircular.</returns>
        public static double NonRegular(Point pa, Point pb, Point pc, Point pd)
        {
            return InCircle(pa, pb, pc, pd);
        }

        /// <summary>
        /// Find the circumcenter of a triangle.
        /// </summary>
        /// <param name="torg">Triangle point.</param>
        /// <param name="tdest">Triangle point.</param>
        /// <param name="tapex">Triangle point.</param>
        /// <param name="xi">Relative coordinate of new location.</param>
        /// <param name="eta">Relative coordinate of new location.</param>
        /// <param name="offconstant">Off-center constant.</param>
        /// <returns>Coordinates of the circumcenter (or off-center)</returns>
        public static Point FindCircumcenter(Point torg, Point tdest, Point tapex,
                              ref double xi, ref double eta, double offconstant)
        {
            double xdo, ydo, xao, yao;
            double dodist, aodist, dadist;
            double denominator;
            double dx, dy, dxoff, dyoff;

            Statistic.CircumcenterCount++;

            // Compute the circumcenter of the triangle.
            xdo = tdest.x - torg.x;
            ydo = tdest.y - torg.y;
            xao = tapex.x - torg.x;
            yao = tapex.y - torg.y;
            dodist = xdo * xdo + ydo * ydo;
            aodist = xao * xao + yao * yao;
            dadist = (tdest.x - tapex.x) * (tdest.x - tapex.x) +
                     (tdest.y - tapex.y) * (tdest.y - tapex.y);

            if (Behavior.NoExact)
            {
                denominator = 0.5 / (xdo * yao - xao * ydo);
            }
            else
            {
                // Use the counterclockwise() routine to ensure a positive (and
                // reasonably accurate) result, avoiding any possibility of
                // division by zero.
                denominator = 0.5 / CounterClockwise(tdest, tapex, torg);
                // Don't count the above as an orientation test.
                Statistic.CounterClockwiseCount--;
            }

            dx = (yao * dodist - ydo * aodist) * denominator;
            dy = (xdo * aodist - xao * dodist) * denominator;

            // Find the (squared) length of the triangle's shortest edge.  This
            // serves as a conservative estimate of the insertion radius of the
            // circumcenter's parent. The estimate is used to ensure that
            // the algorithm terminates even if very small angles appear in
            // the input PSLG.
            if ((dodist < aodist) && (dodist < dadist))
            {
                if (offconstant > 0.0)
                {
                    // Find the position of the off-center, as described by Alper Ungor.
                    dxoff = 0.5 * xdo - offconstant * ydo;
                    dyoff = 0.5 * ydo + offconstant * xdo;
                    // If the off-center is closer to the origin than the
                    // circumcenter, use the off-center instead.
                    if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy)
                    {
                        dx = dxoff;
                        dy = dyoff;
                    }
                }
            }
            else if (aodist < dadist)
            {
                if (offconstant > 0.0)
                {
                    dxoff = 0.5 * xao + offconstant * yao;
                    dyoff = 0.5 * yao - offconstant * xao;
                    // If the off-center is closer to the origin than the
                    // circumcenter, use the off-center instead.
                    if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy)
                    {
                        dx = dxoff;
                        dy = dyoff;
                    }
                }
            }
            else
            {
                if (offconstant > 0.0)
                {
                    dxoff = 0.5 * (tapex.x - tdest.x) - offconstant * (tapex.y - tdest.y);
                    dyoff = 0.5 * (tapex.y - tdest.y) + offconstant * (tapex.x - tdest.x);
                    // If the off-center is closer to the destination than the
                    // circumcenter, use the off-center instead.
                    if (dxoff * dxoff + dyoff * dyoff <
                        (dx - xdo) * (dx - xdo) + (dy - ydo) * (dy - ydo))
                    {
                        dx = xdo + dxoff;
                        dy = ydo + dyoff;
                    }
                }
            }

            // To interpolate vertex attributes for the new vertex inserted at
            // the circumcenter, define a coordinate system with a xi-axis,
            // directed from the triangle's origin to its destination, and
            // an eta-axis, directed from its origin to its apex.
            // Calculate the xi and eta coordinates of the circumcenter.
            xi = (yao * dx - xao * dy) * (2.0 * denominator);
            eta = (xdo * dy - ydo * dx) * (2.0 * denominator);

            return new Point(torg.x + dx, torg.y + dy);
        }

        /// <summary>
        /// Find the circumcenter of a triangle.
        /// </summary>
        /// <param name="torg">Triangle point.</param>
        /// <param name="tdest">Triangle point.</param>
        /// <param name="tapex">Triangle point.</param>
        /// <param name="xi">Relative coordinate of new location.</param>
        /// <param name="eta">Relative coordinate of new location.</param>
        /// <returns>Coordinates of the circumcenter</returns>
        /// <remarks>
        /// The result is returned both in terms of x-y coordinates and xi-eta
        /// (barycentric) coordinates. The xi-eta coordinate system is defined in
        /// terms of the triangle: the origin of the triangle is the origin of the
        /// coordinate system; the destination of the triangle is one unit along the
        /// xi axis; and the apex of the triangle is one unit along the eta axis.
        /// This procedure also returns the square of the length of the triangle's
        /// shortest edge.
        /// </remarks>
        public static Point FindCircumcenter(Point torg, Point tdest, Point tapex,
                              ref double xi, ref double eta)
        {
            double xdo, ydo, xao, yao;
            double dodist, aodist;
            double denominator;
            double dx, dy;

            Statistic.CircumcenterCount++;

            // Compute the circumcenter of the triangle.
            xdo = tdest.x - torg.x;
            ydo = tdest.y - torg.y;
            xao = tapex.x - torg.x;
            yao = tapex.y - torg.y;
            dodist = xdo * xdo + ydo * ydo;
            aodist = xao * xao + yao * yao;

            if (Behavior.NoExact)
            {
                denominator = 0.5 / (xdo * yao - xao * ydo);
            }
            else
            {
                // Use the counterclockwise() routine to ensure a positive (and
                // reasonably accurate) result, avoiding any possibility of
                // division by zero.
                denominator = 0.5 / CounterClockwise(tdest, tapex, torg);
                // Don't count the above as an orientation test.
                Statistic.CounterClockwiseCount--;
            }

            dx = (yao * dodist - ydo * aodist) * denominator;
            dy = (xdo * aodist - xao * dodist) * denominator;

            // To interpolate vertex attributes for the new vertex inserted at
            // the circumcenter, define a coordinate system with a xi-axis,
            // directed from the triangle's origin to its destination, and
            // an eta-axis, directed from its origin to its apex.
            // Calculate the xi and eta coordinates of the circumcenter.
            xi = (yao * dx - xao * dy) * (2.0 * denominator);
            eta = (xdo * dy - ydo * dx) * (2.0 * denominator);

            return new Point(torg.x + dx, torg.y + dy);
        }
    }
}


text:
MashCrashReporterClient::MashCrashReporterClient() {}

MashCrashReporterClient::~MashCrashReporterClient() {}

void MashCrashReporterClient::GetProductNameAndVersion(
    const char** product_name,
    const char** version) {
  *product_name = "Chrome_ChromeOS";
  *version = PRODUCT_VERSION;
}

base::FilePath MashCrashReporterClient::GetReporterLogFilename() {
  return base::FilePath(CrashUploadList::kReporterLogFilename);
}

bool MashCrashReporterClient::GetCrashDumpLocation(base::FilePath* crash_dir) {
  // For development on Linux desktop just use /tmp.
  if (!base::SysInfo::IsRunningOnChromeOS()) {
    *crash_dir = base::FilePath("/tmp");
    return true;
  }

  // TODO(jamescook): Refactor chrome::DIR_CRASH_DUMPS into //components/crash
  // and use it here.
  *crash_dir = base::FilePath("/var/log/chrome/Crash Reports");
  DCHECK(base::PathExists(*crash_dir));
  return true;
}

size_t MashCrashReporterClient::RegisterCrashKeys() {
  // Register keys used by non-browser processes launched by the service manager
  // (e.g. the GPU service). See chrome/common/crash_keys.cc.
  std::vector<base::debug::CrashKey> keys = {
      {"url-chunk", crash_keys::kLargeSize},
      {"total-discardable-memory-allocated", crash_keys::kSmallSize},
      {"discardable-memory-free", crash_keys::kSmallSize},
  };
  crash_keys::GetCrashKeysForCommandLineSwitches(&keys);
  return base::debug::InitCrashKeys(&keys.at(0), keys.size(),
                                    crash_keys::kChunkMaxLength);
}

bool MashCrashReporterClient::IsRunningUnattended() {
  return false;
}

bool MashCrashReporterClient::GetCollectStatsConsent() {
#if defined(GOOGLE_CHROME_BUILD)
  // For development on Linux desktop allow crash reporting to be forced on.
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableCrashReporterForTesting)) {
    return true;
  }
  // TODO(jamescook): Refactor this to share code with
  // chrome/browser/google/google_update_settings_posix.cc.
  base::FilePath consent_file("/home/chronos/Consent To Send Stats");
  return base::PathExists(consent_file);
#else
  // Crash reporting is only supported in branded builds.
  return false;
#endif  // defined(GOOGLE_CHROME_BUILD)
}


text:
require 'rails_helper'

describe Api::V1::ScenariosController do
  render_views

  before do
    @generator = create(:generator)
    @column = create(:column, min: 1, max: 1, parent_generators: [@generator])
    @option = create(:option, column: @column)
    @column_two = create(:column, min: 2, max: 2, parent_columns: [@column])
    @options_for_column_two = create_list(:option, 2, column: @column_two)
  end

  def generate_expected_column_result(column, options)
    {
      'id' => column.id,
      'name' => column.name,
      'help' => column.help,
      'options' => options.map { |option| { 'id' => option.id, 'text' => option.text } },
      'columns' => [],
    }
  end

  describe 'GET new' do
    describe 'when passed random as generator id' do
      before do
        @generator_two = create(:generator)
        get :new, generator_id: 'random', format: :json
        @json = JSON.parse(response.body).with_indifferent_access
      end

      it 'will return a random generator' do
        generator_id = @json[:generator][:id]
        expect(Generator.all.map(&:id)).to include generator_id
      end
    end

    describe 'with one column' do
      before do
        @generator = create(:generator)
        @column = create(:column, min: 1, max: 1, parent_generators: [@generator])
        @option = create(:option, column: @column)
        @expected_column_result = generate_expected_column_result(@column, [@option])
        get :new, generator_id: @generator.id, format: :json
        @json = JSON.parse(response.body).with_indifferent_access
        @scenario = @json[:scenario][:columns]
      end

      it 'returns a scenario containing that column' do
        expect(@scenario).to eq [@expected_column_result]
      end

      describe 'that has two options to pick from' do
        before { @option_new = create(:option, column: @column) }

        describe 'with a max of 1' do
          before do
            get :new, generator_id: @generator.id, format: :json
            @json = JSON.parse(response.body).with_indifferent_access
            @scenario = @json[:scenario][:columns]
            @returned_options = @scenario[0][:options]
          end

          it 'returns one of the options' do
            expect((@column.options.map { |option| option[:id] } | @returned_options.map { |option| option[:id] }).length).to be > 0
          end

          it 'returns max quantity one options' do
            expect(@returned_options.length).to eq 1
          end

          describe 'with exclusions' do
            before do
              @exclusion = @column.exclusion_sets.create(options: [@option_new, @option])
              get :new, generator_id: @generator.id, format: :json
              @json = JSON.parse(response.body).with_indifferent_access
              @scenario = @json[:scenario][:columns]
              @returned_options = @scenario[0][:options]
            end

            it 'returns one of the options' do
              expect((@column.options.map { |option| option[:id] } | @returned_options.map { |option| option[:id] }).length).to be > 0
            end

            it 'returns max quantity one options' do
              expect(@returned_options.length).to eq 1
            end
          end
        end

        describe 'with a max of 2' do
          describe 'and a min of 2' do
            before do
              @column.max = 2
              @column.min = 2
              @column.save
              get :new, generator_id: @generator.id, format: :json
              @json = JSON.parse(response.body).with_indifferent_access
              @scenario = @json[:scenario][:columns]
              @returned_options = @scenario[0][:options]
            end

            it "returns options from the column's option list" do
              expect((@column.options.map { |option| option[:id] } | @returned_options.map { |option| option[:id] }).length).to be > 0
            end

            it 'returns max quantity two options' do
              expect(@returned_options.length).to eq 2
            end

            it 'returns unique options' do
              expect(@returned_options.uniq.length).to eq 2
            end

            describe 'with exclusions' do
              before do
                @exclusion = @column.exclusion_sets.create(options: [@option_new, @option])
                get :new, generator_id: @generator.id, format: :json
                @json = JSON.parse(response.body).with_indifferent_access
                @scenario = @json[:scenario][:columns]
                @returned_options = @scenario[0][:options]
              end

              # Because there aren't enough options available to fulfill the requested amount
              it 'will only return 1' do
                expect(@returned_options.length).to eq 1
              end
            end
          end

          describe 'and a min of 1' do
            before do
              @column.min = 1
              @column.max = 2
              @column.save
              get :new, generator_id: @generator.id, format: :json
              @json = JSON.parse(response.body).with_indifferent_access
              @scenario = @json[:scenario][:columns]
              @returned_options = @scenario[0][:options]
            end

            it "returns options from the column's option list" do
              expect((@column.options.map { |option| option[:id] } | @returned_options.map { |option| option[:id] }).length).to be > 0
            end

            it 'returns max quantity one or two options' do
              expect([1, 2].include? @returned_options.length).to eq true
            end

            it 'returns one or two options randomly' do
              returned_options = []
              50.times do
                get :new, generator_id: @generator.id, format: :json
                @json = JSON.parse(response.body).with_indifferent_access
                @scenario = @json[:scenario][:columns]
                returned_options << @scenario[0][:options].length
              end
              expect(returned_options.uniq.sort).to eq [1, 2]
            end

            describe 'with exclusions' do
              before do
                @exclusion = @column.exclusion_sets.create(options: [@option_new, @option])
              end

              # Because there aren't enough options available to fulfill the requested amount
              it 'will only return 1' do
                10.times do
                  get :new, generator_id: @generator.id, format: :json
                  @json = JSON.parse(response.body).with_indifferent_access
                  @scenario = @json[:scenario][:columns]
                  expect(@scenario[0][:options].length).to eq 1
                end
              end
            end
          end
        end
      end

      describe 'that has 5 options' do
        before do
          @options = create_list(:option, 4, column: @column)
        end

        describe 'and a max and min of two' do
          before do
            @column.max = @column.min = 2
            @column.save
          end

          describe 'with exclusions' do
            before do
              @exlcusion_options = [@options.last, @option]
              @exclusion = @column.exclusion_sets.create(options: @exlcusion_options)
            end

            it "won't return options that conflict" do
              10.times do
                get :new, generator_id: @generator.id, format: :json
                @json = JSON.parse(response.body).with_indifferent_access
                @scenario = @json[:scenario][:columns]
                options = @scenario[0][:options]
                expect(options.include?(@exlcusion_options[0]) && options.include?(@exlcusion_options[1])).to_not eq true
              end
            end

            it 'will return two options' do
              get :new, generator_id: @generator.id, format: :json
              @json = JSON.parse(response.body).with_indifferent_access
              @scenario = @json[:scenario][:columns]
              expect(@scenario[0][:options].length).to eq 2
            end
          end
        end
      end

      describe 'where an option picked has a child column' do
        before do
          @option_child_column = create(:column, min: 1, max: 1, parent_options: [@option])
          @option_child_column_option = create(:option, column: @option_child_column)
          @expected_column_result['columns'] << generate_expected_column_result(@option_child_column, [@option_child_column_option])
        end

        it 'returns a scenario with the child column' do
          get :new, generator_id: @generator.id, format: :json
          @json = JSON.parse(response.body).with_indifferent_access
          @scenario = @json[:scenario][:columns]
          expect(@scenario).to eq [@expected_column_result]
        end

        describe 'and then a column attached to the original column' do
          before do
            @child_column = create(:column, min: 1, max: 1, parent_columns: [@column])
            @child_column_option = create(:option, column: @child_column)
            @expected_column_result['columns'] << generate_expected_column_result(@child_column, [@child_column_option])
          end

          it 'returns a scenario with the child column' do
            get :new, generator_id: @generator.id, format: :json
            @json = JSON.parse(response.body).with_indifferent_access
            @scenario = @json[:scenario][:columns]
            expect(@scenario).to eq [@expected_column_result]
          end
        end
      end

      describe 'that has a child column' do
        before do
          @child_column = create(:column, min: 1, max: 1, parent_columns: [@column])
          @child_column_option = create(:option, column: @child_column)
          @expected_column_result['columns'] << generate_expected_column_result(@child_column, [@child_column_option])
        end

        it 'returns a scenario with the child column' do
          get :new, generator_id: @generator.id, format: :json
          @json = JSON.parse(response.body).with_indifferent_access
          @scenario = @json[:scenario][:columns]
          expect(@scenario).to eq [@expected_column_result]
        end
      end
    end
  end
end


text:
module Ershou
  module TopicsHelper
  end
end


text:
<?php

namespace spec\Sylius\Component\Inventory\Operator;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Sylius\Component\Inventory\Model\StockableInterface;

/**
 * @author Julien Janvier <j.janvier@gmail.com>
 */
class InsufficientStockExceptionSpec extends ObjectBehavior
{
    function let(StockableInterface $stockable)
    {
        $this->beConstructedWith($stockable, 10);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Component\Inventory\Operator\InsufficientStockException');
    }

    function it_is_an_uderflow_exception()
    {
        $this->shouldHaveType('\UnderflowException');
    }

    function it_returns_its_stockable()
    {
        $this->getStockable()->shouldHaveType('Sylius\Component\Inventory\Model\StockableInterface');
    }
}


text:
namespace app { namespace Experimental { namespace Cache { struct DiskCacheEntry; } } }

namespace app {
namespace Uno {
namespace Collections {

::uInterfaceType* IEnumerator__Experimental_Cache_DiskCacheEntry__typeof();

struct IEnumerator__Experimental_Cache_DiskCacheEntry
{
    ::app::Experimental::Cache::DiskCacheEntry*(*__fp_get_Current)(void*);

    static ::app::Experimental::Cache::DiskCacheEntry* Current(::uObject* __this) { return ((IEnumerator__Experimental_Cache_DiskCacheEntry*)uGetInterfacePtr(__this, IEnumerator__Experimental_Cache_DiskCacheEntry__typeof()))->__fp_get_Current((::uByte*)__this + (__this->__obj_type->TypeType == uTypeTypeStruct ? sizeof(::uObject) : 0)); }
};

}}}

#endif


text:
#import "EC2ModifySnapshotAttributeRequestMarshaller.h"

@implementation EC2ModifySnapshotAttributeRequestMarshaller

+(AmazonServiceRequest *)createRequest:(EC2ModifySnapshotAttributeRequest *)modifySnapshotAttributeRequest
{
    AmazonServiceRequest *request = [[EC2Request alloc] init];

    [request setParameterValue:@"ModifySnapshotAttribute"           forKey:@"Action"];
    [request setParameterValue:@"2011-12-15"   forKey:@"Version"];

    [request setDelegate:[modifySnapshotAttributeRequest delegate]];
    [request setCredentials:[modifySnapshotAttributeRequest credentials]];
    [request setEndpoint:[modifySnapshotAttributeRequest requestEndpoint]];
    [request setRequestTag:[modifySnapshotAttributeRequest requestTag]];

    if (modifySnapshotAttributeRequest != nil) {
        if (modifySnapshotAttributeRequest.snapshotId != nil) {
            [request setParameterValue:[NSString stringWithFormat:@"%@", modifySnapshotAttributeRequest.snapshotId] forKey:[NSString stringWithFormat:@"%@", @"SnapshotId"]];
        }
    }
    if (modifySnapshotAttributeRequest != nil) {
        if (modifySnapshotAttributeRequest.attribute != nil) {
            [request setParameterValue:[NSString stringWithFormat:@"%@", modifySnapshotAttributeRequest.attribute] forKey:[NSString stringWithFormat:@"%@", @"Attribute"]];
        }
    }
    if (modifySnapshotAttributeRequest != nil) {
        if (modifySnapshotAttributeRequest.operationType != nil) {
            [request setParameterValue:[NSString stringWithFormat:@"%@", modifySnapshotAttributeRequest.operationType] forKey:[NSString stringWithFormat:@"%@", @"OperationType"]];
        }
    }

    if (modifySnapshotAttributeRequest != nil) {
        int userIdsListIndex = 1;
        for (NSString *userIdsListValue in modifySnapshotAttributeRequest.userIds) {
            if (userIdsListValue != nil) {
                [request setParameterValue:[NSString stringWithFormat:@"%@", userIdsListValue] forKey:[NSString stringWithFormat:@"%@.%d", @"UserId", userIdsListIndex]];
            }

            userIdsListIndex++;
        }
    }

    if (modifySnapshotAttributeRequest != nil) {
        int groupNamesListIndex = 1;
        for (NSString *groupNamesListValue in modifySnapshotAttributeRequest.groupNames) {
            if (groupNamesListValue != nil) {
                [request setParameterValue:[NSString stringWithFormat:@"%@", groupNamesListValue] forKey:[NSString stringWithFormat:@"%@.%d", @"UserGroup", groupNamesListIndex]];
            }

            groupNamesListIndex++;
        }
    }
    if (modifySnapshotAttributeRequest != nil) {
        EC2CreateVolumePermissionModifications *createVolumePermission = modifySnapshotAttributeRequest.createVolumePermission;

        if (createVolumePermission != nil) {
            int addListIndex = 1;
            for (EC2CreateVolumePermission *addListValue in createVolumePermission.add) {
                if (addListValue != nil) {
                    if (addListValue.userId != nil) {
                        [request setParameterValue:[NSString stringWithFormat:@"%@", addListValue.userId] forKey:[NSString stringWithFormat:@"%@.%@.%d.%@", @"CreateVolumePermission", @"Add", addListIndex, @"UserId"]];
                    }
                }
                if (addListValue != nil) {
                    if (addListValue.group != nil) {
                        [request setParameterValue:[NSString stringWithFormat:@"%@", addListValue.group] forKey:[NSString stringWithFormat:@"%@.%@.%d.%@", @"CreateVolumePermission", @"Add", addListIndex, @"Group"]];
                    }
                }

                addListIndex++;
            }
        }

        if (createVolumePermission != nil) {
            int removeListIndex = 1;
            for (EC2CreateVolumePermission *removeListValue in createVolumePermission.remove) {
                if (removeListValue != nil) {
                    if (removeListValue.userId != nil) {
                        [request setParameterValue:[NSString stringWithFormat:@"%@", removeListValue.userId] forKey:[NSString stringWithFormat:@"%@.%@.%d.%@", @"CreateVolumePermission", @"Remove", removeListIndex, @"UserId"]];
                    }
                }
                if (removeListValue != nil) {
                    if (removeListValue.group != nil) {
                        [request setParameterValue:[NSString stringWithFormat:@"%@", removeListValue.group] forKey:[NSString stringWithFormat:@"%@.%@.%d.%@", @"CreateVolumePermission", @"Remove", removeListIndex, @"Group"]];
                    }
                }

                removeListIndex++;
            }
        }
    }

    return [request autorelease];
}

@end


text:
require "orbf/rules_engine"

class MapProjectToOrbfProject
  def initialize(project, indicators, category_combos, data_elements, engine_version = nil)
    @project = project
    @dhis2_indicators_by_id = indicators.index_by(&:id)
    @category_combos_by_id = category_combos ? category_combos.index_by(&:id) : {}
    @data_elements_by_id = data_elements ? data_elements.index_by(&:id) : {}
    @engine_version = engine_version || project.engine_version
  end

  def map
    Orbf::RulesEngine::Project.new(
      packages:                              map_packages(project.packages),
      payment_rules:                         map_payment_rules,
      dhis2_params:                          project.dhis_configuration,
      engine_version:                        @engine_version,
      default_category_combo_ext_id:         project.default_coc_reference,
      default_attribute_option_combo_ext_id: project.default_aoc_reference,
      calendar:                              project.calendar,
      contract_settings:                     project.contract_settings,
      read_through_deg:                      project.read_through_deg
    )
  end

  private

  attr_reader :project, :packages, :dhis2_indicators_by_id, :data_elements_by_id, :category_combos_by_id

  PACKAGE_KINDS = {
    "multi-groupset" => "subcontract"
  }.freeze

  def map_packages(packages)
    packages.map do |package|
      map_package(package)
    end
  end

  def map_package(package)
    @cache_package ||= {}
    from_cache = @cache_package[package]
    return from_cache if from_cache

    category_combo = category_combos_by_id[package.loop_over_combo_ext_id]

    @cache_package[package] = Orbf::RulesEngine::Package.new(
      code:                          package.code,
      kind:                          PACKAGE_KINDS[package.kind] || package.kind,
      frequency:                     package.frequency,
      main_org_unit_group_ext_ids:   package.main_entity_groups
                                        .map(&:organisation_unit_group_ext_ref).compact,

      target_org_unit_group_ext_ids: package.target_entity_groups
                                      .map(&:organisation_unit_group_ext_ref).compact,
      groupset_ext_id:               package.ogs_reference,
      matching_groupset_ext_ids:     package.groupsets_ext_refs,
      dataset_ext_ids:               package.package_states.map(&:ds_external_reference).compact,
      deg_ext_id:                    package.deg_external_reference,
      activities:                    map_activities(package.activities, package.states),
      rules:                         map_rules(package.rules),
      include_main_orgunit:          package.include_main_orgunit,
      loop_over_combo:               category_combo
    )
  end

  def map_activities(package_activities, package_states)
    package_activities.map do |activity|
      Orbf::RulesEngine::Activity.with(
        name:            activity.name,
        activity_code:   activity.code,
        activity_states: map_activity_states(activity.activity_states, package_states)
      )
    end
  end

  ACTIVITY_STATE_KIND = {
    "formula" => "constant"
  }.freeze

  def map_activity_states(activity_states, package_states)
    activity_states.select { |activity_state| package_states.include?(activity_state.state) }
                   .map do |activity_state|
      kind = ACTIVITY_STATE_KIND[activity_state.kind] || activity_state.kind
      formula = activity_state.formula ||
                dhis2_indicators_by_id[activity_state.external_reference]&.numerator
      ext_id = activity_state.external_reference
      if activity_state.kind_data_element_coc?
        # fake date_element_coc as indicator
        kind = "indicator"
        formula = '#{' + activity_state.external_reference + "}"
        ext_id = "inlined-" + ext_id
      end
      category_combo_ext_id = data_elements_by_id[activity_state.external_reference] ? data_elements_by_id[activity_state.external_reference].category_combo["id"] : nil

      Orbf::RulesEngine::ActivityState.with(
        state:                 activity_state.state.code,
        name:                  activity_state.name,
        formula:               formula,
        kind:                  kind,
        ext_id:                ext_id,
        origin:                activity_state.origin,
        category_combo_ext_id: category_combo_ext_id
      )
    end
  end

  RULE_KINDS = { "multi-entities" => "entities_aggregation" }.freeze

  def map_rules(rules)
    rules.map do |rule|
      map_rule(rule)
    end
  end

  def map_rule(rule)
    Orbf::RulesEngine::Rule.new(
      kind:            RULE_KINDS[rule.kind] || rule.kind,
      formulas:        map_formulas(rule.formulas),
      decision_tables: map_decision_tables(rule.decision_tables)
    )
  end

  def map_formulas(formulas)
    formulas.map do |formula|
      Orbf::RulesEngine::Formula.new(
        formula.code,
        formula.expression,
        formula.description,
        map_formula_mappings(formula)
      )
    end
  end

  def map_formula_mappings(formula)
    formula_mappings = {}
    formula_mappings[:frequency] = formula.frequency if formula.frequency
    formula_mappings[:exportable_formula_code] = formula.exportable_formula_code if formula.exportable_formula_code
    if formula.rule.activity_related_kind? && formula.formula_mappings.any?
      formula_mappings[:activity_mappings] = formula.formula_mappings
                                                    .each_with_object({}) do |mapping, hash|
        hash[mapping.activity.code] = mapping.external_reference
      end
    elsif !formula.rule.activity_kind? && formula.formula_mappings.size == 1
      formula_mappings[:single_mapping] = formula.formula_mappings.first.external_reference
    end
    formula_mappings
  end

  def map_decision_tables(decision_tables)
    decision_tables.map do |decision_table|
      Orbf::RulesEngine::DecisionTable.new(
        decision_table.content,
        start_period: decision_table.start_period,
        end_period:   decision_table.end_period
      )
    end
  end

  def map_payment_rules
    project.payment_rules.map do |payment_rule|
      Orbf::RulesEngine::PaymentRule.new(
        code:      payment_rule.code,
        frequency: payment_rule.frequency,
        packages:  map_packages(payment_rule.packages),
        rule:      map_rule(payment_rule.rule)
      )
    end
  end
end


text:
require_relative 'entity'

module Restconomic
  class AccountingYears < Entity
    def find(number)
      raise 'Invalid method'
    end
  end
end


text:
namespace net {

class X509Certificate;

// QuicServerInfo is an interface for fetching information about a QUIC server.
// This information may be stored on disk so does not include keys or other
// sensitive information. Primarily it's intended for caching the QUIC server's
// crypto config.
class NET_EXPORT_PRIVATE QuicServerInfo {
 public:
  QuicServerInfo(const QuicServerId& server_id);
  virtual ~QuicServerInfo();

  // Start will commence the lookup. This must be called before any other
  // methods. By opportunistically calling this early, it may be possible to
  // overlap this object's lookup and reduce latency.
  virtual void Start() = 0;

  // WaitForDataReady returns OK if the fetch of the requested data has
  // completed. Otherwise it returns ERR_IO_PENDING and will call |callback| on
  // the current thread when ready.
  //
  // Only a single callback can be outstanding at a given time and, in the
  // event that WaitForDataReady returns OK, it's the caller's responsibility
  // to delete |callback|.
  //
  // |callback| may be NULL, in which case ERR_IO_PENDING may still be returned
  // but, obviously, a callback will never be made.
  virtual int WaitForDataReady(const CompletionCallback& callback) = 0;

  // Reset's WaitForDataReady callback. This method shouldn't have any side
  // effects (could be called even if HttpCache doesn't exist).
  virtual void ResetWaitForDataReadyCallback() = 0;

  // Cancel's WaitForDataReady callback. |callback| passed in WaitForDataReady
  // will not be called.
  virtual void CancelWaitForDataReadyCallback() = 0;

  // Returns true if data is loaded from disk cache and ready (WaitForDataReady
  // doesn't have a pending callback).
  virtual bool IsDataReady() = 0;

  // Returns true if the object is ready to persist data, in other words, if
  // data is loaded from disk cache and ready and there are no pending writes.
  virtual bool IsReadyToPersist() = 0;

  // Persist allows for the server information to be updated for future users.
  // This is a fire and forget operation: the caller may drop its reference
  // from this object and the store operation will still complete. This can
  // only be called once WaitForDataReady has returned OK or called its
  // callback.
  virtual void Persist() = 0;

  // Called whenever an external cache reuses quic server config.
  virtual void OnExternalCacheHit() = 0;

  struct State {
    State();
    ~State();

    void Clear();

    // This class matches QuicClientCryptoConfig::CachedState.
    std::string server_config;         // A serialized handshake message.
    std::string source_address_token;  // An opaque proof of IP ownership.
    std::vector<std::string> certs;    // A list of certificates in leaf-first
                                       // order.
    std::string server_config_sig;     // A signature of |server_config_|.

   private:
    DISALLOW_COPY_AND_ASSIGN(State);
  };

  // Once the data is ready, it can be read using the following members. These
  // members can then be updated before calling |Persist|.
  const State& state() const;
  State* mutable_state();

  base::TimeTicks wait_for_data_start_time() const {
    return wait_for_data_start_time_;
  }

  base::TimeTicks wait_for_data_end_time() const {
    return wait_for_data_end_time_;
  }

 protected:
  // Parse parses pickled data and fills out the public member fields of this
  // object. It returns true iff the parse was successful. The public member
  // fields will be set to something sane in any case.
  bool Parse(const std::string& data);
  std::string Serialize();

  State state_;

  // Time when WaitForDataReady was called and when it has finished.
  base::TimeTicks wait_for_data_start_time_;
  base::TimeTicks wait_for_data_end_time_;

  // This is the QUIC server (hostname, port, is_https, privacy_mode) tuple for
  // which we restore the crypto_config.
  const QuicServerId server_id_;

 private:
  // ParseInner is a helper function for Parse.
  bool ParseInner(const std::string& data);

  // SerializeInner is a helper function for Serialize.
  std::string SerializeInner() const;

  DISALLOW_COPY_AND_ASSIGN(QuicServerInfo);
};

class NET_EXPORT_PRIVATE QuicServerInfoFactory {
 public:
  QuicServerInfoFactory() {}
  virtual ~QuicServerInfoFactory();

  // GetForServer returns a fresh, allocated QuicServerInfo for the given
  // |server_id| or NULL on failure.
  virtual QuicServerInfo* GetForServer(const QuicServerId& server_id) = 0;

  DISALLOW_COPY_AND_ASSIGN(QuicServerInfoFactory);
};

}  // namespace net

#endif  // NET_QUIC_CRYPTO_QUIC_SERVER_INFO_H_


text:
package requirementsfakes

import (
	"sync"

	"code.cloudfoundry.org/cli/cf/requirements"
)

type FakeRequirement struct {
	ExecuteStub        func() error
	executeMutex       sync.RWMutex
	executeArgsForCall []struct{}
	executeReturns     struct {
		result1 error
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakeRequirement) Execute() error {
	fake.executeMutex.Lock()
	fake.executeArgsForCall = append(fake.executeArgsForCall, struct{}{})
	fake.recordInvocation("Execute", []interface{}{})
	fake.executeMutex.Unlock()
	if fake.ExecuteStub != nil {
		return fake.ExecuteStub()
	} else {
		return fake.executeReturns.result1
	}
}

func (fake *FakeRequirement) ExecuteCallCount() int {
	fake.executeMutex.RLock()
	defer fake.executeMutex.RUnlock()
	return len(fake.executeArgsForCall)
}

func (fake *FakeRequirement) ExecuteReturns(result1 error) {
	fake.ExecuteStub = nil
	fake.executeReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeRequirement) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.executeMutex.RLock()
	defer fake.executeMutex.RUnlock()
	return fake.invocations
}

func (fake *FakeRequirement) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ requirements.Requirement = new(FakeRequirement)


text:
namespace fsm { namespace aux {

template< typename Derived >
struct event
    : base_event
{
 public:
    typedef base_event base_t;

 private:

#if defined(BOOST_NO_CXX11_SMART_PTR)

    virtual std::auto_ptr<base_event> do_clone() const
    {
        return std::auto_ptr<base_event>(
              new Derived(static_cast<Derived const&>(*this))
            );
    }

#else

    virtual std::unique_ptr<base_event> do_clone() const
    {
        return std::unique_ptr<base_event>(
              new Derived(static_cast<Derived const&>(*this))
            );
    }

#endif

};

}}

#endif // BOOST_FSM_EVENT_INCLUDED


text:
/**
 * This package (along with @see org.jboss.resteasy.test.cdi.generic) tests injection
 * with parameterized required types and/or parameterized bean types.
 *
 * @see org.jboss.resteasy.package-info.java
 */
package org.jboss.resteasy.cdi.generic;


text:
package com.ctrip.xpipe.exception;

import com.ctrip.xpipe.AbstractTest;
import com.ctrip.xpipe.api.codec.Codec;
import com.ctrip.xpipe.api.codec.GenericTypeReference;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

/**
 * @author wenchao.meng
 *
 * Aug 11, 2016
 */
public class ErrorMessageTest extends AbstractTest{

	public enum ERRORCODE{
		NET_EXCEPTION,
		DB_EXCEPTION
	}

	public static class TestErrorMessage extends ErrorMessage<ERRORCODE>{

		public TestErrorMessage(){}
		public TestErrorMessage(ERRORCODE errorType, String errorMessage){
			super(errorType, errorMessage);
		}

	}

	@Test
	public void testSubClass(){

		TestErrorMessage testErrorMessage = new TestErrorMessage(ERRORCODE.DB_EXCEPTION, "hello");
		String encode = Codec.DEFAULT.encode(testErrorMessage);

		TestErrorMessage decode = Codec.DEFAULT.decode(encode, TestErrorMessage.class);

		Assert.assertEquals(testErrorMessage, decode);

	}

	@Test
	public void testSerializa() throws JsonParseException, JsonMappingException, IOException{

		ErrorMessage<ERRORCODE> error = new ErrorMessage<ERRORCODE>(ERRORCODE.NET_EXCEPTION, "conntect refused");

		String result = Codec.DEFAULT.encode(error);
		logger.info("{}", result);

		ObjectMapper om = new ObjectMapper();
		ErrorMessage<ERRORCODE> desr = om.readValue(result, new TypeReference<ErrorMessage<ERRORCODE>>() {
		});
		Assert.assertEquals(error, desr);

		desr = Codec.DEFAULT.decode(result, new GenericTypeReference<ErrorMessage<ERRORCODE>>() {
		});
		Assert.assertEquals(error, desr);

		//test wrong message
		try{
			String wrong = "{\"errorType\":\"NET_EXCEPTION1\",\"errorMessage\":\"conntect refused\"}";
			desr = om.readValue(wrong, new TypeReference<ErrorMessage<ERRORCODE>>() {
			});
			Assert.fail();
		}catch(Exception e){
		}
	}

}


text:
class CreateOldRatings < ActiveRecord::Migration
  def up
    create_table :old_ratings do |t|
      # Warning: column order should match CSV import file (see below).
      t.integer  :icu_id
      t.integer  :rating, :games, limit: 2
      t.boolean  :full, default: false
    end

    # This is fast, despite the large amount of data, but it needs the column order to match and the DB user to have FILE privilege.
    execute "load data infile '#{Rails.root}/db/data/old_ratings.csv' into table old_ratings fields terminated by ','"

    add_index :old_ratings, :icu_id, unique: true
  end

  def down
    drop_table :old_ratings
  end
end