text:
package org.burstsort4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * An implementation of the funnelsort algorithm as described by Frigo,
 * Leisersen, Prokop, and Ramachandran in "Cache Oblivious Algorithms"
 * (the extended abstract, based on the thesis by Prokop).
 *
 * @author Nathan Fiedler
 */
public class Funnelsort {

    /** Size of inputs for which insertion sort should be used. */
    private static final int INSERTSORT_THRESHOLD = 21;

    private Funnelsort() {
    }

    /**
     * Sorts the set of strings using the "lazy" funnelsort algorithm as
     * described by Brodal, Fagerberg, and Vinther.
     *
     * @param  <T>      type of comparable to be sorted.
     * @param  strings  array of strings to be sorted.
     */
    public static <T extends Comparable<? super T>> void sort(T[] strings) {
        if (strings == null || strings.length < 2) {
            return;
        }
        sort(strings, 0, strings.length);
    }

    /**
     * Sorts the elements within the array starting at the offset and
     * ending at offset plus the count.
     *
     * @param  <T>      type of comparable to be sorted.
     * @param  strings  array containing elements to be sorted.
     * @param  offset   first position within array to be sorted.
     * @param  count    number of elements from offset to be sorted.
     */
    @SuppressWarnings("unchecked")
    private static <T extends Comparable<? super T>> void sort(T[] strings, int offset, int count) {
        if (count > INSERTSORT_THRESHOLD) {
            // Divide input into n^(1/3) arrays of size n^(2/3).
            final int num_blocks = Math.round((float) Math.cbrt((double) count));
            final int block_size = count / num_blocks;
            int mark = offset;
            for (int ii = 1; ii < num_blocks; ii++) {
                sort(strings, mark, block_size);
                mark += block_size;
            }
            int leftover = count - (mark - offset);
            if (leftover > 0) {
                sort(strings, mark, leftover);
            }

            // Merge the n^(1/3) sorted arrays using a k-merger.
            List<CircularBuffer<T>> inputs =
                    new ArrayList<CircularBuffer<T>>(num_blocks);
            mark = offset;
            for (int ii = 1; ii < num_blocks; ii++) {
                inputs.add(new CircularBuffer<T>(strings, mark, block_size, false));
                mark += block_size;
            }
            leftover = count - (mark - offset);
            if (leftover > 0) {
                inputs.add(new CircularBuffer<T>(strings, mark, leftover, false));
            }
            CircularBuffer<T> output = new CircularBuffer<T>(count);
            Kmerger<T> merger = MergerFactory.createMerger(inputs, output);
            merger.merge();
            output.drain(strings, offset);
        } else {
            // For small subarrays, delegate to insertion sort.
            Insertionsort.sort(strings, offset, offset + count - 1);
        }
    }

    /**
     * A Kmerger merges one or more input streams into a single output
     * stream, sorting the elements in the process.
     *
     * @param  <E>  type of elements being merged.
     */
    private static interface Kmerger<E extends Comparable<? super E>> {

        /**
         * Return the reference to this merger's output buffer.
         *
         * @return  output buffer for this merger, or null if none.
         */
        CircularBuffer<E> getOutput();

        /**
         * Merges k^3 elements from the inputs and writes them to the output.
         */
        void merge();
    }

    /**
     * MergerFactory creates instances of Kmerger based on the given inputs.
     */
    private static class MergerFactory {

        private MergerFactory() {
        }

        /**
         * Creates a new instance of Kmerger appropriate for the inputs.
         *
         * @param  inputs  streams of sorted input to be merged.
         * @param  output  buffer to which merged results are written.
         * @return  a Kmerger instance.
         */
        public static <T extends Comparable<? super T>> Kmerger<T> createMerger(
                List<CircularBuffer<T>> inputs,
                CircularBuffer<T> output) {
            int k = inputs.size();
            if (k == 1) {
                return new UnaryMerger<T>(inputs.get(0), output);
            } else if (k == 2) {
                CircularBuffer<T> lb = inputs.get(0);
                CircularBuffer<T> rb = inputs.get(1);
                return new BinaryMerger<T>(lb, rb, output);
            } else if (k == 3) {
                CircularBuffer<T> b1 = inputs.get(0);
                CircularBuffer<T> o1 = new CircularBuffer<T>(16);
                List<Kmerger<T>> mergers = new ArrayList<Kmerger<T>>(2);
                mergers.add(new UnaryMerger<T>(b1, o1));
                CircularBuffer<T> b2 = inputs.get(1);
                CircularBuffer<T> b3 = inputs.get(2);
                CircularBuffer<T> o2 = new CircularBuffer<T>(16);
                mergers.add(new BinaryMerger<T>(b2, b3, o2));
                return new BufferMerger<T>(output, mergers);
            } else {
                return new BufferMerger<T>(inputs, output);
            }
        }
    }

    /**
     * A BufferMerger divides up the input streams into k^(1/2) groups
     * each of size k^(1/2), creating additional mergers for those
     * groups, and ultimately merging their output into a single buffer.
     *
     * @param  <E>  the type of the buffer elements.
     */
    private static class BufferMerger<E extends Comparable<? super E>>
            implements Kmerger<E>, Observer {

        /** The number of times to invoke the R merger to merge inputs. */
        private final int k3half;
        /** The right k-merger for merging the k^(1/2) input streams. */
        private final Kmerger<E> R;
        /** The left k^(1/2) input streams each of size k^(1/2). */
        private final List<Kmerger<E>> Li;

        /**
         * Creates a new instance of BufferMerger.
         *
         * @param  inputs  streams of sorted input to be merged.
         * @param  output  buffer to which merged results are written.
         */
        BufferMerger(CircularBuffer<E> output,
                List<Kmerger<E>> mergers) {
            int k = mergers.size() ^ 2;
            k3half = Math.round((float) Math.sqrt((double) k * k * k));
            List<CircularBuffer<E>> buffers =
                    new ArrayList<CircularBuffer<E>>();
            for (Kmerger<E> merger : mergers) {
                buffers.add(merger.getOutput());
            }
            Li = mergers;
            R = MergerFactory.createMerger(buffers, output);
            output.addObserver(this);
        }

        /**
         * Creates a new instance of BufferMerger.
         *
         * @param  inputs  streams of sorted input to be merged.
         * @param  output  buffer to which merged results are written.
         */
        BufferMerger(List<CircularBuffer<E>> inputs,
                CircularBuffer<E> output) {
            int k = inputs.size();
            // Rounding up avoids creating excessive numbers of mergers.
            int kroot = Math.round((float) Math.sqrt((double) k));
            k3half = Math.round((float) Math.sqrt((double) k * k * k));
            int twok3half = 2 * k3half;
            int offset = 0;
            // Set up the list of buffers for the right side merger.
            List<CircularBuffer<E>> buffers =
                    new ArrayList<CircularBuffer<E>>();
            // Create mergers for the left inputs by dividing up the
            // inputs into roughly equal-sized sublists.
            Li = new ArrayList<Kmerger<E>>(kroot);
            for (int ii = 1; ii < kroot; ii++) {
                List<CircularBuffer<E>> li = inputs.subList(offset, offset + kroot);
                CircularBuffer<E> buffer = new CircularBuffer<E>(twok3half);
                buffers.add(buffer);
                Li.add(MergerFactory.createMerger(li, buffer));
                offset += kroot;
            }
            if (inputs.size() > offset) {
                List<CircularBuffer<E>> li = inputs.subList(offset, inputs.size());
                CircularBuffer<E> buffer = new CircularBuffer<E>(twok3half);
                buffers.add(buffer);
                Li.add(MergerFactory.createMerger(li, buffer));
            }
            R = MergerFactory.createMerger(buffers, output);
            output.addObserver(this);
        }

        @Override
        public CircularBuffer<E> getOutput() {
            return R.getOutput();
        }

        @Override
        public void merge() {
            // Invoke the R merger k^(3/2) times to generate our output.
            for (int ii = 0; ii < k3half; ii++) {
                // Make sure all of the buffers are at least half full.
                for (Kmerger<E> merger : Li) {
                    CircularBuffer<E> buf = merger.getOutput();
                    if (buf.size() < (buf.capacity() / 2)) {
                        merger.merge();
                    }
                }
                R.merge();
            }
        }

        @Override
        public void update(Observable o, Object arg) {
            merge();
        }
    }

    /**
     * A k-merger that merges two input buffers.
     */
    private static class BinaryMerger<E extends Comparable<? super E>>
            implements Kmerger<E>, Observer {

        /** The "left" input buffer. */
        private final CircularBuffer<E> leftBuffer;
        /** The "right" input buffer. */
        private final CircularBuffer<E> rightBuffer;
        /** The output buffer. */
        private final CircularBuffer<E> output;

        /**
         * Creates a new instance of BinaryMerger.
         *
         * @param  leftBuffer   the left input buffer.
         * @param  rightBuffer  the right input buffer.
         * @param  output       the output buffer.
         */
        BinaryMerger(CircularBuffer<E> leftBuffer,
                CircularBuffer<E> rightBuffer,
                CircularBuffer<E> output) {
            this.leftBuffer = leftBuffer;
            this.rightBuffer = rightBuffer;
            this.output = output;
            output.addObserver(this);
        }

        @Override
        public CircularBuffer<E> getOutput() {
            return output;
        }

        @Override
        @SuppressWarnings("unchecked")
        public void merge() {
            int count = output.remaining();
//            if (leftBuffer.isEmpty()) {
//                int n = Math.min(rightBuffer.size(), count);
//                if (n > 0) {
//                    rightBuffer.move(output, n);
//                }
//            } else if (rightBuffer.isEmpty()) {
//                int n = Math.min(leftBuffer.size(), count);
//                if (n > 0) {
//                    leftBuffer.move(output, n);
//                    count -= n;
//                }
//            } else {
                // Try to fill the output buffer with whatever input is
                // available, so long as neither input becomes empty.
                while (count > 0 && !leftBuffer.isEmpty() && !rightBuffer.isEmpty()) {
                    if (leftBuffer.peek().compareTo(rightBuffer.peek()) < 0) {
                        output.add(leftBuffer.remove());
                    } else {
                        output.add(rightBuffer.remove());
                    }
                    count--;
                }
//            }
//            // Output k^3 elements from the two buffers using a simple merge.
//            int count = output.remaining();
//            while (count > 0 && !leftBuffer.isEmpty() && !rightBuffer.isEmpty()) {
//                if (leftBuffer.peek().compareTo(rightBuffer.peek()) < 0) {
//                    output.add(leftBuffer.remove());
//                } else {
//                    output.add(rightBuffer.remove());
//                }
//                count--;
//            }
//            int n = Math.min(leftBuffer.size(), count);
//            if (n > 0) {
//                leftBuffer.move(output, n);
//                count -= n;
//            }
//            n = Math.min(rightBuffer.size(), count);
//            if (n > 0) {
//                rightBuffer.move(output, n);
//            }
        }

        @Override
        public void update(Observable o, Object arg) {
            merge();
        }
    }

    /**
     * A k-merger that streams a single input buffer to its output buffer.
     */
    private static class UnaryMerger<E extends Comparable<? super E>>
            implements Kmerger<E>, Observer {

        /** The input buffer. */
        private final CircularBuffer<E> input;
        /** The output buffer. */
        private final CircularBuffer<E> output;

        /**
         * Creates a new instance of UnaryMerger.
         *
         * @param  input   the input buffer.
         * @param  output  the output buffer.
         */
        UnaryMerger(CircularBuffer<E> input,
                CircularBuffer<E> output) {
            this.input = input;
            this.output = output;
            output.addObserver(this);
        }

        @Override
        public CircularBuffer<E> getOutput() {
            return output;
        }

        @Override
        public void merge() {
            // Fill the output buffer with whatever is available.
            int n = Math.min(input.size(), output.remaining());
            if (n > 0) {
                input.move(output, n);
            }
        }

        @Override
        public void update(Observable o, Object arg) {
            merge();
        }
    }
}


text:
import au.com.glassechidna.openddl.*;
import au.com.glassechidna.openddl.primitives.Reference;
import au.com.glassechidna.openddl.primitives.UnsignedInt64Structure;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class PropertiesSample
{
	private static String readFile(final String path) throws IOException
	{
		byte[] encoded = Files.readAllBytes(Paths.get(path));
		return new String(encoded, StandardCharsets.UTF_8);
	}

	private static void writeFile(final String pathName, final String string) throws IOException
	{
		final Path filePath = Paths.get(pathName);

		final File dir = new File(filePath.getParent().toString());
		dir.mkdirs();

		Files.write(filePath, string.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
	}

	public static void main(final String[] args)
	{
		final String inputFilename = "data/properties.oddl";
		final String outputFilename = "data/out/properties.oddl";

		GenericDecoder genericDecoder;

		try
		{
			genericDecoder = new GenericDecoder(readFile(inputFilename));

			final RootStructure rootStructure = genericDecoder.parse();
			System.out.println("Original:");
			System.out.println(rootStructure);

			final NodeStructure propTestStructure = (NodeStructure) rootStructure.getStructure(new Reference("$propTest"));

			propTestStructure.addInt8Property("TestInt8", (byte) 23, LiteralEncoding.DECIMAL);
			propTestStructure.addInt16Property("TestInt16", (short) -46, LiteralEncoding.DECIMAL);
			propTestStructure.addInt32Property("TestInt32", 1234567890, LiteralEncoding.DECIMAL);
			propTestStructure.addInt64Property("TestInt64", Long.MAX_VALUE, LiteralEncoding.DECIMAL);

			propTestStructure.addUnsignedInt8Property("UnsignedTestInt8", (byte) 23, LiteralEncoding.DECIMAL);
			propTestStructure.addUnsignedInt16Property("UnsignedTestInt16", 46, LiteralEncoding.DECIMAL);
			propTestStructure.addUnsignedInt32Property("UnsignedTestInt32", 1234567890, LiteralEncoding.DECIMAL);
			propTestStructure.addUnsignedInt64Property("UnsignedTestInt64", UnsignedInt64Structure.MAX, LiteralEncoding.DECIMAL);

			propTestStructure.addFloatProperty("FloatProperty", 1.2345f, LiteralEncoding.FLOATING_POINT);
			propTestStructure.addDoubleProperty("DoubleProperty", 6.1232143243242344, LiteralEncoding.FLOATING_POINT);

			propTestStructure.addStringProperty("StringProperty", "A string of some sort");
			propTestStructure.addReferenceProperty("ReferenceProperty", new Reference("$propTest"));
			propTestStructure.addTypeProperty("TypeProperty", PrimitiveType.INT64);

			rootStructure.validate();
			writeFile(outputFilename, rootStructure.toString());

			genericDecoder = new GenericDecoder(readFile(outputFilename));
			final RootStructure readOutputRootStructure = genericDecoder.parse();

			System.out.println("\nOutput (read from file):");
			System.out.println(readOutputRootStructure.toString());
		}
		catch (final OpenDDLException e)
		{
			e.printStackTrace();
		}
		catch (final IOException e)
		{
			e.printStackTrace();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Gpupo\Tests\Search\Paginator;

use Gpupo\Search\Paginator\Paginator;
use Gpupo\Search\Query\Keywords;
use Gpupo\Search\Query\Query;
use Gpupo\Search\Search;
use Gpupo\Tests\Search\TestCaseAbstract;

class PaginatorTest extends TestCaseAbstract
{
    protected function getResultCollection($word)
    {
        $keywords = new Keywords();
        $keywords->addKeyword($word);

        $query = new Query($keywords);
        $query->setIndex('produtoIndex');

        $collection = Search::getInstance()->findByQuery($query);

        return $collection;
    }

    public function testResultadosPossuiObjetoModeladoParaPaginacao()
    {
        if (!$this->hasHost()) {
            return $this->markTestSkipped();
        }

        $results = $this->getResultCollection('shampoo');
        $this->assertInstanceOf('\Gpupo\Search\Paginator\PaginableInterface', $results);
        $this->assertInstanceOf('\Gpupo\Search\Paginator\PaginatorInterface', $results->getPaginator());
        $this->assertInstanceOf('\Gpupo\Search\Paginator\Paginator', $results->getPaginator());

        return $results;
    }

    /**
     * @depends testResultadosPossuiObjetoModeladoParaPaginacao
     */
    public function testProcessaResultCollection($results)
    {
        $paginator = $results->getPaginator();
        $paginator->paginateResult($results, 1, 10);
        $this->assertEquals($results->getTotal(), $paginator->getTotalItemCount());
    }

    /**
     * @dataProvider dataProviderOffset
     */
    public function testMarcaAPaginaAtual($page, $resultados, $limit)
    {
        $paginator = new Paginator();
        $paginator->paginate($resultados, $page, $limit);
        $this->assertEquals($page, $paginator->getCurrentPageNumber());
    }
    /**
     * @dataProvider dataProviderOffset
     */
    public function testManipulaOffsetDeQuery($page, $resultados, $limit, $expectedValue)
    {
        $paginator = new Paginator();
        $paginator->paginate($resultados, $page, $limit);
        $this->assertEquals($expectedValue, $paginator->getOffset());
    }

    /**
     * @dataProvider dataProviderOffset
     */
    public function testManipulaLimitDeQuery($page, $resultados, $limit)
    {
        $paginator = new Paginator();
        $paginator->paginate($resultados, $page, $limit);
        $this->assertEquals($limit, $paginator->getItemNumberPerPage());
    }

    /**
     * @dataProvider dataProviderPaginas
     */
    public function testDivideResultadosEmPaginasDeAcordoComLimite($resultados,
        $page, $limit, $expectedPages)
    {
        $paginator = new Paginator();
        $this->assertInstanceOf('\Gpupo\Search\Paginator\PaginatorInterface', $paginator);
        $paginator->paginate($resultados, $page, $limit);

        $this->assertEquals($expectedPages, $paginator->getPagesCount());
    }

    /**
     * @dataProvider dataProviderRanges
     */
    public function testAcessoAoRangeDePaginasAproximadas($page, $resultados, $limit, array $rangeExpected)
    {
        $paginator = new Paginator();
        $paginator->paginate($resultados, $page, $limit);

        $data = $paginator->getPaginationData();

        $this->assertEquals($data['pagesInRange'], $rangeExpected);
    }

    /**
     * @dataProvider dataProviderCustomRanges
     */
    public function testPermiteCustomizacaoDoRangeDePaginasParaNavegacao($page, $resultados, $limit, $range, $rangeExpected)
    {
        $paginator = new Paginator();
        $paginator->paginate($resultados, $page, $limit);
        $paginator->setPageRange($range);

        $this->assertEquals($range, $paginator->getPageRange());
        $data = $paginator->getPaginationData();
        $this->assertEquals($rangeExpected, $data['pagesInRange']);
    }

    /**
     * @dataProvider dataProviderLongRanges
     */
    public function testAcessoAValoresDaPaginacao($page, $resultados, $limit)
    {
        $paginator = new Paginator();
        $paginator->paginate($resultados, $page, $limit);

        $list = [
            'last',
            'current',
            'numItemsPerPage',
            'first',
            'pageCount',
            'totalCount',
            'previous',
            'next',
            'pagesInRange',
            'firstPageInRange',
            'lastPageInRange',
        ];

        foreach ($list as $k) {
            $this->assertArrayHasKey($k, $paginator->getPaginationData());
        }
    }

    public function dataProviderRanges()
    {
        $array = $this->dataProviderLongRanges();

        $array[] = [2, 20,  10, [1,2]];

        return $array;
    }

    /**
     * @return array [page, resultados, limit]
     */
    public function dataProviderLongRanges()
    {
        return [

            [5, 100, 10, [3,4,5,6,7]],
            [6, 100, 10, [4,5,6,7,8]],
            [7, 100, 10, [5,6,7,8,9]],
            [8, 100, 10, [6,7,8,9,10]],
        ];
    }

    /**
     * @return array [page, resultados, limit, $range, expectedRange]
     */
    public function dataProviderCustomRanges()
    {
        return [
            [5, 100, 10, 3, [4,5,6]],
            [5, 100, 10, 7, [2,3,4,5,6,7,8]],
            [5, 100, 10, 9, [1,2,3,4,5,6,7,8,9]],
            [5, 100, 10, 11, [1,2,3,4,5,6,7,8,9,10]],
            [5, 100, 10, 21, [1,2,3,4,5,6,7,8,9,10]],
            [5, 100, 2, 11, [1,2,3,4,5,6,7,8,9,10,11]],
            [5, 100, 2, 13, [1,2,3,4,5,6,7,8,9,10,11,12,13]],
        ];
    }
    /**
     * @return array [resultados,page,limit,expectedPages]
     */
    public function dataProviderPaginas()
    {
        return [
            [100, 1, 10, 10],
            [10, 1, 10, 1],
            [99, 1, 10, 10],
            [101, 1, 10, 11],
            [11, 1, 10, 2],
            [11, 1, 2, 6],
        ];
    }

    public function dataProviderOffset()
    {
        //page,results,limit,expectedValue
        return [
            [
                3,10,2,4,
            ],
            [
                3,100,10,20,
            ],
            [
                4,100,10,30,
            ],
            [
                5,100,10,40,
            ],
            [
                9,99,10,80,
            ],
            [
                9,99,1,8,
            ],
            [
                99,99,1,98,
            ],
        ];
    }
}


text:
//metadoc Object copyright Steve Dekorte 2002
//metadoc Object license BSD revised

#ifndef OBJECT_STRUCT_DEFINED
#define OBJECT_STRUCT_DEFINED 1

#include "Common.h"
#include "PHash_struct.h"
#include "BStream.h"
#include "IoTag.h"
#include "Collector.h"

#ifdef __cplusplus
extern "C" {
#endif

// Shortcut for method definitons in C code
#define IO_METHOD(CLASS, NAME) IoObject * CLASS ## _ ## NAME (CLASS  *self, IoObject *locals, IoMessage *m)

typedef struct CollectorMarker IoObject;
//typedef struct IoObjectData IoObjectData;
/*
#ifndef CollectorObjectReference_DEFINED
	#define CollectorObjectReference_DEFINED 1
	typedef struct IoObjectData CollectorObjectReference;
#endif
*/

#define IOOBJECT_PERSISTENCE 1

struct IoObjectData
{
	unsigned int markerCount;

	union
	{
		void *ptr;
		double d;
		uint32_t ui32;
	} data; // 8 bytes (9+8 = 17)

	// 4*4 = 16 bytes (17+16 = 33)
	IoTag *tag;
	PHash *slots;
	List *listeners;
	IoObject **protos;

	unsigned int hasDoneLookup : 1;    // used to avoid slot lookup loops
	unsigned int isActivatable : 1;    // if true, upon activation, call activate slot
	unsigned int isDirty : 1;          // set to true when the object changes its storable state

	// optimizations

	unsigned int ownsSlots : 1;        // if true, io_free slots hash table when io_freeing object
	unsigned int isSymbol : 1;         // true if the object is a unqiue sequence - a symbol
	unsigned int isLocals : 1;         // true if the Object is a locals object
	unsigned int isReferenced : 1;     // 1 bit ref counter
	unsigned int sentWillFree : 1;     // 1 is sent willFree mes
	//unsigned int isPObject : 1;        // check before type tests?
};

#define IoObject_deref(self) ((IoObjectData *)(((CollectorMarker *)(self))->object))
#define IoObject_markerCount(self)          IoObject_deref(self)->markerCount
#define IoObject_markerCount_(self, v)      IoObject_deref(self)->markerCount = (v);
#define IoObject_incrementMarkerCount(self) IoObject_deref(self)->markerCount ++;
#define IoObject_decrementMarkerCount(self) IoObject_deref(self)->markerCount --;

#define IoObject_tag_(self, t) IoObject_deref(self)->tag = t;
#define IoObject_tag(self) (IoObject_deref(self)->tag)

#define IoObject_state(self) ((IoState *)(IoObject_tag(self)->state))
#define IOSTATE ((IoState *)(IoObject_tag(self)->state))
//#define IOSTATE IoObject_state(state)

#define IoObject_dataPointer(self)          IoObject_deref(self)->data.ptr
#define IoObject_setDataPointer_(self, v)   IoObject_deref(self)->data.ptr = (void *)(v);

#define IoObject_dataDouble(self)           IoObject_deref(self)->data.d
#define IoObject_setDataDouble_(self, v)    IoObject_deref(self)->data.d = (double)(v);

#define IoObject_dataUint32(self)           IoObject_deref(self)->data.ui32
#define IoObject_setDataUint32_(self, v)    IoObject_deref(self)->data.ui32 = (uint32_t)(v);

#define IoObject_isActivatable_(self, b)    IoObject_deref(self)->isActivatable = b;
#define IoObject_isActivatable(self)        (IoObject_deref(self)->isActivatable)

#define IoObject_ownsSlots_(self, b)        IoObject_deref(self)->ownsSlots = b;
#define IoObject_ownsSlots(self)            (IoObject_deref(self)->ownsSlots)

#define IoObject_slots_(self, v)            IoObject_deref(self)->slots = v;
#define IoObject_slots(self)                (IoObject_deref(self)->slots)

#define IoObject_protos_(self, v)        IoObject_deref(self)->protos = v;
#define IoObject_protos(self)            (IoObject_deref(self)->protos)

#define IoObject_firstProto(self)        IoObject_protos(self)[0]
#define IoObject_protoAt_(self, i)       IoObject_protos(self)[i]
#define IoObject_protoAtPut_(self, i, v) IoObject_protos(self)[i] = v;

#define IoObject_listeners_(self, v) IoObject_deref(self)->listeners = v;
#define IoObject_listeners(self)     (IoObject_deref(self)->listeners)

#define IoObject_hasDoneLookup_(self, v) IoObject_deref(self)->hasDoneLookup = v;
#define IoObject_hasDoneLookup(self)     (IoObject_deref(self)->hasDoneLookup)

#define IoObject_isSymbol_(self, v) IoObject_deref(self)->isSymbol = v;
#define IoObject_isSymbol(self)     (IoObject_deref(self)->isSymbol)

#ifdef IOOBJECT_PERSISTENCE
#define IoObject_isDirty_(self, v) IoObject_deref(self)->isDirty = v;
#define IoObject_isDirty(self)     (IoObject_deref(self)->isDirty)
#else
#define IoObject_isDirty_(self, v)
#define IoObject_isDirty(self) 0
#endif

#define IoObject_sentWillFree_(self, v) IoObject_deref(self)->sentWillFree = v;
#define IoObject_sentWillFree(self)     (IoObject_deref(self)->sentWillFree)

#define IoObject_isLocals_(self, v) IoObject_deref(self)->isLocals = v;
#define IoObject_isLocals(self)     (IoObject_deref(self)->isLocals)

#ifdef IO_BLOCK_LOCALS_RECYCLING
#define IoObject_isReferenced_(self, v) IoObject_deref(self)->isReferenced = v;
#define IoObject_isReferenced(self) (IoObject_deref(self)->isReferenced)
#else
#define IoObject_isReferenced_(self, v)
#define IoObject_isReferenced(self) 0
#endif

typedef IoObject *(IoMethodFunc)(IoObject *, IoObject *, IoObject *);

typedef struct
{
	const char *name;
	IoMethodFunc *func;
} IoMethodTable;

#ifdef __cplusplus
}
#endif
#endif


text:
package org.zmlx.hg4idea.util;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.zmlx.hg4idea.action.HgCommandResultNotifier;
import org.zmlx.hg4idea.execution.HgCommandResult;

import javax.swing.event.HyperlinkEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class HgErrorUtil {

  private static final Logger LOG = Logger.getInstance(HgErrorUtil.class.getName());

  private static final String SETTINGS_LINK = "settings";
  public static final String MAPPING_ERROR_MESSAGE =
    "Please, ensure that your project base dir is hg root directory or specify full repository path in  directory mappings panel.";
  private static final String MERGE_WITH_ANCESTOR_ERROR = "merging with a working directory ancestor has no effect";
  private static final String NOTHING_TO_REBASE_WARNING = "nothing to rebase";

  private HgErrorUtil() {
  }

  public static boolean isAbort(@Nullable HgCommandResult result) {
    return result == null || getAbortLine(result) != null;
  }

  @Nullable
  private static String getAbortLine(@NotNull HgCommandResult result) {
    final List<String> errorLines = result.getErrorLines();
    return ContainerUtil.find(errorLines, s -> isAbortLine(s));
  }

  public static boolean isAncestorMergeError(@Nullable HgCommandResult result) {
    if (result == null) return false;
    String errorLine = getAbortLine(result);
    return errorLine != null && StringUtil.contains(errorLine, MERGE_WITH_ANCESTOR_ERROR);
  }

  public static boolean isNothingToRebase(@Nullable HgCommandResult result) {
    if (result == null) return false;
    return ContainerUtil.exists(result.getOutputLines(), s -> StringUtil.contains(s, NOTHING_TO_REBASE_WARNING));
  }

  public static boolean isAuthorizationError(@Nullable HgCommandResult result) {
    if (result == null) {
      return false;
    }
    String line = getLastErrorLine(result);
    return isAuthorizationError(line);
  }

  @Nullable
  private static String getLastErrorLine(@Nullable HgCommandResult result) {
    if (result == null) {
      return null;
    }
    final List<String> errorLines = result.getErrorLines();
    if (errorLines.isEmpty()) {
      return null;
    }
    return errorLines.get(errorLines.size() - 1);
  }

  //unresolved conflict errors included
  public static boolean hasErrorsInCommandExecution(@Nullable HgCommandResult result) {
    return isAbort(result) || result.getExitValue() != 0;
  }

  //todo should be modified and/or merged with HgErrorHandler
  public static boolean isCommandExecutionFailed(@Nullable HgCommandResult result) {
    return isAbort(result) || result.getExitValue() > 1;
  }

  public static boolean hasAuthorizationInDestinationPath(@Nullable String destinationPath) {
    if (StringUtil.isEmptyOrSpaces(destinationPath)) {
      return false;
    }
    return HgUtil.URL_WITH_PASSWORD.matcher(destinationPath).matches();
  }

  @NotNull
  public static NotificationListener getMappingErrorNotificationListener(@NotNull final Project project) {
    return new NotificationListener.Adapter() {
      @Override
      protected void hyperlinkActivated(@NotNull Notification notification,
                                        @NotNull HyperlinkEvent e) {
        if (SETTINGS_LINK.equals(e.getDescription())) {
          ShowSettingsUtil.getInstance()
            .showSettingsDialog(project, VcsBundle.message("version.control.main.configurable.name"));
        }
      }
    };
  }

  public static boolean isUnknownEncodingError(@Nullable HgCommandResult result) {
    if (result == null) {
      return false;
    }
    List<String> errorLines = result.getErrorLines();
    if (errorLines.isEmpty()) {
      return false;
    }
    String line = errorLines.get(0);
    return !StringUtil.isEmptyOrSpaces(line) && (line.contains("abort") && line.contains("unknown encoding"));
  }

  //during update  or revert action with  uncommitted merges/changes
  public static boolean hasUncommittedChangesConflict(@Nullable HgCommandResult result) {
    if (result == null) {
      return false;
    }
    // error messages from mercurial after update command failed: "abort: outstanding uncommitted merges", "abort: uncommitted changes";
    //after revert command failed: abort: "uncommitted merge"
    final Pattern UNCOMMITTED_PATTERN = Pattern.compile(".*abort.*uncommitted\\s*(change|merge).*", Pattern.DOTALL);
    Matcher matcher = UNCOMMITTED_PATTERN.matcher(result.getRawError());
    return matcher.matches();
  }

  public static boolean isAuthorizationError(String line) {
    return !StringUtil.isEmptyOrSpaces(line) && (line.contains("authorization required") || line.contains("authorization failed"));
  }

  public static boolean isAbortLine(String line) {
    return !StringUtil.isEmptyOrSpaces(line) && line.trim().startsWith("abort:");
  }

  public static void handleException(@Nullable Project project, @NotNull Exception e) {
    handleException(project, "Error", e);
  }

  public static void handleException(@Nullable Project project, @NotNull String title, @NotNull Exception e) {
    LOG.info(e);
    new HgCommandResultNotifier(project).notifyError(null, title, e.getMessage());
  }

  public static void markDirtyAndHandleErrors(Project project, VirtualFile repository) {
    try {
      HgUtil.markDirectoryDirty(project, repository);
    }
    catch (InvocationTargetException | InterruptedException e) {
      handleException(project, e);
    }
  }
}


text:
FROM python:2.7.11-alpine

RUN apk add --no-cache openssl ca-certificates

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY requirements.txt /usr/src/app/
RUN pip install --no-cache-dir -r requirements.txt

COPY . /usr/src/app

ENTRYPOINT [ "python", "./acmedns.py" ]


text:
package hex.psvm.psvm;

import hex.DataInfo;
import water.*;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.NewChunk;
import water.fvec.Vec;
import water.util.Log;

/**
 * Implementation of ICF based on https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/34638.pdf
 *
 * This implementation is based on and takes clues from the reference PSVM implementation in C++:
 *    https://code.google.com/archive/p/psvm/source/default/source
 *    original code: Copyright 2007 Google Inc., Apache License, Version 2.0
 */
public class IncompleteCholeskyFactorization {

  public static Frame icf(DataInfo di, Kernel kernel, int n, double threshold) {
    return icf(di._adaptedFrame, di, kernel, n, threshold);
  }

  static Frame icf(Frame frame, String response, Kernel kernel, int n, double threshold) {
    Frame adapted = new Frame(frame);
    try {
      adapted.add(response, adapted.remove(response)); // make response to the last column
      adapted.add("two_norm_sq", adapted.anyVec().makeZero()); // (L2 norm)^2; initialized 0 - will be calculated later - treated as second response for the lack of a better place

      DataInfo di = new DataInfo(adapted, null, 2, true, DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false, null)
              .disableIntercept();

      return icf(di, kernel, n, threshold);
    } finally {
      Vec tns = adapted.vec("two_norm_sq");
      if (tns != null) {
        tns.remove();
      }
    }
  }

  private static Frame icf(Frame frame, DataInfo di, Kernel kernel, int n, double threshold) {
    Frame icf = new Frame();
    Frame workspace = new Frame();
    try {
      Vec diag1 = new InitICF(di, kernel).doAll(Vec.T_NUM, frame).outputFrame().anyVec(); // diag1: the diagonal part of Q (the kernel matrix diagonal)
      Vec diag2 = frame.anyVec().makeZero(); // diag2: the quadratic sum of a row of the ICF matrix
      Vec pivot_selected = frame.anyVec().makeZero();

      workspace.add("pivot_selected", pivot_selected);
      workspace.add("diag1", diag1);
      workspace.add("diag2", diag2);

      for (int i = 0; i < n; i++) {
        FindPivot fp = new FindPivot(frame, di).doAll(workspace);
        if (fp._trace < threshold) {
          Log.info("ICF finished before full rank was reached in iteration " + i +
                  ". Trace value = " + fp._trace + " (convergence threshold = " + threshold + ").");
          break;
        }
        Log.info("ICF Iteration " + i + ": trace: " + fp._trace);

        Vec newCol = frame.anyVec().makeZero();
        icf.add("C" + (i + 1), newCol);

        UpdatePivot up = new UpdatePivot(icf, pivot_selected, fp).doOnRemote();

        new CalculateColumn(frame, di, kernel, icf, fp._pivot_sample, up._header_row).doAll(pivot_selected, diag2, newCol);
      }
    } finally {
      workspace.delete();
    }
    return icf;
  }

  /**
   * Calculate a new column of the ICF matrix
   */
  private static class CalculateColumn extends MRTask<CalculateColumn> {
    // IN
    Frame _full_frame;
    DataInfo _dinfo;
    Kernel _kernel;
    double[] _header_row;
    DataInfo.Row _pivot_sample;
    Frame _icf;

    private CalculateColumn(Frame frame, DataInfo dinfo, Kernel kernel,
                            Frame icf,
                            DataInfo.Row pivotSample, double[] headerRow) {
      _full_frame = frame;
      _dinfo = dinfo;
      _kernel = kernel;
      _icf = icf;
      _pivot_sample = pivotSample;
      _header_row = headerRow;
    }

    @Override
    public void map(Chunk pivot_selected, Chunk diag2, Chunk newColChunk) {
      Chunk[] icf = getLocalChunks(_icf, pivot_selected.start());
      Chunk[] frameChunks = getLocalChunks(_full_frame, pivot_selected.start());

      double[] newColData = MemoryManager.malloc8d(newColChunk._len);
      boolean[] pivotSelected = MemoryManager.mallocZ(newColChunk._len);
      for (int i = 0; i < newColData.length; i++) {
        pivotSelected[i] = pivot_selected.at8(i) != 0;
        newColData[i] = pivotSelected[i] ? newColChunk.atd(i) : 0;
      }

      for (int k = 0; k < icf.length - 1; k++) {
        for (int i = 0; i < newColChunk._len; i++) {
          if (pivotSelected[i])
            continue;
          newColData[i] -= icf[k].atd(i) * _header_row[k];
        }
      }
      DataInfo.Row row = _dinfo.newDenseRow();
      for (int i = 0; i < newColChunk._len; i++) {
        if (pivotSelected[i])
          continue;
        _dinfo.extractDenseRow(frameChunks, i, row);
        newColData[i] += _kernel.calcKernelWithLabel(row, _pivot_sample);
      }
      for (int i = 0; i < newColChunk._len; i++) {
        if (pivotSelected[i])
          continue;
        newColData[i] /= _header_row[_header_row.length - 1];
      }

      // Updated newCol chunk and calculate diag2
      for (int i = 0; i < newColData.length; i++) {
        double v = newColData[i];
        newColChunk.set(i, v);
        diag2.set(i, diag2.atd(i) + (v * v));
      }
    }
  }

  private static class InitICF extends MRTask<InitICF> {
    // IN
    DataInfo _dinfo;
    Kernel _kernel;

    InitICF(DataInfo dinfo, Kernel kernel) {
      _dinfo = dinfo;
      _kernel = kernel;
    }

    @Override
    public void map(Chunk[] cs, NewChunk nc) {
      DataInfo.Row row = _dinfo.newDenseRow();
      Chunk two_norm_sq = cs[cs.length - 1];

      for (int r = 0; r < cs[0]._len; r++) {
        _dinfo.extractDenseRow(cs, r, row);
        final double tns = row.twoNormSq();
        row.response[1] = tns;
        two_norm_sq.set(r, tns);
        double diag1val = _kernel.calcKernel(row, row);
        nc.addNum(diag1val);
      }
    }

  }

  /**
   * Find new pivot and calculate a trace of Q
   */
  private static class FindPivot extends MRTask<FindPivot> {
    // IN
    Frame _full_frame;
    DataInfo _dinfo;

    // OUT
    long _index = -1;
    double _value;
    DataInfo.Row _pivot_sample;
    double _trace;

    FindPivot(Frame frame, DataInfo dinfo) {
      _full_frame = frame;
      _dinfo = dinfo;
    }

    @Override
    public void map(Chunk pivot_selected, Chunk diag1, Chunk diag2) {
      if (diag1._len == 0)
        return;
      int idx = -1;
      _value = -Double.MAX_VALUE;
      _trace = 0;
      for (int i = 0; i < diag1._len; i++) {
        if (pivot_selected.at8(i) != 0)
          continue;
        double diff = diag1.atd(i) - diag2.atd(i);
        _trace += diff;
        if (diff > _value) {
          _value = diff;
          idx = i;
        }
      }
      if (idx != -1) {
        _index = diag1.start() + idx;
        _pivot_sample = extractLocalRow(_index);
      }
    }

    @Override
    public void reduce(FindPivot mrt) {
      _trace += mrt._trace;
      if ((_index == -1) || ((mrt._index != -1) && (mrt._value > _value))) {
        _index = mrt._index;
        _value = mrt._value;
        _pivot_sample = mrt._pivot_sample;
      }
    }

    private DataInfo.Row extractLocalRow(long idx) {
      Chunk[] chks = getLocalChunks(_full_frame, idx);
      DataInfo.Row row = _dinfo.newDenseRow();
      int rid = (int) (idx - chks[0].start());
      _dinfo.extractDenseRow(chks, rid, row);
      return row;
    }

  }

  /**
   * Update pivot on remote node and return the corresponding row of the ICF matrix
   */
  private static class UpdatePivot extends DTask<UpdatePivot> {
    // IN
    Frame _icf;
    Vec _pivot_selected;
    long _index;
    double _value;

    // OUT
    double[] _header_row;

    UpdatePivot(Frame icf, Vec pivotSelected, FindPivot fp) {
      _icf = icf;
      _pivot_selected = pivotSelected;
      _index = fp._index;
      _value = Math.sqrt(fp._value);
    }

    @Override
    public void compute2() {
      // using global Vec API on the home node of the underlying chunks - will be fast
      _icf.vecs()[_icf.numCols() - 1].set(_index, _value);
      _pivot_selected.set(_index, 1);

      Chunk[] chks = getLocalChunks(_icf, _index);
      int row = (int) (_index - chks[0].start());
      _header_row = new double[chks.length];
      for (int i = 0; i < chks.length; i++) {
        _header_row[i] = chks[i].atd(row);
      }
      tryComplete();
    }

    UpdatePivot doOnRemote() {
      Vec newCol = _icf.lastVec();
      assert newCol.isConst();

      H2ONode node = newCol.chunkKey(newCol.elem2ChunkIdx(_index)).home_node();
      return new RPC<>(node, this).call().get();
    }

  }

  private static Chunk[] getLocalChunks(Frame f, long rowId) {
    if (f.numCols() == 0)
      return new Chunk[0];
    Vec[] vecs = f.vecs();
    Chunk[] chks = new Chunk[vecs.length];
    int cidx = vecs[0].elem2ChunkIdx(rowId);
    for (int i = 0; i < chks.length; i++) {
      assert vecs[i].chunkKey(cidx).home();
      chks[i] = vecs[i].chunkForChunkIdx(cidx);
    }
    return chks;
  }

}


text:
package org.apache.druid.metadata;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Inject;
import org.apache.druid.audit.AuditManager;
import org.apache.druid.java.util.common.lifecycle.Lifecycle;
import org.apache.druid.server.audit.SQLAuditManager;
import org.skife.jdbi.v2.IDBI;

/**
 */
public class SQLMetadataRuleManagerProvider implements MetadataRuleManagerProvider
{
  private final ObjectMapper jsonMapper;
  private final MetadataRuleManagerConfig config;
  private final MetadataStorageTablesConfig dbTables;
  private final SQLMetadataConnector connector;
  private final Lifecycle lifecycle;
  private final IDBI dbi;
  private final AuditManager auditManager;

  @Inject
  public SQLMetadataRuleManagerProvider(
      ObjectMapper jsonMapper,
      MetadataRuleManagerConfig config,
      MetadataStorageTablesConfig dbTables,
      SQLMetadataConnector connector,
      Lifecycle lifecycle,
      SQLAuditManager auditManager
  )
  {
    this.jsonMapper = jsonMapper;
    this.config = config;
    this.dbTables = dbTables;
    this.connector = connector;
    this.dbi = connector.getDBI();
    this.lifecycle = lifecycle;
    this.auditManager = auditManager;
  }

  @Override
  public SQLMetadataRuleManager get()
  {
    try {
      lifecycle.addMaybeStartHandler(
          new Lifecycle.Handler()
          {
            @Override
            public void start()
            {
              connector.createRulesTable();
              SQLMetadataRuleManager.createDefaultRule(
                  dbi,
                  dbTables.getRulesTable(),
                  config.getDefaultRule(),
                  jsonMapper
              );
            }

            @Override
            public void stop()
            {

            }
          }
      );
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }

    return new SQLMetadataRuleManager(jsonMapper, config, dbTables, connector, auditManager);
  }
}


text:
package iso20022

// Details on the quantity, account and other related information involved in a transaction.
type QuantityAndAccount57 struct {

	// Quantity of financial instrument effectively settled.
	SettledQuantity *Quantity10Choice `xml:"SttldQty"`

	// Quantity of financial instrument previously settled.
	PreviouslySettledQuantity *FinancialInstrumentQuantity15Choice `xml:"PrevslySttldQty,omitempty"`

	// Quantity of financial instrument remaining to be settled.
	RemainingToBeSettledQuantity *FinancialInstrumentQuantity15Choice `xml:"RmngToBeSttldQty,omitempty"`

	// Amount of money previously settled.
	PreviouslySettledAmount *AmountAndDirection57 `xml:"PrevslySttldAmt,omitempty"`

	// Amount of money remaining to be settled.
	RemainingToBeSettledAmount *AmountAndDirection57 `xml:"RmngToBeSttldAmt,omitempty"`

	// Denomination of the security to be received or delivered.
	DenominationChoice *RestrictedFINXMax210Text `xml:"DnmtnChc,omitempty"`

	// Party that legally owns the account.
	AccountOwner *PartyIdentification119 `xml:"AcctOwnr,omitempty"`

	// Account to or from which a securities entry is made.
	SafekeepingAccount *SecuritiesAccount27 `xml:"SfkpgAcct"`

	// Account to or from which a cash entry is made.
	CashAccount *CashAccountIdentification6Choice `xml:"CshAcct,omitempty"`

	// Breakdown of a quantity into lots such as tax lots, instrument series, etc.
	QuantityBreakdown []*QuantityBreakdown44 `xml:"QtyBrkdwn,omitempty"`

	// Place where the securities are safe-kept, physically or notionally.  This place can be, for example, a local custodian, a Central Securities Depository (CSD) or an International Central Securities Depository (ICSD).
	SafekeepingPlace *SafeKeepingPlace2 `xml:"SfkpgPlc,omitempty"`
}

func (q *QuantityAndAccount57) AddSettledQuantity() *Quantity10Choice {
	q.SettledQuantity = new(Quantity10Choice)
	return q.SettledQuantity
}

func (q *QuantityAndAccount57) AddPreviouslySettledQuantity() *FinancialInstrumentQuantity15Choice {
	q.PreviouslySettledQuantity = new(FinancialInstrumentQuantity15Choice)
	return q.PreviouslySettledQuantity
}

func (q *QuantityAndAccount57) AddRemainingToBeSettledQuantity() *FinancialInstrumentQuantity15Choice {
	q.RemainingToBeSettledQuantity = new(FinancialInstrumentQuantity15Choice)
	return q.RemainingToBeSettledQuantity
}

func (q *QuantityAndAccount57) AddPreviouslySettledAmount() *AmountAndDirection57 {
	q.PreviouslySettledAmount = new(AmountAndDirection57)
	return q.PreviouslySettledAmount
}

func (q *QuantityAndAccount57) AddRemainingToBeSettledAmount() *AmountAndDirection57 {
	q.RemainingToBeSettledAmount = new(AmountAndDirection57)
	return q.RemainingToBeSettledAmount
}

func (q *QuantityAndAccount57) SetDenominationChoice(value string) {
	q.DenominationChoice = (*RestrictedFINXMax210Text)(&value)
}

func (q *QuantityAndAccount57) AddAccountOwner() *PartyIdentification119 {
	q.AccountOwner = new(PartyIdentification119)
	return q.AccountOwner
}

func (q *QuantityAndAccount57) AddSafekeepingAccount() *SecuritiesAccount27 {
	q.SafekeepingAccount = new(SecuritiesAccount27)
	return q.SafekeepingAccount
}

func (q *QuantityAndAccount57) AddCashAccount() *CashAccountIdentification6Choice {
	q.CashAccount = new(CashAccountIdentification6Choice)
	return q.CashAccount
}

func (q *QuantityAndAccount57) AddQuantityBreakdown() *QuantityBreakdown44 {
	newValue := new(QuantityBreakdown44)
	q.QuantityBreakdown = append(q.QuantityBreakdown, newValue)
	return newValue
}

func (q *QuantityAndAccount57) AddSafekeepingPlace() *SafeKeepingPlace2 {
	q.SafekeepingPlace = new(SafeKeepingPlace2)
	return q.SafekeepingPlace
}