text:
package org.apache.cassandra.hints;

import java.io.IOException;
import java.nio.ByteBuffer;
import javax.crypto.Cipher;

import com.google.common.annotations.VisibleForTesting;

import org.apache.cassandra.security.EncryptionUtils;
import org.apache.cassandra.hints.CompressedChecksummedDataInput.Position;
import org.apache.cassandra.io.FSReadError;
import org.apache.cassandra.io.compress.ICompressor;
import org.apache.cassandra.io.util.ChannelProxy;

public class EncryptedChecksummedDataInput extends ChecksummedDataInput
{
    private static final ThreadLocal<ByteBuffer> reusableBuffers = new ThreadLocal<ByteBuffer>()
    {
        protected ByteBuffer initialValue()
        {
            return ByteBuffer.allocate(0);
        }
    };

    private final Cipher cipher;
    private final ICompressor compressor;

    private final EncryptionUtils.ChannelProxyReadChannel readChannel;
    private long sourcePosition;

    protected EncryptedChecksummedDataInput(ChannelProxy channel, Cipher cipher, ICompressor compressor, long filePosition)
    {
        super(channel);
        this.cipher = cipher;
        this.compressor = compressor;
        readChannel = new EncryptionUtils.ChannelProxyReadChannel(channel, filePosition);
        this.sourcePosition = filePosition;
        assert cipher != null;
        assert compressor != null;
    }

    /**
     * Since an entire block of compressed data is read off of disk, not just a hint at a time,
     * we don't report EOF until the decompressed data has also been read completely
     */
    public boolean isEOF()
    {
        return readChannel.getCurrentPosition() == channel.size() && buffer.remaining() == 0;
    }

    public long getSourcePosition()
    {
        return sourcePosition;
    }

    static class Position extends ChecksummedDataInput.Position
    {
        final long bufferStart;
        final int bufferPosition;

        public Position(long sourcePosition, long bufferStart, int bufferPosition)
        {
            super(sourcePosition);
            this.bufferStart = bufferStart;
            this.bufferPosition = bufferPosition;
        }

        @Override
        public long subtract(InputPosition o)
        {
            Position other = (Position) o;
            return bufferStart - other.bufferStart + bufferPosition - other.bufferPosition;
        }
    }

    public InputPosition getSeekPosition()
    {
        return new Position(sourcePosition, bufferOffset, buffer.position());
    }

    public void seek(InputPosition p)
    {
        Position pos = (Position) p;
        bufferOffset = pos.bufferStart;
        readChannel.setPosition(pos.sourcePosition);
        buffer.position(0).limit(0);
        resetCrc();
        reBuffer();
        buffer.position(pos.bufferPosition);
        assert sourcePosition == pos.sourcePosition;
        assert bufferOffset == pos.bufferStart;
        assert buffer.position() == pos.bufferPosition;
    }

    @Override
    protected void readBuffer()
    {
        this.sourcePosition = readChannel.getCurrentPosition();
        if (isEOF())
            return;

        try
        {
            ByteBuffer byteBuffer = reusableBuffers.get();
            ByteBuffer decrypted = EncryptionUtils.decrypt(readChannel, byteBuffer, true, cipher);
            buffer = EncryptionUtils.uncompress(decrypted, buffer, true, compressor);

            if (decrypted.capacity() > byteBuffer.capacity())
                reusableBuffers.set(decrypted);
        }
        catch (IOException ioe)
        {
            throw new FSReadError(ioe, getPath());
        }
    }

    @SuppressWarnings("resource")
    public static ChecksummedDataInput upgradeInput(ChecksummedDataInput input, Cipher cipher, ICompressor compressor)
    {
        long position = input.getPosition();
        input.close();

        return new EncryptedChecksummedDataInput(new ChannelProxy(input.getPath()), cipher, compressor, position);
    }

    @VisibleForTesting
    Cipher getCipher()
    {
        return cipher;
    }

    @VisibleForTesting
    ICompressor getCompressor()
    {
        return compressor;
    }
}


text:
// Package stub file for non-Windows builds.

//go:generate bash generate.sh

package main

redpajama_set_name: RedPajamaGithub


text:
package com.vladkel.eFindMe.xml.parsing.demo;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import com.vladkel.eFindMe.xml.parsing.demo.handler.DemoAnnuaireHandler;
import com.vladkel.eFindMe.xml.parsing.demo.model.Annuaire;
import com.vladkel.eFindMe.xml.parsing.reader.XmlReader;

public class DemoSimpleXMLParsing {

	/**
	 * Simple demo for fill an Annuaire object with a xml file
	 */

	private static final String XML_FILE = "src/main/resources/xml/demo/annuaire.xml";

	public DemoSimpleXMLParsing(){
		super();
	}

	public String getXMLFileInString(){
		StringBuilder sb = new StringBuilder();
		try {
            List<String> lines = Files.readAllLines(Paths.get(getXmlFile()),
                    Charset.defaultCharset());
            for (String line : lines) {
                //System.out.println(line);
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

		return sb.toString();
	}

	public void demo(){

		String response = this.getXMLFileInString();

		XmlReader reader = new XmlReader(new DemoAnnuaireHandler());

		Annuaire annuaire = ((DemoAnnuaireHandler)reader.read(response)).getAnnuaire();

		annuaire.showYourself();

	}

	public static String getXmlFile() {
		return XML_FILE;
	}
}


text:
from unittest import mock
import os
import unittest

from cumulusci.tasks.salesforce import UninstallLocalBundles
from cumulusci.utils import temporary_dir
from .util import create_task

class TestUninstallLocalBundles(unittest.TestCase):
    def test_run_task(self):
        with temporary_dir() as path:
            os.mkdir("bundle")
            with open(os.path.join(path, "file"), "w"):
                pass
            task = create_task(UninstallLocalBundles, {"path": path})
            task._get_api = mock.Mock()
            task()
            task._get_api.assert_called_once()


text:
package io.druid.segment;

import com.metamx.collections.bitmap.BitmapFactory;
import com.metamx.collections.bitmap.ImmutableBitmap;
import com.metamx.collections.bitmap.MutableBitmap;
import com.metamx.collections.bitmap.WrappedImmutableRoaringBitmap;
import io.druid.segment.data.Offset;
import io.druid.segment.data.RoaringBitmapSerdeFactory;
import org.roaringbitmap.IntIterator;

/**
 */
public class BitmapOffset implements Offset
{
  private static final int INVALID_VALUE = -1;
  private static final BitmapFactory ROARING_BITMAP_FACTORY = new RoaringBitmapSerdeFactory(false).getBitmapFactory();

  private final IntIterator itr;
  private final BitmapFactory bitmapFactory;
  private final ImmutableBitmap bitmapIndex;
  private final boolean descending;

  private volatile int val;

  public static IntIterator getReverseBitmapOffsetIterator(ImmutableBitmap bitmapIndex)
  {
    ImmutableBitmap roaringBitmap = bitmapIndex;
    if (!(bitmapIndex instanceof WrappedImmutableRoaringBitmap)) {
      final MutableBitmap bitmap = ROARING_BITMAP_FACTORY.makeEmptyMutableBitmap();
      final IntIterator iterator = bitmapIndex.iterator();
      while (iterator.hasNext()) {
        bitmap.add(iterator.next());
      }
      roaringBitmap = ROARING_BITMAP_FACTORY.makeImmutableBitmap(bitmap);
    }
    return ((WrappedImmutableRoaringBitmap) roaringBitmap).getBitmap().getReverseIntIterator();
  }

  public BitmapOffset(BitmapFactory bitmapFactory, ImmutableBitmap bitmapIndex, boolean descending)
  {
    this.bitmapFactory = bitmapFactory;
    this.bitmapIndex = bitmapIndex;
    this.descending = descending;
    this.itr = newIterator();
    increment();
  }

  private IntIterator newIterator()
  {
    if (!descending) {
      return bitmapIndex.iterator();
    } else {
      return getReverseBitmapOffsetIterator(bitmapIndex);
    }
  }

  private BitmapOffset(BitmapOffset otherOffset)
  {
    this.bitmapFactory = otherOffset.bitmapFactory;
    this.bitmapIndex = otherOffset.bitmapIndex;
    this.descending = otherOffset.descending;
    this.itr = otherOffset.itr.clone();
    this.val = otherOffset.val;
  }

  @Override
  public void increment()
  {
    if (itr.hasNext()) {
      val = itr.next();
    } else {
      val = INVALID_VALUE;
    }
  }

  @Override
  public boolean withinBounds()
  {
    return val > INVALID_VALUE;
  }

  @Override
  public Offset clone()
  {
    if (bitmapIndex == null || bitmapIndex.size() == 0) {
      return new BitmapOffset(bitmapFactory, bitmapFactory.makeEmptyImmutableBitmap(), descending);
    }

    return new BitmapOffset(this);
  }

  @Override
  public int getOffset()
  {
    return val;
  }
}


text:
- [x] Homomorphic Addition
- [ ] Homomorphic Multiplication
- [ ] Homomorphic Subtraction
- [ ] Negative Number Support

A **[Paillier](https://en.wikipedia.org/wiki/Paillier_cryptosystem)** implementation in Haskell after updating and fixing **[this](https://github.com/onemouth/HsPaillier)**  implementation.

#### Description
The paillier scheme supports binary operations on encrypted data such that when the result is decrypted it equals a binary operation on the unencrypted data.

Multiplication of ciphertext results in the addition of underlying plaintext when the resulting ciphertext is decrypted.
Similarly, exponentiation of ciphertexts results in multiplication of the underlying plaintext.

### Implementation
- Public Key Params :
    * n = p*q where p & q are large primes such that gcd(pq,(p-1)(q-1)). This requirement is guaranteed because p & q are of equal size.
    * g = Is the set of integers less than n^2 & relatively prime to n^2. i.e gcd(g,n^2) == 1

- Private Key Params :
    * λ = lcm(p-1,q-1)
    * μ = a^(1) mod n. Where a^(-1) is the multiplicative modular inverse and a = L (g^λ mod n^2) where L(x) = (x-1)/n

- Encryption:
    * cipher = g^plain * r^n mod n^2

- Decryption:
    * plain = L(cipher^λ mod n^2) * μ mod n

### NOTES
Currently only supports additive homomorphism on positive integers. Key pairs are recommended to be at least > 5 bits as part of the [cryptonite](https://hackage.haskell.org/package/cryptonite) package.

QuickCheck test-suite is available under the test directory

```haskell

main = do
    -- Generate a 64Bit public/private key pair
    Right(pub,prv) <- runExceptT $ genKeys 64

    -- Encrypt 10
    ct  <- encrypt (PlainText 10) pub

    --Encrypt 5
    ct' <- encrypt (PlainText 5) pub

    -- CipherText is has instance Num so multiplication is simple
    let ct'' = ct * ct'

    -- Decryption of resulting product will be 15
    let p = decrypt ct'' prv pub


text:
OpenImage is a micro library for resize, make a thumbnail or apply filters of your images.

## Usage

```php
require('class.openimage.php');

$image = new OpenImage($_FILES['image']['tmp_name']);    // string: path of image
$image->name('thumbnail_200-200');                       // string: name of image
$image->width(200);                                      // int: width of new image
$image->height(290);                                     // int: height of new image
$image->quality(100);                                    // int: quality in percent of new image
$image->processing('cover');                             // string: (stretch, cover, contain) how the new image is processed for a thumbnail
$image->position('center center');                       // string: (left top, center bottom, right center, top, right) where the new image is placed
$image->background('currentColor');                      // string/array: ('ffffff', '#000000', 'faa', 'currentColor', array("r" => 255, "g" => 255, "b" => 255, "a" => 1)) the background color of the image, "currentColor" uses the main color of the image, The array manage the alpha channel
$image->filter('grayscale');                             // string: (negate, grayscale, edgedetect, emboss, mean_removal, blur) apply filtres to new image
$image->convert('png');                                  // string: (jpg, png) convert new image to new extension
$image->destination('./uploads/');                       // string/null: the path of new image, null return the raw image stream directly
$image->debug(true);                                     // boolean: return php error

$imageName = $image->render(); // make new image and return the new image name with extension or return false

if ($imageName) {
    var_dump($imageName);      // "thumbnail_200-200.png"
} else {
    var_dump($imageName);      // false
}
```

## Releases

[3.1] Release:
- rewrite documentation

[3.0] Release:
- rewrite OpenImage in object

[2.4] Release:
- Optimization and reorganize the function.
- Can choice filters for the picture : "<tt>negate</tt>", "<tt>grayscale</tt>", "<tt>edgedetect</tt>", "<tt>emboss</tt>", "<tt>mean_removal</tt>", "<tt>smooth</tt>" or "<tt>blur</tt>"

[2.3] Release:
- Optimization of the function.
- Can choice the position of the picture for thumbnail in "<tt>contain</tt>" or "<tt>cover</tt>"

[2.2] Release:
- Optimization of the function.

[2.1] Release:
- You can choice the <tt>background</tt> color (hexa) or <tt>transparent</tt> for your thumbnail (jpg and png).
- You can make a <tt>blur</tt> picture.

[2.0] Release:
- You can create on thumbnail (jpg and png).
- 3 mod for thumbnail: <tt>strectch</tt> (default), <tt>contain</tt>, <tt>cover</tt>.
- PNG <tt>transparent</tt> is ok.

[1.0] Release:
- You can resize on picture (jpg and png).
- PNG transparent is OK.
- Choice the quality (percentage)
- Can convert the new picture: <tt>jpg</tt> or <tt>png</tt>

## License

The code is MIT license. You must just say the name of the first developer : Jérôme Wohlschlegel


text:
<?php
	if (!defined('STORE_KEY')) { die ('[ERR:'.__LINE__.'] Invalid direct call to file'); }

function returnRelatedPhotos($aryParams = FALSE) {

ob_start(); ?>

Related Photos

<?php

		return ob_get_clean();

	}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Gaivota</logradouro><bairro>Passarinho</bairro><cidade>Recife</cidade><uf>PE</uf><cep>52170200</cep></feed>


text:
dbm.registerClass("dbm.core.globalobjects.templatemanager.setup.DefaultBasicClassShortcutSetup", "dbm.core.BaseObject", function(objectFunctions, staticFunctions, ClassReference) {
	//console.log("dbm.core.globalobjects.templatemanager.setup.DefaultBasicClassShortcutSetup");

	var DefaultBasicClassShortcutSetup = dbm.importClass("dbm.core.globalobjects.templatemanager.setup.DefaultBasicClassShortcutSetup");

	var ErrorManager = dbm.importClass("dbm.core.globalobjects.errormanager.ErrorManager");
	var ReportTypes = dbm.importClass("dbm.constants.error.ReportTypes");
	var ReportLevelTypes = dbm.importClass("dbm.constants.error.ReportLevelTypes");

	var DisplayBaseObject = dbm.importClass("dbm.gui.DisplayBaseObject");
	var BaseButton = dbm.importClass("dbm.gui.buttons.BaseButton");
	var StaticImage = dbm.importClass("dbm.gui.images.StaticImage");
	var StateImage = dbm.importClass("dbm.gui.images.StateImage");
	var InputField = dbm.importClass("dbm.gui.form.InputField");
	var FileUploadButton = dbm.importClass("dbm.gui.buttons.FileUploadButton");
	var LinkElement = dbm.importClass("dbm.gui.text.LinkElement");
	var TreeStructureView = dbm.importClass("dbm.gui.data.treestructure.TreeStructureView");
	var TreeStructureItemView = dbm.importClass("dbm.gui.data.treestructure.TreeStructureItemView");
	var SwitchableAreaHolder = dbm.importClass("dbm.gui.abstract.switchablearea.SwitchableAreaHolder");
	var HorizontalScaleSlider = dbm.importClass("dbm.gui.form.sliders.HorizontalScaleSlider");
	var HorizontalPlayheadSlider = dbm.importClass("dbm.gui.form.sliders.HorizontalPlayheadSlider");
	var CanvasView = dbm.importClass("dbm.gui.canvas.CanvasView");

	var TemplateClassShortcutNames = dbm.importClass("dbm.constants.template.TemplateClassShortcutNames");

	objectFunctions._init = function() {
		//console.log("dbm.core.globalobjects.templatemanager.setup.DefaultBasicClassShortcutSetup::_init");

		this.superCall();

		return this;
	};

	staticFunctions.setup = function() {

		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_DISPLAY_BASE_OBJECT, DisplayBaseObject);
		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_BASE_BUTTON, BaseButton);
		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_STATIC_IMAGE, StaticImage);
		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_STATE_IMAGE, StateImage);
		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_INPUT_FIELD, InputField);
		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_FILE_UPLOAD_BUTTON, FileUploadButton);
		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_LINK_ELEMENT, LinkElement);
		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_HORIZONTAL_SCALE_SLIDER, HorizontalScaleSlider);
		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_HORIZONTAL_PLAYHEAD_SLIDER, HorizontalPlayheadSlider);

		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_CANVAS_VIEW, CanvasView);

		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_SWITCHABLE_AREA_HOLDER, SwitchableAreaHolder);

		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_TREE_STRUCTURE_VIEW, TreeStructureView);
		dbm.singletons.dbmTemplateManager.registerClassShortcut(TemplateClassShortcutNames.DBM_TREE_STRUCTURE_ITEM_VIEW, TreeStructureItemView);

	};
});


text:
package org.bouncycastle.openpgp.jcajce;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator;

/**
 * {@link PGPObjectFactory} that uses the sources cryptographic primitives from the JCA API.
 */
public class JcaPGPObjectFactory
    extends PGPObjectFactory
{
    /**
     * Construct an object factory to read PGP objects from encoded data.
     *
     * @param encoded the PGP encoded data.
     */
    public JcaPGPObjectFactory(byte[] encoded)
    {
        this(new ByteArrayInputStream(encoded));
    }

    /**
     * Construct an object factory to read PGP objects from a stream.
     *
     * @param in the stream containing PGP encoded objects.
     */
    public JcaPGPObjectFactory(InputStream in)
    {
        // FIXME: Convert this to builder style so we can set provider?
        super(in, new JcaKeyFingerprintCalculator());
    }
}


text:
<?php
Controller::$defaultLayout='admin/cms';
/** @Check('ACSecureAdmin') @Acl('CMS') */
class FilesLibraryController extends Controller{
	/** */
	static function index(){
		LibraryFile::Table()->allowFilters()
			->paginate()
			->fields(array('id',
					'image'=>array('widthPx'=>1,'function'=>function($o){ return $o->type===LibraryFile::IMAGE ? $o->show('mini') : ''; },'escape'=>false),
					'name'=>array(
						'escape'=>false,
						'function'=>function($o){ return h($o->name).'<br/>'.HHtml::link(substr($link=$o->link(),0,1)==='/'?'\\'.$link:$link,false,array('target'=>'_blank')); }
					),
					'type'=>array('widthPx'=>1),
					'created','updated'
			))
			->actionDelete()
			->render(_t('plugins.files.FilesLibrary'),function(){
				echo $form=HForm::File()->action('/filesLibrary/upload')->attrClass('oneline');
				echo $form->inputFile('file')->noLabel();
				echo $form->select('type',LibraryFile::typesList())->noLabel();
				echo $form->end(_tC('Add'));
			});
	}
	/** */
	static function tools(){
		/* TODO : regenerate thumbnails,... */
		redirect('/filesLibrary');
	}

	/** */
	static function delete(int $id){
		if(CHttpRequest::referer(true) !== CRoute::getStringLink('admin','/filesLibrary')) exit;
		$file = LibraryFile::ById($id)->mustFetch();
		if($file->type===LibraryFile::IMAGE) ACFilesLibraryImages::deleteFiles($id);
		else ACFilesLibrary::deleteFile($file);
		LibraryFile::deleteOneById($id);
		redirect('/filesLibrary');
	}

	/** */
	static function upload(int $type){
		if($type===LibraryFile::IMAGE) ACFilesLibraryImages::upload('file');
		else ACFilesLibrary::uploadAndDetect('file','ACFilesLibraryImages');
		redirect('/filesLibrary');
	}

	/** @Ajax */
	static function images(int $id){
		if($id===0) $id=false;

		CGallery::index($id,LibraryFile::IMAGE,'LibraryFolder','LibraryFile');
	}

	/** */
	static function uploadImage(int $albumId){
		$image=new LibraryFile();
		$image->type=LibraryFile::IMAGE;
		if($albumId!==0) $image->album_id=$albumId;
		ACFilesLibraryImages::plupload($image);
	}

	/** @Ajax @ValidParams @AllRequired */
	static function renameFile(int $id,$newName){
		LibraryFile::updateOneFieldByPk($id,'name',$newName);
		renderText('1');
	}

	/** @Ajax @ValidParams @AllRequired */
	static function renameFolder(int $id,$newName){
		LibraryFolder::updateOneFieldByPk($id,'name',$newName);
		renderText('1');
	}

	/** @Ajax @ValidParams @Required('name') */
	static function addFolder(int $parentId,$name){
		if($parentId===0) $parentId=null;
		$id=LibraryFolder::create($parentId,$name);
		renderJSON('{"id":'.$id.'}');
	}
}


text:
package tuner.test.integration

import org.scalatest._
import org.scalatest.Matchers._

import net.liftweb.json._
import net.liftweb.json.Extraction._
import scala.io.Source

import tuner.gp.GpModel
import tuner.gp.GpSpecification

import tuner.test.Util._

class GpModelSpec extends WordSpec {

  implicit val formats = net.liftweb.json.DefaultFormats

  "A GpModel" when {
    "given a valid 8D json file to load" must {
      val jsonPath = resource("/gp/8d_1.json")
      val json = parse(Source.fromFile(jsonPath).mkString)

      "load the model without errors" in {
        val proj = json.extract[GpSpecification]
        GpModel.fromJson(proj)
      }
    }

    "given a valid 3D json file to load" must {
      val jsonPath = resource("/gp/3d_1.json")
      val json = parse(Source.fromFile(jsonPath).mkString)

      "load the model without errors" in {
        val proj = json.extract[GpSpecification]
        GpModel.fromJson(proj)
      }

      "create json that is reloadable" in {
        val gp = GpModel.fromJson(json.extract[GpSpecification])
        val gpJson = gp.toJson
        GpModel.fromJson(json.extract[GpSpecification]) should equal (gp)
      }
    }

    "2 models are loaded from the same dataset they" must {
      val jsonPath = resource("/gp/3d_1.json")
      val json = parse(Source.fromFile(jsonPath).mkString)

      "equal each other" in {
        val gp1 = GpModel.fromJson(json.extract[GpSpecification])
        val gp2 = GpModel.fromJson(json.extract[GpSpecification])
        gp1 should equal (gp2)
      }
    }

    "given another valid 3D json file to load" must {
      val jsonPath = resource("/gp/3d_2.json")
      val json = parse(Source.fromFile(jsonPath).mkString)

      "load the model without errors" in {
        val proj = json.extract[GpSpecification]
        GpModel.fromJson(proj)
      }
    }
  }

}


text:
/**
 * Utilities for generating shaders from literal style objects
 * @module ol/webgl/ShaderBuilder
 */

import {asArray} from '../color.js';

/**
 * Will return the number as a float with a dot separator, which is required by GLSL.
 * @param {number} v Numerical value.
 * @returns {string} The value as string.
 */
export function formatNumber(v) {
  const s = v.toString();
  return s.indexOf('.') === -1 ? s + '.0' : s;
}

/**
 * Will return the number array as a float with a dot separator, concatenated with ', '.
 * @param {Array<number>} array Numerical values array.
 * @returns {string} The array as string, e. g.: `1.0, 2.0, 3.0`.
 */
export function formatArray(array) {
  return array.map(formatNumber).join(', ');
}

/**
 * Will normalize and converts to string a color array compatible with GLSL.
 * @param {Array<number>} colorArray Color in [r, g, b, a] array form, with RGB components in the
 * 0..255 range and the alpha component in the 0..1 range. Note that if the A component is
 * missing, only 3 values will be output.
 * @returns {string} The color components concatenated in `1.0, 1.0, 1.0, 1.0` form.
 */
export function formatColor(colorArray) {
  return colorArray.map(function(c, i) {
    return i < 3 ? c / 255 : c;
  }).map(formatNumber).join(', ');
}

/**
 * @typedef {Object} VaryingDescription
 * @property {string} name Varying name, as will be declared in the header.
 * @property {string} type Varying type, either `float`, `vec2`, `vec4`...
 * @property {string} expression Expression which will be assigned to the varying in the vertex shader, and
 * passed on to the fragment shader.
 */

/**
 * @typedef {Object} ShaderParameters
 * @property {Array<string>} [uniforms] Uniforms; these will be declared in the header (should include the type).
 * @property {Array<string>} [attributes] Attributes; these will be declared in the header (should include the type).
 * @property {Array<VaryingDescription>} [varyings] Varyings with a name, a type and an expression.
 * @property {string} sizeExpression This will be assigned to a `vec2 size` variable.
 * @property {string} offsetExpression This will be assigned to a `vec2 offset` variable.
 * @property {string} colorExpression This will be the value assigned to gl_FragColor
 * @property {string} texCoordExpression This will be the value assigned to the `vec4 v_texCoord` varying.
 * @property {boolean} [rotateWithView=false] Whether symbols should rotate with view
 */

/**
 * Generates a symbol vertex shader from a set of parameters,
 * intended to be used on point geometries.
 *
 * Three uniforms are hardcoded in all shaders: `u_projectionMatrix`, `u_offsetScaleMatrix` and
 * `u_offsetRotateMatrix`.
 *
 * The following attributes are hardcoded and expected to be present in the vertex buffers:
 * `vec2 a_position`, `float a_index` (being the index of the vertex in the quad, 0 to 3).
 *
 * The following varyings are hardcoded and gives the coordinate of the pixel both in the quad on the texture:
 * `vec2 v_quadCoord`, `vec2 v_texCoord`
 *
 * @param {ShaderParameters} parameters Parameters for the shader.
 * @returns {string} The full shader as a string.
 */
export function getSymbolVertexShader(parameters) {
  const offsetMatrix = parameters.rotateWithView ?
    'u_offsetScaleMatrix * u_offsetRotateMatrix' :
    'u_offsetScaleMatrix';

  const uniforms = parameters.uniforms || [];
  const attributes = parameters.attributes || [];
  const varyings = parameters.varyings || [];

  const body = `precision mediump float;
uniform mat4 u_projectionMatrix;
uniform mat4 u_offsetScaleMatrix;
uniform mat4 u_offsetRotateMatrix;
${uniforms.map(function(uniform) {
    return 'uniform ' + uniform + ';';
  }).join('\n')}
attribute vec2 a_position;
attribute float a_index;
${attributes.map(function(attribute) {
    return 'attribute ' + attribute + ';';
  }).join('\n')}
varying vec2 v_texCoord;
varying vec2 v_quadCoord;
${varyings.map(function(varying) {
    return 'varying ' + varying.type + ' ' + varying.name + ';';
  }).join('\n')}
void main(void) {
  mat4 offsetMatrix = ${offsetMatrix};
  vec2 size = ${parameters.sizeExpression};
  vec2 offset = ${parameters.offsetExpression};
  float offsetX = a_index == 0.0 || a_index == 3.0 ? offset.x - size.x / 2.0 : offset.x + size.x / 2.0;
  float offsetY = a_index == 0.0 || a_index == 1.0 ? offset.y - size.y / 2.0 : offset.y + size.y / 2.0;
  vec4 offsets = offsetMatrix * vec4(offsetX, offsetY, 0.0, 0.0);
  gl_Position = u_projectionMatrix * vec4(a_position, 0.0, 1.0) + offsets;
  vec4 texCoord = ${parameters.texCoordExpression};
  float u = a_index == 0.0 || a_index == 3.0 ? texCoord.s : texCoord.q;
  float v = a_index == 2.0 || a_index == 3.0 ? texCoord.t : texCoord.p;
  v_texCoord = vec2(u, v);
  u = a_index == 0.0 || a_index == 3.0 ? 0.0 : 1.0;
  v = a_index == 2.0 || a_index == 3.0 ? 0.0 : 1.0;
  v_quadCoord = vec2(u, v);
${varyings.map(function(varying) {
    return '  ' + varying.name + ' = ' + varying.expression + ';';
  }).join('\n')}
}`;

  return body;
}

/**
 * Generates a symbol fragment shader intended to be used on point geometries.
 *
 * Expected the following varyings to be transmitted by the vertex shader:
 * `vec2 v_texCoord`
 *
 * @param {ShaderParameters} parameters Parameters for the shader.
 * @returns {string} The full shader as a string.
 */
export function getSymbolFragmentShader(parameters) {
  const uniforms = parameters.uniforms || [];
  const varyings = parameters.varyings || [];

  const body = `precision mediump float;
${uniforms.map(function(uniform) {
    return 'uniform ' + uniform + ';';
  }).join('\n')}
varying vec2 v_texCoord;
varying vec2 v_quadCoord;
${varyings.map(function(varying) {
    return 'varying ' + varying.type + ' ' + varying.name + ';';
  }).join('\n')}
void main(void) {
  gl_FragColor = ${parameters.colorExpression};
  gl_FragColor.rgb *= gl_FragColor.a;
}`;

  return body;
}

/**
 * Base type for values fed to operators; can be a number literal or the output of another operator
 * @typedef {Array<*>|number} OperatorValue
 */

/**
 * Parses the provided expressions and produces a GLSL-compatible assignment string, such as:
 * `['add', ['*', ['get', 'size'], 0.001], 12] => '(a_size * (0.001)) + (12.0)'
 *
 * The following operators can be used:
 * * `['get', 'attributeName']` fetches a feature attribute (it will be prefixed by `a_` in the shader)
 * * `['*', value1, value1]` multiplies value1 by value2
 * * `['+', value1, value1]` adds value1 and value2
 * * `['clamp', value1, value2, value3]` clamps value1 between values2 and value3
 * * `['stretch', value1, value2, value3, value4, value5]` maps value1 from [value2, value3] range to
 *   [value4, value5] range, clamping values along the way
 *
 * Values can either be literals (numbers) or another operator, as they will be evaluated recursively.
 *
 * Also takes in an array where new attributes will be pushed, so that the user of the `parse` function
 * knows which attributes are expected to be available at evaluation time.
 *
 * A prefix must be specified so that the attributes can either be written as `a_name` or `v_name` in
 * the final assignment string.
 *
 * @param {OperatorValue} value Either literal or an operator.
 * @param {Array<string>} attributes Array containing the attribute names prefixed with `a_`; it
 * it passed along recursively
 * @param {string} attributePrefix Prefix added to attribute names in the final output (typically `a_` or `v_`).
 * @returns {string} Assignment string.
 */
export function parse(value, attributes, attributePrefix) {
  const v = value;
  function p(value) {
    return parse(value, attributes, attributePrefix);
  }
  if (Array.isArray(v)) {
    switch (v[0]) {
      case 'get':
        if (attributes.indexOf(v[1]) === -1) {
          attributes.push(v[1]);
        }
        return attributePrefix + v[1];
      case '*': return `(${p(v[1])} * ${p(v[2])})`;
      case '+': return `(${p(v[1])} + ${p(v[2])})`;
      case 'clamp': return `clamp(${p(v[1])}, ${p(v[2])}, ${p(v[3])})`;
      case 'stretch': return `(clamp(${p(v[1])}, ${p(v[2])}, ${p(v[3])}) * ((${p(v[5])} - ${p(v[4])}) / (${p(v[3])} - ${p(v[2])})) + ${p(v[4])})`;
      default: throw new Error('Unrecognized literal style expression: ' + JSON.stringify(value));
    }
  } else if (typeof value === 'number') {
    return formatNumber(value);
  } else {
    throw new Error('Invalid value type in expression: ' + JSON.stringify(value));
  }
}

/**
 * @typedef {Object} StyleParseResult
 * @property {ShaderParameters} params Symbol shader params.
 * @property {Object.<string,import("./Helper").UniformValue>} uniforms Uniform definitions.
 * @property {Array<import("../renderer/webgl/PointsLayer").CustomAttribute>} attributes Attribute descriptions.
 */

/**
 * Parses a {@link import("../style/LiteralStyle").LiteralSymbolStyle} object and outputs shader parameters to be
 * then fed to {@link getSymbolVertexShader} and {@link getSymbolFragmentShader}.
 *
 * Also returns `uniforms` and `attributes` properties as expected by the
 * {@link module:ol/renderer/webgl/PointsLayer~WebGLPointsLayerRenderer}.
 *
 * @param {import("../style/LiteralStyle").LiteralSymbolStyle} style Symbol style.
 * @returns {StyleParseResult} Result containing shader params, attributes and uniforms.
 */
export function parseSymbolStyle(style) {
  const size = Array.isArray(style.size) && typeof style.size[0] == 'number' ?
    style.size : [style.size, style.size];
  const color = (typeof style.color === 'string' ?
    asArray(style.color).map(function(c, i) {
      return i < 3 ? c / 255 : c;
    }) :
    style.color || [255, 255, 255, 1]);
  const texCoord = style.textureCoord || [0, 0, 1, 1];
  const offset = style.offset || [0, 0];
  const opacity = style.opacity !== undefined ? style.opacity : 1;

  let attributes = [];
  const varyings = [];
  function pA(value) {
    return parse(value, attributes, 'a_');
  }
  function pV(value) {
    return parse(value, varyings, 'v_');
  }

  let opacityFilter = '1.0';
  const visibleSize = pV(size[0]);
  switch (style.symbolType) {
    case 'square': break;
    case 'image': break;
    // taken from https://thebookofshaders.com/07/
    case 'circle':
      opacityFilter = `(1.0-smoothstep(1.-4./${visibleSize},1.,dot(v_quadCoord-.5,v_quadCoord-.5)*4.))`;
      break;
    case 'triangle':
      const st = '(v_quadCoord*2.-1.)';
      const a = `(atan(${st}.x,${st}.y))`;
      opacityFilter = `(1.0-smoothstep(.5-3./${visibleSize},.5,cos(floor(.5+${a}/2.094395102)*2.094395102-${a})*length(${st})))`;
      break;

    default: throw new Error('Unexpected symbol type: ' + style.symbolType);
  }

  /** @type {import('../webgl/ShaderBuilder.js').ShaderParameters} */
  const params = {
    uniforms: [],
    colorExpression: `vec4(${pV(color[0])}, ${pV(color[1])}, ${pV(color[2])}, ${pV(color[3])})` +
      ` * vec4(1.0, 1.0, 1.0, ${pV(opacity)} * ${opacityFilter})`,
    sizeExpression: `vec2(${pA(size[0])}, ${pA(size[1])})`,
    offsetExpression: `vec2(${pA(offset[0])}, ${pA(offset[1])})`,
    texCoordExpression: `vec4(${pA(texCoord[0])}, ${pA(texCoord[1])}, ${pA(texCoord[2])}, ${pA(texCoord[3])})`,
    rotateWithView: !!style.rotateWithView
  };

  attributes = attributes.concat(varyings).filter(function(attrName, index, arr) {
    return arr.indexOf(attrName) === index;
  });
  params.attributes = attributes.map(function(attributeName) {
    return `float a_${attributeName}`;
  });
  params.varyings = varyings.map(function(attributeName) {
    return {
      name: `v_${attributeName}`,
      type: 'float',
      expression: `a_${attributeName}`
    };
  });

  /** @type {Object.<string,import("../webgl/Helper").UniformValue>} */
  const uniforms = {};

  if (style.symbolType === 'image' && style.src) {
    const texture = new Image();
    texture.src = style.src;
    params.uniforms.push('sampler2D u_texture');
    params.colorExpression = params.colorExpression +
      ' * texture2D(u_texture, v_texCoord)';
    uniforms['u_texture'] = texture;
  }

  return {
    params: params,
    attributes: attributes.map(function(attributeName) {
      return {
        name: attributeName,
        callback: function(feature) {
          return feature.get(attributeName) || 0;
        }
      };
    }),
    uniforms: uniforms
  };
}


text:
package de.deutschepost.rs.gr.eval.springboot.sse.controller;

import java.time.LocalTime;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter.SseEventBuilder;

@Controller
public class SseEmitterController {
    private ExecutorService nonBlockingService = Executors.newCachedThreadPool();

    @GetMapping(Constants.API_SSE)
    public SseEmitter handleSse() {
        SseEmitter emitter = new SseEmitter();

        nonBlockingService.execute(() -> {
            try {
                emitter.send(Constants.API_SSE_MSG + " @ " + new Date());
                emitter.complete();
            } catch (Exception ex) {
                System.out.println(Constants.GENERIC_EXCEPTION);
                emitter.completeWithError(ex);
            }
        });

        return emitter;
    }

    @GetMapping("/stream-sse-mvc")
    public SseEmitter streamSseMvc() {
        SseEmitter emitter = new SseEmitter();
        ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();

        sseMvcExecutor.execute(() -> {
            try {
                for (int i = 0; true; i++) {
                    SseEventBuilder event = SseEmitter.event()
                        .data("SSE MVC - " + LocalTime.now()
                            .toString())
                        .id(String.valueOf(i))
                        .name("sse event - mvc");
                    emitter.send(event);
                    Thread.sleep(1000);
                }
            } catch (Exception ex) {
                emitter.completeWithError(ex);
            }
        });
        return emitter;
    }

}


text:
import setuptools

VERSION = "0.1.0"

setuptools.setup(
    name="emailer",
    packages=["emailer"],

    version=VERSION,
    download_url="https://github.com/cmeadows/emailer/archive/v%s.zip" % VERSION,
    url="https://github.com/cmeadows/emailer",

    author="Collin Meadows",
    author_email="cmeadows@eborkdev.com",

    description="Python email package to send emails based off of jinja templates",
    long_description=open('README.md').read(),
    license="MIT",
    keywords=["email", "emailer", "jinja", "jinja2"],
    classifiers=[
        "Topic :: Utilities",
        "License :: OSI Approved :: MIT License",

        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.3",
    ],

    install_requires=[
        "jinja2 >= 2.8"
    ],
)


text:
#include "legion_terra.h"
#include "lua_mapper_wrapper.h"
#include "legion_terra_util.h"

#include <vector>

extern "C"
{
#include "lua.h"
#include "terra.h"

extern lua_State* prepare_interpreter(const std::string&);
}

using namespace std;
using namespace LegionRuntime::HighLevel;

#ifdef PROF_BINDING
static LegionRuntime::Logger::Category log("legion_terra_mapper");
#endif

enum LuaMapperResult
{
  FALSE_RETURNED = 0,
  TRUE_RETURNED,
  UNDEFINED,
};

LuaMapperWrapper::LuaMapperWrapper(Machine machine, Processor local,
                                   const char *name)
  : DefaultMapper(machine, local, name)
{
}

#if 0
// the resulting stack will have the method on top of its class
// if the return value was 0. Once the method call is returned,
// callers should pop out the remaining class from the stack.
static inline int lua_push_method(lua_State *L,
                                  const char *class_name,
                                  const char *method_name)
{
  lua_getglobal(L, class_name);
  if (!lua_istable(L, -1))
  {
    lua_pop(L, 1);
    return -1;
  }
  lua_pushstring(L, method_name);
  lua_gettable(L, -2);
  if (!lua_isfunction(L, -1))
  {
    lua_pop(L, 2);
    return -2;
  }
  return 0;
}

LuaMapperWrapper::LuaMapperWrapper(const char* qualified_mapper_name_,
                                   Machine machine,
                                   HighLevelRuntime *runtime,
                                   Processor local_proc)
  : DefaultMapper(machine, runtime, local_proc),
    qualified_mapper_name(qualified_mapper_name_),
    mapper_name(),
    L(0)
{
#ifdef PROF_BINDING
  double ts_start = LegionRuntime::TimeStamp::get_current_time_in_micros();
#endif
  unsigned n = qualified_mapper_name.find_last_of("/");
  string script_file = qualified_mapper_name.substr(0, n);
  mapper_name = qualified_mapper_name.substr(n + 1);
  L = prepare_interpreter(script_file);

  CHECK_LUA(lua_push_method(L, "LuaMapperWrapper", "new"));

  legion_machine_t machine_ = CObjectWrapper::wrap(&machine);
  legion_runtime_t runtime_ = CObjectWrapper::wrap(runtime);
  legion_processor_t local_proc_ = CObjectWrapper::wrap(local_proc);

  lua_getglobal(L, "LuaMapperWrapper");
  lua_pushlightuserdata(L, this);
  lua_pushstring(L, mapper_name.c_str());
  lua_push_opaque_object<CObjectWrapper>(L, machine_);
  lua_push_opaque_object<CObjectWrapper>(L, runtime_);
  lua_pushlightuserdata(L, &local_proc_);
  CHECK_LUA(lua_pcall(L, 6, 0, 0));

  // pop off the LuaMapperWrapper class(table)
  lua_pop(L, 1);
#ifdef PROF_BINDING
  double ts_end = LegionRuntime::TimeStamp::get_current_time_in_micros();
  log.info(
      "Proc " IDFMT ", Mapper new: %.3f ms",
      local_proc.id,
      (ts_end - ts_start) / 1e3);
#endif
}

LuaMapperWrapper::~LuaMapperWrapper()
{
#ifdef PROF_BINDING
  double ts_start = LegionRuntime::TimeStamp::get_current_time_in_micros();
#endif
  lua_close(L);
#ifdef PROF_BINDING
  double ts_end = LegionRuntime::TimeStamp::get_current_time_in_micros();
  log.info(
      "Proc " IDFMT ", Mapper delete: %.3f ms",
      local_proc.id,
      (ts_end - ts_start) / 1e3);
#endif
}

void LuaMapperWrapper::slice_domain(const Task *task, const Domain &domain,
                                    vector<DomainSplit> &slices)
{
#ifdef PROF_BINDING
  double ts_start = LegionRuntime::TimeStamp::get_current_time_in_micros();
#endif
  CHECK_LUA(lua_push_method(L, "LuaMapperWrapper", "slice_domain_wrapper"));

  const legion_task_t task_ = CObjectWrapper::wrap_const(task);
  legion_domain_t domain_ = CObjectWrapper::wrap(const_cast<Domain&>(domain));
  vector_legion_domain_split_t slices_ = ObjectWrapper::wrap(&slices);

  // call wrapper method in Lua
  lua_getglobal(L, "LuaMapperWrapper");
  lua_push_opaque_object<CObjectWrapper>(L, task_);
  lua_pushlightuserdata(L, &domain_);
  lua_push_opaque_object<ObjectWrapper, vector_legion_domain_split_t>(L, slices_);
  CHECK_LUA(lua_pcall(L, 4, 1, 0));

  // handle return value
  LuaMapperResult result = (LuaMapperResult)lua_tonumber(L, -1);
  lua_pop(L, 1);

  // pop off the LuaMapperWrapper class(table)
  lua_pop(L, 1);
  if (result == UNDEFINED)
    DefaultMapper::slice_domain(task, domain, slices);

#ifdef PROF_BINDING
  double ts_end = LegionRuntime::TimeStamp::get_current_time_in_micros();
  log.info(
      "Proc " IDFMT ", Slice domain: %.3f ms",
      local_proc.id,
      (ts_end - ts_start) / 1e3);
#endif
}

bool LuaMapperWrapper::map_task(Task *task)
{
#ifdef PROF_BINDING
  double ts_start = LegionRuntime::TimeStamp::get_current_time_in_micros();
#endif
  CHECK_LUA(lua_push_method(L, "LuaMapperWrapper", "map_task_wrapper"));

  legion_task_t task_ = CObjectWrapper::wrap(task);

  // call wrapper method in Lua
  lua_getglobal(L, "LuaMapperWrapper");
  lua_push_opaque_object<CObjectWrapper>(L, task_);
  CHECK_LUA(lua_pcall(L, 2, 1, 0));

  // handle return value
  LuaMapperResult result = (LuaMapperResult)lua_tonumber(L, -1);
  lua_pop(L, 1);

  // pop off the LuaMapperWrapper class(table)
  lua_pop(L, 1);
  if (result == UNDEFINED)
    result = static_cast<LuaMapperResult>(DefaultMapper::map_task(task));

#ifdef PROF_BINDING
  double ts_end = LegionRuntime::TimeStamp::get_current_time_in_micros();
  log.info(
      "Proc " IDFMT ", Map task: %.3f ms",
      local_proc.id,
      (ts_end - ts_start) / 1e3);
#endif
  return static_cast<bool>(result);
}

bool LuaMapperWrapper::map_inline(Inline *inline_operation)
{
#ifdef PROF_BINDING
  double ts_start = LegionRuntime::TimeStamp::get_current_time_in_micros();
#endif
  CHECK_LUA(lua_push_method(L, "LuaMapperWrapper", "map_inline_wrapper"));

  legion_inline_t inline_ = CObjectWrapper::wrap(inline_operation);

  // call wrapper method in Lua
  lua_getglobal(L, "LuaMapperWrapper");
  lua_push_opaque_object<CObjectWrapper>(L, inline_);
  CHECK_LUA(lua_pcall(L, 2, 1, 0));

  // handle return value
  LuaMapperResult result = (LuaMapperResult)lua_tonumber(L, -1);
  lua_pop(L, 1);

  // pop off the LuaMapperWrapper class(table)
  lua_pop(L, 1);

  if (result == UNDEFINED)
    result =
      static_cast<LuaMapperResult>(DefaultMapper::map_inline(inline_operation));

#ifdef PROF_BINDING
  double ts_end = LegionRuntime::TimeStamp::get_current_time_in_micros();
  log.info(
      "Proc " IDFMT ", Map inline: %.3f ms",
      local_proc.id,
      (ts_end - ts_start) / 1e3);
#endif
  return static_cast<bool>(result);
}

void LuaMapperWrapper::notify_mapping_failed(const Mappable *mappable)
{
  CHECK_LUA(lua_push_method(L, "LuaMapperWrapper",
        "notify_mapping_failed_wrapper"));

  legion_mappable_t mappable_ =
    CObjectWrapper::wrap(const_cast<Mappable*>(mappable));

  // call wrapper method in Lua
  lua_getglobal(L, "LuaMapperWrapper");
  lua_push_opaque_object<CObjectWrapper>(L, mappable_);
  CHECK_LUA(lua_pcall(L, 2, 1, 0));

  // handle return value
  LuaMapperResult result = (LuaMapperResult)lua_tonumber(L, -1);
  lua_pop(L, 1);

  // pop off the LuaMapperWrapper class(table)
  lua_pop(L, 1);

  if (result == UNDEFINED)
    DefaultMapper::notify_mapping_failed(mappable);
}

extern "C"
{

void decompose_index_space(legion_domain_t domain_,
                           legion_processor_t *targets_,
                           unsigned targets_size,
                           unsigned splitting_factor,
                           vector_legion_domain_split_t slices_)
{
  Domain domain = CObjectWrapper::unwrap(domain_);
  vector<Processor> targets;
  for (unsigned i = 0; i < targets_size; ++i)
    targets.push_back(CObjectWrapper::unwrap(targets_[i]));

  vector<Mapper::DomainSplit>* slices = ObjectWrapper::unwrap(slices_);
  DefaultMapper::decompose_index_space(domain, targets, splitting_factor,
                                       *slices);
}

}
#endif


text:
package org.dcm4cheri.imageio.plugins;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferUShort;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.WritableRaster;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.util.Collections;
import java.util.Iterator;

import javax.imageio.IIOException;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;

import org.apache.log4j.Logger;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.data.DcmParser;
import org.dcm4che.data.DcmParserFactory;
import org.dcm4che.data.DcmValueException;
import org.dcm4che.data.FileFormat;
import org.dcm4che.dict.Tags;
import org.dcm4che.dict.UIDs;
import org.dcm4che.image.ColorModelFactory;
import org.dcm4che.image.ColorModelParam;
import org.dcm4che.imageio.plugins.DcmImageReadParam;
import org.dcm4cheri.image.ImageReaderFactory;
import org.dcm4cheri.image.ItemParser;

import com.sun.media.imageio.stream.SegmentedImageInputStream;

/**
 * @author Gunter Zeilinger <gunterze@gmail.com>
 * @version $Revision: 18050 $ $Date: 2013-09-11 22:14:47 +0800 (周三, 11 9月 2013) $
 */
public class DcmImageReader extends ImageReader {

    private static final Logger log = Logger.getLogger(DcmImageReader.class);

    private static final String J2KIMAGE_READER = "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReader";

    private static final ColorModelFactory cmFactory = ColorModelFactory
            .getInstance();

    private ImageInputStream stream = null;

    private ImageReader decompressor = null;

    private boolean patchJpegLS;

    private ItemParser itemParser = null;

    // The image to be written.
    private BufferedImage theImage = null;

    // The image's tile.
    private WritableRaster theTile = null;

    private DcmParser theParser = null;

    private DcmMetadataImpl theMetadata = null;

    private Dataset theDataset = null;

    private long frame1StartPos;

    private int frameLength;

    private int width = -1;

    private int height = -1;

    private int planes = 0;

    private int samplesPerPixel = 1;

    private int numberOfFrames = 0;

    private String pmi = null;

    private boolean clamp;

    private int mask;

    private int sign;

    private boolean ybr2rgb = false;

    private ColorModelParam cmParam;

    private int dataType = 0;

    private int stored = 0;

    private float aspectRatio = 0;

    private int sourceXOffset;

    private int sourceYOffset;

    private int sourceWidth;

    private int sourceHeight;

    private int sourceXSubsampling;

    private int sourceYSubsampling;

    private int subsamplingXOffset;

    private int subsamplingYOffset;

    private int destXOffset;

    private int destYOffset;

    private int destWidth;

    private int totDestWidth;

    private int totDestHeight;

    public DcmImageReader(ImageReaderSpi originatingProvider) {
        super(originatingProvider);
    }

    // Take input from an ImageInputStream
    public void setInput(Object input, boolean seekForwardOnly,
            boolean ignoreMetadata) {
        super.setInput(input, seekForwardOnly, ignoreMetadata);
        if (input != null) {
            if (!(input instanceof ImageInputStream)) {
                throw new IllegalArgumentException(
                        "input not an ImageInputStream!");
            }
            this.stream = (ImageInputStream) input;
        } else {
            this.stream = null;
        }

        // Clear all values based on the previous stream contents
        resetStreamSettings();
    }

    public int getNumImages(boolean allowSearch) throws IOException {
        readMetadata();
        return numberOfFrames;
    }

    private void checkIndex(int imageIndex) {
        if (imageIndex >= numberOfFrames) {
            throw new IndexOutOfBoundsException("index: " + imageIndex
                    + ", frames: " + numberOfFrames);
        }
    }

    public int getWidth(int imageIndex) throws IOException {
        readMetadata();
        checkIndex(imageIndex);
        return width;
    }

    public int getHeight(int imageIndex) throws IOException {
        readMetadata();
        checkIndex(imageIndex);
        return height;
    }

    public float getAspectRatio(int imageIndex) throws IOException {
        readMetadata();
        checkIndex(imageIndex);
        return aspectRatio;
    }

    public IIOMetadata getStreamMetadata() throws IOException {
        readMetadata();
        return theMetadata;
    }

    public IIOMetadata getImageMetadata(int imageIndex) throws IOException {
        readMetadata();
        checkIndex(imageIndex);
        return null;
    }

    private void readMetadata() throws IOException {
        if (theMetadata != null) {
            return;
        }
        if (stream == null) {
            throw new IllegalStateException("Input not set!");
        }
        theParser = DcmParserFactory.getInstance().newDcmParser(stream);
        FileFormat fileFormat = theParser.detectFileFormat();
        this.theDataset = DcmObjectFactory.getInstance().newDataset();
        theParser.setDcmHandler(theDataset.getDcmHandler());
        theParser.parseDcmFile(fileFormat, Tags.PixelData);
        this.theMetadata = new DcmMetadataImpl(theDataset);
        if (theParser.getReadTag() != Tags.PixelData) {
            this.numberOfFrames = 0;
        } else {
            initParams();
        }
    }

    private void initParams() throws IOException {
        int alloc;
        switch (alloc = theDataset.getInt(Tags.BitsAllocated, 8)) {
        case 8:
            this.dataType = DataBuffer.TYPE_BYTE;
            break;
        case 16:
            this.dataType = DataBuffer.TYPE_USHORT;
            break;
        default:
            throw new IOException("" + alloc + " Bits Allocated not supported!");
        }
        this.stored = theDataset.getInt(Tags.BitsStored, alloc);
        this.mask = -1 >>> (32 - stored);
        this.sign = (theDataset.getInt(Tags.PixelRepresentation, 0) != 0)
                    ? -1 << (stored - 1) : 0;
        this.width = theDataset.getInt(Tags.Columns, 0);
        this.height = theDataset.getInt(Tags.Rows, 0);
        this.samplesPerPixel = theDataset.getInt(Tags.SamplesPerPixel, 1);
        this.pmi = theDataset.getString(Tags.PhotometricInterpretation,
                "MONOCHROME2");
        log.debug("Samples per pixel is " + this.samplesPerPixel + " "
                + this.pmi + " for size " + this.width + "," + this.height);
        this.planes = theDataset.getInt(Tags.PlanarConfiguration, 0);
        this.aspectRatio = width * pixelRatio() / height;
        this.numberOfFrames = theDataset.getInt(Tags.NumberOfFrames, 1);

        int rLen = theParser.getReadLength();
        if (rLen == -1) {
            String ts = getTransferSyntaxUID();
            this.ybr2rgb = ts.equals(UIDs.JPEGBaseline)
                    || ts.equals(UIDs.JPEGExtended);
            this.clamp = ybr2rgb && sign == 0 && alloc == 16 && stored < 12;
            this.itemParser = new ItemParser(theParser, numberOfFrames, ts);
            return;
        }
        this.frame1StartPos = theParser.getStreamPosition();
        this.frameLength = rLen / numberOfFrames;

        if (this.samplesPerPixel > 1) {
            if (alloc == 16) {
                throw new IOException("RGB 16 Bits allocated not supported!");
            }
            if (frameLength < 3 * width * height) {
                throw new DcmValueException("Invalid Length of Pixel Data: "
                        + rLen);
            }
            return;
        }

        if (frameLength < width * height * (alloc >> 3)) {
            throw new DcmValueException("Invalid Length of Pixel Data: " + rLen);
        }
    }

    private String getTransferSyntaxUID() {
        return theDataset.getFileMetaInfo().getTransferSyntaxUID();
    }

    private float pixelRatio() {
        int[] ratio = theDataset.getInts(Tags.PixelAspectRatio);
        if (ratio != null && ratio.length == 2) {
            if (ratio[0] == ratio[1] || ratio[0] <= 0 || ratio[1] <= 0) {
                return 1.f; // accept 0/0
            }
            return ratio[1] / (float) ratio[0];
        }
        float[] spacing = theDataset.getFloats(Tags.PixelSpacing);
        if (spacing == null || spacing.length != 2) {
            spacing = theDataset.getFloats(Tags.ImagerPixelSpacing);
            if (spacing == null || spacing.length != 2) {
                return 1.f;
            }
        }
        if (spacing[0] == spacing[1] || spacing[0] <= 0 || spacing[1] <= 0) {
            return 1.f;
        }
        return spacing[1] / spacing[0];
    }

    private static final ColorSpace sRGB = ColorSpace
            .getInstance(ColorSpace.CS_sRGB);

    private static final ColorSpace CS_YBR_FULL = SimpleYBRColorSpace
            .createYBRFullColorSpace();

    private static final ColorSpace CS_YBR_PARTIAL = SimpleYBRColorSpace
            .createYBRPartialColorSpace();

    private static final ImageTypeSpecifier YBR_FULL_PLANE = ImageTypeSpecifier
            .createBanded(CS_YBR_FULL, new int[] { 0, 1, 2 }, new int[] { 0, 0,
                    0 }, DataBuffer.TYPE_BYTE, false, false);

    private static final ImageTypeSpecifier YBR_FULL_PIXEL = ImageTypeSpecifier
            .createInterleaved(CS_YBR_FULL, new int[] { 0, 1, 2 },
                    DataBuffer.TYPE_BYTE, false, false);

    private static final ImageTypeSpecifier YBR_PARTIAL_PLANE = ImageTypeSpecifier
            .createBanded(CS_YBR_PARTIAL, new int[] { 0, 1, 2 }, new int[] { 0,
                    0, 0 }, DataBuffer.TYPE_BYTE, false, false);

    private static final ImageTypeSpecifier YBR_PARTIAL_PIXEL = ImageTypeSpecifier
            .createInterleaved(CS_YBR_PARTIAL, new int[] { 0, 1, 2 },
                    DataBuffer.TYPE_BYTE, false, false);

    private static final ImageTypeSpecifier RGB_PLANE = ImageTypeSpecifier
            .createBanded(sRGB, new int[] { 0, 1, 2 }, new int[] { 0, 0, 0 },
                    DataBuffer.TYPE_BYTE, false, false);

    private static final ImageTypeSpecifier RGB_PIXEL = ImageTypeSpecifier
            .createInterleaved(sRGB, new int[] { 0, 1, 2 },
                    DataBuffer.TYPE_BYTE, false, false);

    public Iterator getImageTypes(int imageIndex) throws IOException {
        return getImageTypes(imageIndex, null);
    }

    private Iterator getImageTypes(int imageIndex, DcmImageReadParam param)
            throws IOException {
        readMetadata();
        checkIndex(imageIndex);
        return Collections.singletonList(
                getImageTypeSpecifier(imageIndex, param != null ? param.getPValToDDL()
                        : null)).iterator();
    }

    private ImageTypeSpecifier getImageTypeSpecifier(int imageIndex, byte[] pv2dll) {
        if (this.samplesPerPixel == 3) {
            if (!ybr2rgb) {
                if (pmi.startsWith("YBR_FULL"))
                    return this.planes != 0 ? YBR_FULL_PLANE : YBR_FULL_PIXEL;
                if (pmi.startsWith("YBR_PARTIAL"))
                    return this.planes != 0 ? YBR_PARTIAL_PLANE
                            : YBR_PARTIAL_PIXEL;
            }
            return this.planes != 0 ? RGB_PLANE : RGB_PIXEL;
        }
        return new ImageTypeSpecifier(cmFactory
                .getColorModel(
                        this.cmParam = cmFactory.makeParam(
                                theDataset, imageIndex, pv2dll)),
                        new PixelInterleavedSampleModel(
                this.dataType, 1, 1, 1, 1, new int[] { 0 }));
    }

    public ImageReadParam getDefaultReadParam() {
        return new DcmImageReadParamImpl();
    }

    public synchronized BufferedImage read(int imageIndex, ImageReadParam param)
            throws IOException {
        readMetadata();
        checkIndex(imageIndex);
        DcmImageReadParam readParam = (DcmImageReadParam) param;
        if (readParam == null) {
            readParam = (DcmImageReadParam) getDefaultReadParam();
        }
        Iterator imageTypes = getImageTypes(imageIndex, readParam);
        this.theImage = getDestination(param, imageTypes, this.width,
                this.height);
        if (itemParser != null)
            return adjustBufferedImage(
                    decompress(imageIndex, readParam),
                    readParam);

        stream.seek(frame1StartPos + imageIndex * frameLength);

        this.theTile = theImage.getWritableTile(0, 0);

        Rectangle rect = getSourceRegion(param, width, height);
        this.sourceXOffset = rect.x;
        this.sourceYOffset = rect.y;
        this.sourceWidth = rect.width;
        this.sourceHeight = rect.height;
        this.sourceXSubsampling = readParam.getSourceXSubsampling();
        this.sourceYSubsampling = readParam.getSourceYSubsampling();
        this.subsamplingXOffset = readParam.getSubsamplingXOffset();
        this.subsamplingYOffset = readParam.getSubsamplingYOffset();
        Point point = readParam.getDestinationOffset();
        this.destXOffset = point.x;
        this.destYOffset = point.y;
        this.destWidth = sourceWidth / sourceXSubsampling;
        this.totDestWidth = theTile.getWidth();
        this.totDestHeight = theTile.getHeight();
        if (destXOffset < 0) {
            sourceXOffset -= destXOffset * sourceXSubsampling;
            if ((sourceWidth += destXOffset * sourceXSubsampling) < 0) {
                sourceWidth = 0;
            }
            destXOffset = 0;
        }
        if (destYOffset < 0) {
            sourceYOffset -= destYOffset * sourceYSubsampling;
            if ((sourceHeight += destYOffset * sourceYSubsampling) < 0) {
                sourceHeight = 0;
            }
            destYOffset = 0;
        }

        DataBuffer db = this.theTile.getDataBuffer();
        if (this.dataType == DataBuffer.TYPE_BYTE) {
            if (this.samplesPerPixel == 3) {
                if (this.planes != 0) {
                    readByteSamples(1, ((DataBufferByte) db).getData(0));
                    readByteSamples(1, ((DataBufferByte) db).getData(1));
                    readByteSamples(1, ((DataBufferByte) db).getData(2));
                } else {
                    readByteSamples(3, ((DataBufferByte) db).getData());
                }
            } else {
                readByteSamples(1, ((DataBufferByte) db).getData());
            }
        } else {
            readWordSamples(1, ((DataBufferUShort) db).getData());
        }

        return adjustBufferedImage(this.theImage, readParam);
    }

    private void initDecompressor() {
        if (decompressor == null) {
            ImageReaderFactory f = ImageReaderFactory.getInstance();
            String tsuid = getTransferSyntaxUID();
            decompressor = f.getReaderForTransferSyntax(tsuid);
            patchJpegLS = false;
            if (dataType == DataBuffer.TYPE_USHORT
                        && UIDs.JPEGLSLossless.equals(tsuid)) {
                    String patchJAIJpegLS = f.patchJAIJpegLS();
                    if (patchJAIJpegLS != null)
                        patchJpegLS = patchJAIJpegLS.length() == 0
                                || patchJAIJpegLS.equals(
                                        theDataset.getFileMetaInfo()
                                            .getImplementationClassUID());
            }
        }
    }

    private BufferedImage adjustBufferedImage(BufferedImage bi,
            DcmImageReadParam readParam) {
        final boolean autoWindowing = cmParam != null && cmParam.isMonochrome()
                && cmParam.getVOILUT() == null
                && cmParam.getNumberOfWindows() == 0
                && readParam.isAutoWindowing();
        if (!autoWindowing && !readParam.isMaskPixelData())
            return bi;
        final WritableRaster raster = bi.getRaster();
        DataBuffer db = raster.getDataBuffer();
        if (db instanceof DataBufferUShort)
            return adjustUShortBufferedImage(bi, readParam, autoWindowing,
                    raster, db);
        else if (db instanceof DataBufferByte)
            return adjustByteBufferedImage(bi, readParam, autoWindowing,
                    raster, db);
        else
            return bi;
    }

    /**
     * Adjusts the window level automatically for byte data, also performing the
     * masking if appropriate.
     *
     * @param bi
     * @param readParam
     * @param autoWindowing
     * @param raster
     * @param db
     * @return buffered image with a modified window level.
     */
    private BufferedImage adjustByteBufferedImage(BufferedImage bi,
            DcmImageReadParam readParam, final boolean autoWindowing,
            final WritableRaster raster, DataBuffer db) {
        byte[] data = ((DataBufferByte) db).getData();
        int mask = this.mask;
        int sign = this.sign;
        if (!autoWindowing) {
            for (int i = 0; i < data.length; i++)
                data[i] &= mask;
            return bi;
        }
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        int val;
        if (readParam.isMaskPixelData()) {
            for (int i = 0; i < data.length; i++) {
                data[i] = (byte) (val = data[i] & mask);
                if ((val & sign) != 0)
                    val |= sign;
                if (val < min)
                    min = val;
                if (val > max)
                    max = val;
            }
        } else {
            for (int i = 0; i < data.length; i++) {
                val = data[i] & mask;
                if ((val & sign) != 0)
                    val |= sign;
                if (val < min)
                    min = val;
                if (val > max)
                    max = val;
            }
        }
        final float w = (max - min) * cmParam.getRescaleSlope();
        final float c = ((max + min) / 2) * cmParam.getRescaleSlope()
                + cmParam.getRescaleIntercept();
        log.debug("auto c,w=" + c + "," + w + " min,max=" + min + "," + max
                + " mask=" + mask + " sign=" + sign);
        ColorModel cm = cmFactory.getColorModel(cmParam.update(c, w, cmParam
                .isInverse()));
        return new BufferedImage(cm, raster, false, null);
    }

    /**
     * Does auto windowing level and mask on unsigned unsigned short images.
     *
     * @param bi
     * @param readParam
     * @param autoWindowing
     * @param raster
     * @param db
     * @return Auto-window levelled image.
     */
    private BufferedImage adjustUShortBufferedImage(BufferedImage bi,
            DcmImageReadParam readParam, final boolean autoWindowing,
            final WritableRaster raster, DataBuffer db) {
        short[] data = ((DataBufferUShort) db).getData();
        int mask = this.mask;
        int sign = this.sign;
        if (!autoWindowing) {
            if (clamp)
                for (int i = 0; i < data.length; i++) {
                    if ((data[i] & 0xffff) > mask)
                        data[i] = (short) mask;
                }
            else
                for (int i = 0; i < data.length; i++)
                    data[i] &= mask;
            return bi;
        }
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        int val;
        if (clamp) {
            for (int i = 0; i < data.length; i++) {
                val = data[i] & 0xffff;
                if (val > mask)
                    data[i] = (short) (val = mask);
                if ((val & sign) != 0)
                    val |= sign;
                if (val < min)
                    min = val;
                if (val > max)
                    max = val;
            }
        } else if (readParam.isMaskPixelData()) {
            for (int i = 0; i < data.length; i++) {
                data[i] = (short) (val = data[i] & mask);
                if ((val & sign) != 0)
                    val |= sign;
                if (val < min)
                    min = val;
                if (val > max)
                    max = val;
            }
        } else {
            for (int i = 0; i < data.length; i++) {
                val = data[i] & mask;
                if ((val & sign) != 0)
                    val |= sign;
                if (val < min)
                    min = val;
                if (val > max)
                    max = val;
            }
        }
        final float w = (max - min) * cmParam.getRescaleSlope();
        final float c = ((max + min) / 2) * cmParam.getRescaleSlope()
                + cmParam.getRescaleIntercept();
        log.debug("auto w,c=" + w + "," + c + " min,max=" + min + "," + max
                + " mask=" + mask + " sign=" + sign);
        ColorModel cm = cmFactory.getColorModel(cmParam.update(c, w, cmParam
                .isInverse()));
        return new BufferedImage(cm, raster, false, null);
    }

    private BufferedImage decompress(int imageIndex,
            DcmImageReadParam readParam) throws IOException {
        initDecompressor();
        log.debug("Start decompressing frame#" + (imageIndex + 1));
        SegmentedImageInputStream siis =
                new SegmentedImageInputStream(stream, itemParser);
        itemParser.seekFrame(siis, imageIndex);
        decompressor.setInput(
                patchJpegLS ? new PatchJpegLSImageInputStream(siis)
                              : (ImageInputStream) siis);
        BufferedImage bi =
                decompressor.read(0, decompressorReadParam(readParam));
        // workaround for Bug in J2KImageReader and
        // J2KImageReaderCodecLib.setInput()
        if (decompressor.getClass().getName().startsWith(J2KIMAGE_READER)) {
            decompressor.dispose();
            decompressor = null;
        } else {
            decompressor.reset();
        }
        log.debug("Finished decompressed frame#" + (imageIndex + 1));
        return bi;
    }

    private ImageReadParam decompressorReadParam(DcmImageReadParam readParam) {
        ImageReadParam decompressorReadParam =
                decompressor.getDefaultReadParam();
        decompressorReadParam.setDestination(theImage);
        decompressorReadParam.setSourceRegion(readParam.getSourceRegion());
        decompressorReadParam.setSourceSubsampling(
                readParam.getSourceXSubsampling(),
                readParam.getSourceYSubsampling(),
                readParam.getSubsamplingXOffset(),
                readParam.getSubsamplingYOffset());
        decompressorReadParam.setDestinationOffset(
                readParam.getDestinationOffset());
        return decompressorReadParam;
    }

    private void readByteSamples(int samples, byte[] dest) throws IOException {
        byte[] srcRow = null;
        final int rowLen = width * samples;
        final int srcRowLen = sourceWidth * samples;
        final int srcXOffsetLen = sourceXOffset * samples;
        final int destXOffsetLen = destXOffset * samples;
        if (sourceXSubsampling != 1) {
            srcRow = new byte[srcRowLen];
        }
        final int maxPosMax = totDestHeight * totDestWidth;
        final int totDestRowLen = totDestWidth * samples;
        stream.skipBytes(rowLen * sourceYOffset);
        int destY = destYOffset;
        int pos = 0, posMax = 0;
        int x = 0, y = 0;
        int x3, pos3;
        try {
            for (y = 0; y < sourceHeight; ++y) {
                if ((y - subsamplingYOffset) % sourceYSubsampling != 0) {
                    stream.skipBytes(rowLen);
                    continue;
                }
                stream.skipBytes(srcXOffsetLen);
                if (sourceXSubsampling == 1) {
                    stream.readFully(dest, destY * totDestRowLen
                            + destXOffsetLen, srcRowLen);
                } else {
                    stream.readFully(srcRow);
                    pos = destY * totDestWidth + destXOffset;
                    posMax = Math.min(pos + destWidth, maxPosMax);
                    switch (samples) {
                    case 1:
                        for (x = 0; pos < posMax; ++x) {
                            if ((x - subsamplingXOffset) % sourceXSubsampling == 0) {
                                dest[pos++] = srcRow[x];
                            }
                        }
                        break;
                    case 3:
                        for (x = 0, x3 = 0, pos3 = pos * 3; pos < posMax; ++x) {
                            if ((x - subsamplingXOffset) % sourceXSubsampling == 0) {
                                dest[pos3++] = srcRow[x3++];
                                dest[pos3++] = srcRow[x3++];
                                dest[pos3++] = srcRow[x3++];
                                ++pos;
                            } else {
                                x3 += 3;
                            }
                        }
                        break;
                    default:
                        throw new Error("Internal dcm4che Error");
                    }
                }
                stream.skipBytes(rowLen - srcXOffsetLen - srcRowLen);
                if (++destY >= totDestHeight) {
                    ++y;
                    break;
                }
            }
            stream.skipBytes(rowLen * (height - sourceYOffset - y));
        } catch (Exception ex) {
            log.error(ex);
            throw new IIOException("Exception in readByteSamples", ex);
        }
    }

    private void readWordSamples(int samples, short[] dest) throws IOException {
        final int rowLen = width * samples;
        final int srcRowLen = sourceWidth * samples;
        final int srcXOffsetLen = sourceXOffset * samples;
        final int destXOffsetLen = destXOffset * samples;
        final byte[] srcRow = new byte[srcRowLen << 1];
        final ShortBuffer srcRowBuf = ByteBuffer.wrap(srcRow).order(
                theParser.getDcmDecodeParam().byteOrder).asShortBuffer();
        final int maxPosMax = totDestHeight * totDestWidth;
        final int totDestRowLen = totDestWidth * samples;
        stream.skipBytes((rowLen * sourceYOffset) << 1);
        int destY = destYOffset;
        int pos = 0, posMax = 0;
        int x = 0, y = 0;
        int x3, pos3;
        try {
            for (y = 0; y < sourceHeight; ++y) {
                if ((y - subsamplingYOffset) % sourceYSubsampling != 0) {
                    stream.skipBytes(rowLen << 1);
                    continue;
                }
                stream.skipBytes(srcXOffsetLen << 1);
                stream.readFully(srcRow);
                if (sourceXSubsampling == 1) {
                    srcRowBuf.rewind();
                    srcRowBuf.get(dest, destY * totDestRowLen + destXOffsetLen,
                            srcRowLen);
                } else {
                    pos = destY * totDestWidth + destXOffset;
                    posMax = Math.min(pos + destWidth, maxPosMax);
                    switch (samples) {
                    case 1:
                        for (x = 0; pos < posMax; ++x) {
                            if ((x - subsamplingXOffset) % sourceXSubsampling == 0) {
                                dest[pos++] = srcRowBuf.get(x);
                            }
                        }
                        break;
                    case 3:
                        for (x = 0, x3 = 0, pos3 = pos * 3; pos < posMax; ++x) {
                            if ((x - subsamplingXOffset) % sourceXSubsampling == 0) {
                                dest[pos3++] = srcRowBuf.get(x3++);
                                dest[pos3++] = srcRowBuf.get(x3++);
                                dest[pos3++] = srcRowBuf.get(x3++);
                                ++pos;
                            } else {
                                x3 += 3;
                            }
                        }
                        break;
                    default:
                        throw new Error("Internal dcm4che Error");
                    }
                }
                stream.skipBytes((rowLen - srcXOffsetLen - srcRowLen) << 1);
                if (++destY >= totDestHeight) {
                    ++y;
                    break;
                }
            }
            stream.skipBytes((rowLen * (height - sourceYOffset - y)) << 1);
        } catch (Exception ex) {
            log.error(ex);
            throw new IIOException("Exception in readWordSamples", ex);
        }
    }

    /**
     * Remove all settings including global settings such as <code>Locale</code>s
     * and listeners, as well as stream settings.
     */
    public void reset() {
        super.reset();
        this.stream = null;
        resetStreamSettings();
    }

    /**
     * Remove local settings based on parsing of a stream.
     */
    private void resetStreamSettings() {
        theParser = null;
        theMetadata = null;
        theDataset = null;
        pmi = null;
        cmParam = null;

        theImage = null;
        theTile = null;
        if (decompressor != null)
            decompressor.dispose();
        decompressor = null;
        ybr2rgb = false;
        itemParser = null;
    }
}


text:
import sys
import os
import platform
import argparse
import subprocess
import uuid
import shutil

pomdogDependencies = [
    {
        'dest': 'third-party',
        'repository': 'https://github.com/mogemimi/pomdog-third-party.git',
    },
    {
        'dest': 'tools/gyp',
        'repository': 'https://chromium.googlesource.com/external/gyp.git',
    },
    {
        'dest': 'third-party/iutest',
        'repository': 'https://github.com/srz-zumix/iutest.git',
    },
]

def GitCloneRepository(url, dest):
    command = ' '.join(["git clone --depth=1", url, dest])
    print(command)
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    message = process.communicate()[0]
    return message

def DownloadDependencies(pomdogPath):
    for dependency in pomdogDependencies:
        dest = os.path.normpath(os.path.join(pomdogPath, dependency['dest']))
        if not os.path.exists(dest):
            repositoryUrl = dependency['repository']
            GitCloneRepository(repositoryUrl, dest)
        if not os.path.isdir(dest):
            print("Error: {0} is not directory".format(dest))
            return False
    return True

def main():
    pomdogPath = os.path.join(os.path.dirname(__file__), "..")
    pomdogPath = os.path.normpath(pomdogPath)
    DownloadDependencies(pomdogPath)

if __name__ == '__main__':
    main()


text:
<readable><title>2094543127_46d2f1fedf</title><content>
A girl holding a crocodile 's mouth closed
A girl is posed over a statue of a dangerous animal .
A girl sits on what appears to be a crocodile .
A girl sitting on top of a crocodile
A girl with red hair is sitting on a crocodile holding its jaw .
</content></readable>


text:
<?php
use PHPUnit\Framework\TestCase;

class EmptyTestCaseTest extends TestCase
{
}


text:
/* (c) 2014 LinkedIn Corp. All rights reserved.
 *
 * 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.
 */

package com.linkedin.cubert.plan.physical;

import java.io.IOException;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.JobConf;
import org.codehaus.jackson.JsonNode;

import com.linkedin.cubert.utils.JsonUtils;

/**
 * Executes file systems tasks (rm, cp, mv etc).
 *
 * @author Maneesh Varshney
 */
public class CompletionTasks
{
    public static void doCompletionTasks(JsonNode tasks) throws IOException
    {
        FileSystem fs = FileSystem.get(new JobConf());

        for (int i = 0; i < tasks.size(); i++)
        {
            try
            {
                final JsonNode task = tasks.get(i);
                final String taskType = JsonUtils.getText(task, "type");
                final String[] paths = JsonUtils.asArray(task, "paths");

                if (taskType.equals("rm"))
                {
                    for (String path : paths)
                    {
                        System.out.println("Deleting path " + path + "...");
                        fs.delete(new Path(path), true);
                    }
                }
                else if (taskType.equals("mv"))
                {
                    System.out.println("Moving " + paths[0] + " to " + paths[1] + "...");

                    final Path from = new Path(paths[0]);
                    final Path to = new Path(paths[1]);
                    fs.delete(to, true);
                    fs.rename(from, to);
                }
                else if (taskType.equals("mkdir"))
                {
                    for (String path : paths)
                    {
                        System.out.println("Creating directory " + path);
                        fs.mkdirs(new Path(path));
                    }
                }
            }
            catch (IOException e)
            {
                System.err.println("ERROR: " + e.getMessage());
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface org.apache.poi.ss.formula.functions.Function (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.apache.poi.ss.formula.functions.Function

Packages that use Function

Package
Description

org.apache.poi.ss.formula

This package contains common internal POI code for manipulating formulas.

org.apache.poi.ss.formula.eval

org.apache.poi.ss.formula.functions

Uses of Function in org.apache.poi.ss.formula

Methods in org.apache.poi.ss.formula with parameters of type Function

Modifier and Type
Method and Description

static void
WorkbookEvaluator.registerFunction(java.lang.String name,
                Function func)

Register a function in runtime.

Uses of Function in org.apache.poi.ss.formula.eval

Classes in org.apache.poi.ss.formula.eval that implement Function

Modifier and Type
Class and Description

class
ConcatEval

class
IntersectionEval

class
PercentEval

Implementation of Excel formula token '%'.

class
RangeEval

class
RelationalOperationEval

Base class for all comparison operator evaluators

class
TwoOperandNumericOperation

class
UnaryMinusEval

class
UnaryPlusEval

Fields in org.apache.poi.ss.formula.eval declared as Function

Modifier and Type
Field and Description

static Function
TwoOperandNumericOperation.AddEval

static Function
TwoOperandNumericOperation.DivideEval

static Function
RelationalOperationEval.EqualEval

protected static Function[]
FunctionEval.functions

Array elements corresponding to unimplemented functions are null

static Function
RelationalOperationEval.GreaterEqualEval

static Function
RelationalOperationEval.GreaterThanEval

static Function
UnaryPlusEval.instance

static Function
UnaryMinusEval.instance

static Function
RangeEval.instance

static Function
PercentEval.instance

static Function
IntersectionEval.instance

static Function
ConcatEval.instance

static Function
RelationalOperationEval.LessEqualEval

static Function
RelationalOperationEval.LessThanEval

static Function
TwoOperandNumericOperation.MultiplyEval

static Function
RelationalOperationEval.NotEqualEval

static Function
TwoOperandNumericOperation.PowerEval

static Function
TwoOperandNumericOperation.SubtractEval

Methods in org.apache.poi.ss.formula.eval that return Function

Modifier and Type
Method and Description

static Function
FunctionEval.getBasicFunction(int functionIndex)

Methods in org.apache.poi.ss.formula.eval with parameters of type Function

Modifier and Type
Method and Description

static void
FunctionEval.registerFunction(java.lang.String name,
                Function func)

Register a new function in runtime.

Uses of Function in org.apache.poi.ss.formula.functions

Subinterfaces of Function in org.apache.poi.ss.formula.functions

Modifier and Type
Interface and Description

interface
Function0Arg

Implemented by all functions that can be called with zero arguments

interface
Function1Arg

Implemented by all functions that can be called with one argument

interface
Function2Arg

Implemented by all functions that can be called with two arguments

interface
Function3Arg

Implemented by all functions that can be called with three arguments

interface
Function4Arg

Implemented by all functions that can be called with four arguments

Classes in org.apache.poi.ss.formula.functions that implement Function

Modifier and Type
Class and Description

class
Address

Creates a text reference as text, given specified row and column numbers.

class
AggregateFunction

class
Bin2Dec

Implementation for Excel Bin2Dec() function.

class
BooleanFunction

Here are the general rules concerning Boolean functions:

  Blanks are ignored (not either true or false)
  Strings are ignored if part of an area ref or cell ref, otherwise they must be 'true' or 'false'
  Numbers: 0 is false.

class
CalendarFieldFunction

Implementation of Excel functions Date parsing functions:
  Date - DAY, MONTH and YEAR
  Time - HOUR, MINUTE and SECOND

class
Choose

class
Code

Implementation for Excel CODE () function.

class
Column

class
Columns

Implementation for Excel COLUMNS function.

class
Complex

Implementation for Excel COMPLEX () function.

class
Count

Counts the number of cells that contain numeric data within
  the list of arguments.

class
Counta

Counts the number of cells that contain data within the list of arguments.

class
Countblank

Implementation for the function COUNTBLANK

  Syntax: COUNTBLANK ( range )

      range   is the range of cells to count blanks

class
Countif

Implementation for the function COUNTIF

  Syntax: COUNTIF ( range, criteria )

      range   is the range of cells to be counted based on the criteria
      criteriais used to determine which cells to count

class
DateFunc

Implementation for the Excel function DATE

class
Days360

Calculates the number of days between two dates based on a 360-day year
 (twelve 30-day months), which is used in some accounting calculations.

class
Dec2Bin

Implementation for Excel Bin2Dec() function.

class
Dec2Hex

Implementation for Excel DELTA() function.

class
Delta

Implementation for Excel DELTA() function.

class
Errortype

Implementation for the ERROR.TYPE() Excel function.

class
Even

class
FactDouble

Implementation for Excel FACTDOUBLE() function.

class
FinanceFunction

class
Fixed0ArgFunction

Convenience base class for functions that only take zero arguments.

class
Fixed1ArgFunction

Convenience base class for functions that must take exactly one argument.

class
Fixed2ArgFunction

Convenience base class for functions that must take exactly two arguments.

class
Fixed3ArgFunction

Convenience base class for functions that must take exactly three arguments.

class
Fixed4ArgFunction

Convenience base class for functions that must take exactly four arguments.

class
Hex2Dec

Implementation for Excel HEX2DEC() function.

class
Hlookup

Implementation of the HLOOKUP() function.

class
Hyperlink

Implementation of Excel HYPERLINK function.

class
IfFunc

Implementation for the Excel function IF

class
Imaginary

Implementation for Excel IMAGINARY() function.

class
ImReal

Implementation for Excel ImReal() function.

class
Index

Implementation for the Excel function INDEX

 Syntax :

  INDEX ( reference, row_num[, column_num [, area_num]])

  INDEX ( array, row_num[, column_num])

      referencetypically an area reference, possibly a union of areas
      arraya literal array value (currently not supported)
      row_numselects the row within the array or area reference
      column_numselects column within the array or area reference. default is 1
      area_numused when reference is a union of areas

class
Intercept

Implementation of Excel function INTERCEPT()

 Calculates the INTERCEPT of the linear regression line that is used to predict y values from x values

 (http://introcs.cs.princeton.edu/java/97data/LinearRegression.java.html)
 Syntax:

 INTERCEPT(arrayX, arrayY)

class
IPMT

class
Irr

Calculates the internal rate of return.

class
LinearRegressionFunction

Base class for linear regression functions.

class
LogicalFunction

class
Lookup

Implementation of Excel function LOOKUP.

class
Match

Implementation for the MATCH() Excel function.

class
MinaMaxa

class
Mirr

Calculates Modified internal rate of return.

class
Mode

class
MultiOperandNumericFunction

class
Na

Implementation of Excel function NA()

class
NotImplementedFunction

class
Now

Implementation of Excel NOW() Function

class
Npv

Calculates the net present value of an investment by using a discount rate
 and a series of future payments (negative values) and income (positive
 values).

class
NumericFunction

static class
NumericFunction.OneArg

static class
NumericFunction.TwoArg

class
Oct2Dec

Implementation for Excel Oct2Dec() function.

class
Odd

class
Offset

Implementation for Excel function OFFSET()

 OFFSET returns an area reference that is a specified number of rows and columns from a
 reference cell or area.

class
PPMT

Compute the interest portion of a payment.

class
Quotient

Implementation for Excel QUOTIENT () function.

class
Rank

Returns the rank of a number in a list of numbers.

class
Rate

Implements the Excel Rate function

class
Replace

An implementation of the Excel REPLACE() function:

 Replaces part of a text string based on the number of characters
 you specify, with another text string.

class
Rept

Implementation for Excel REPT () function.

class
Roman

Implementation for Excel WeekNum() function.

class
RowFunc

Implementation for the Excel function ROW

class
Rows

Implementation for Excel ROWS function.

class
Slope

Implementation of Excel function SLOPE()

 Calculates the SLOPE of the linear regression line that is used to predict y values from x values

 (http://introcs.cs.princeton.edu/java/97data/LinearRegression.java.html)
 Syntax:

 SLOPE(arrayX, arrayY)

class
Substitute

An implementation of the SUBSTITUTE function:

 Substitutes text in a text string with new text, some number of times.

class
Subtotal

Implementation for the Excel function SUBTOTAL

 Syntax :

  SUBTOTAL ( functionCode, ref1, ref2 ... )

      functionCode(1-11) Selects the underlying aggregate function to be used (see table below)
      ref1, ref2 ...

class
Sumif

Implementation for the Excel function SUMIF

 Syntax :

  SUMIF ( range, criteria, sum_range )

      rangeThe range over which criteria is applied.

class
Sumproduct

Implementation for the Excel function SUMPRODUCT

 Syntax :

  SUMPRODUCT ( array1[, array2[, array3[, ...]]])

class
Sumx2my2

Implementation of Excel function SUMX2MY2()

 Calculates the sum of differences of squares in two arrays of the same size.

class
Sumx2py2

Implementation of Excel function SUMX2PY2()

 Calculates the sum of squares in two arrays of the same size.

class
Sumxmy2

Implementation of Excel function SUMXMY2()

 Calculates the sum of squares of differences between two arrays of the same size.

class
T

Implementation of Excel T() function

 If the argument is a text or error value it is returned unmodified.

class
TextFunction

class
TimeFunc

Implementation for the Excel function TIME

class
Today

Implementation of Excel TODAY() Function

class
Value

Implementation for Excel VALUE() function.

class
Vlookup

Implementation of the VLOOKUP() function.

class
WeekdayFunc

Implementation for the Excel function WEEKDAY

class
WeekNum

Implementation for Excel WeekNum() function.

class
XYNumericFunction

Fields in org.apache.poi.ss.formula.functions declared as Function

Modifier and Type
Field and Description

static Function
NumericFunction.ABS

static Function
NumericFunction.ACOS

static Function
NumericFunction.ACOSH

static Function
BooleanFunction.AND

static Function
NumericFunction.ASIN

static Function
NumericFunction.ASINH

static Function
NumericFunction.ATAN

static Function
NumericFunction.ATAN2

static Function
NumericFunction.ATANH

static Function
AggregateFunction.AVEDEV

static Function
AggregateFunction.AVERAGE

static Function
NumericFunction.CEILING

static Function
TextFunction.CHAR

Returns the character specified by a number.

static Function
TextFunction.CLEAN

An implementation of the CLEAN function:
 In Excel, the Clean function removes all non-printable characters from a string.

static Function
NumericFunction.COMBIN

static Function
TextFunction.CONCATENATE

static Function
NumericFunction.COS

static Function
NumericFunction.COSH

static Function
CalendarFieldFunction.DAY

static Function
NumericFunction.DEGREES

static Function
AggregateFunction.DEVSQ

static Function
NumericFunction.DOLLAR

static Function
TextFunction.EXACT

static Function
NumericFunction.EXP

static Function
NumericFunction.FACT

static Function
BooleanFunction.FALSE

static Function
TextFunction.FIND

Implementation of the FIND() function.

static Function
NumericFunction.FLOOR

static Function
FinanceFunction.FV

static Function
CalendarFieldFunction.HOUR

static Function
WeekdayFunc.instance

static Function
DateFunc.instance

static Function
NumericFunction.INT

static Function
LogicalFunction.ISBLANK

static Function
LogicalFunction.ISERROR

static Function
LogicalFunction.ISLOGICAL

static Function
LogicalFunction.ISNA

Implementation for Excel ISNA() function.

static Function
LogicalFunction.ISNONTEXT

static Function
LogicalFunction.ISNUMBER

static Function
LogicalFunction.ISREF

static Function
LogicalFunction.ISTEXT

static Function
AggregateFunction.LARGE

static Function
TextFunction.LEFT

static Function
TextFunction.LEN

static Function
NumericFunction.LN

static Function
NumericFunction.LOG

static Function
NumericFunction.LOG10

static Function
TextFunction.LOWER

static Function
AggregateFunction.MAX

static Function
MinaMaxa.MAXA

static Function
AggregateFunction.MEDIAN

static Function
TextFunction.MID

An implementation of the MID function

 MID returns a specific number of
 characters from a text string, starting at the specified position.

static Function
AggregateFunction.MIN

static Function
MinaMaxa.MINA

static Function
CalendarFieldFunction.MINUTE

static Function
NumericFunction.MOD

static Function
CalendarFieldFunction.MONTH

static Function
BooleanFunction.NOT

static Function
FinanceFunction.NPER

static Function
BooleanFunction.OR

static Function
AggregateFunction.PERCENTILE

static Function
NumericFunction.PI

static Function
FinanceFunction.PMT

static Function
NumericFunction.POISSON

static Function
NumericFunction.POWER

static Function
AggregateFunction.PRODUCT

static Function
FinanceFunction.PV

static Function
NumericFunction.RADIANS

static Function
NumericFunction.RAND

static Function
TextFunction.RIGHT

static Function
NumericFunction.ROUND

static Function
NumericFunction.ROUNDDOWN

static Function
NumericFunction.ROUNDUP

static Function
TextFunction.SEARCH

Implementation of the FIND() function.

static Function
CalendarFieldFunction.SECOND

static Function
NumericFunction.SIGN

static Function
NumericFunction.SIN

static Function
NumericFunction.SINH

static Function
AggregateFunction.SMALL

static Function
NumericFunction.SQRT

static Function
AggregateFunction.STDEV

static Function
AggregateFunction.SUM

static Function
AggregateFunction.SUMSQ

static Function
NumericFunction.TAN

static Function
NumericFunction.TANH

static Function
TextFunction.TEXT

An implementation of the TEXT function

 TEXT returns a number value formatted with the given number formatting string.

static Function
TextFunction.TRIM

An implementation of the TRIM function:
 Removes leading and trailing spaces from value if evaluated operand
  value is string.

static Function
BooleanFunction.TRUE

static Function
NumericFunction.TRUNC

static Function
TextFunction.UPPER

static Function
AggregateFunction.VAR

static Function
AggregateFunction.VARP

static Function
CalendarFieldFunction.YEAR

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

                Copyright 2014 The Apache Software Foundation or
        its licensors, as applicable.


text:
@implementation GKUEvent

+ (instancetype)eventWithName:(NSString *)name
{
    return [[self alloc] initWithName:name];
}

- (instancetype)initWithName:(NSString *)name
{
    self = [super init];
    if (self)
    {
        _name = name;
    }
    return self;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"%@: name - %@", [super description], _name];
}

@end


text:
+++
draft = false
author = "theobutler"
description = "Last week's Pony news, reported this week."
categories = [
    "Last Week in Pony",
]
title = "Last Week in Pony - September 1, 2019"
date = "2019-09-01T13:52:07+02:00"
+++
_Last Week In Pony_ is a weekly blog post to catch you up on the latest news for the Pony programming language. To learn more about Pony check out [our website](https://ponylang.io), our Twitter account [@ponylang](https://twitter.com/ponylang), or our [Zulip community](https://ponylang.zulipchat.com).

Got something you think should be featured? There's a GitHub issue for that! Add a comment to the [open "Last Week in Pony" issue](https://github.com/ponylang/ponylang.github.io/issues?q=is%3Aissue+is%3Aopen+label%3Alast-week-in-pony).

<!--more-->

## Items of note

- Pony 0.31.0 was [released](https://www.ponylang.io/blog/2019/08/0.31.0-released/) on Saturday. There's one small breaking change. There aren't any major bug fixes or security patches so feel free to upgrade at your leisure.

    [Release notes](https://www.ponylang.io/blog/2019/08/0.31.0-released/)

- Recording of the August 27, 2019 Pony developer sync is available [here](https://sync-recordings.ponylang.io/r/2019_08_27.m4a).

- Sylvan Clebsch, originator of Pony, will be joining Sean T. Allen to give an all-day Pony tutorial at CodeMesh in London this November. [Tickets are still available](https://codesync.global/conferences/code-mesh-ldn/tutorial/?utm_source=Twitter&utm_medium=Code%20Sync&utm_campaign=Code%20Mesh%20LDN%2019/#18oo-programming-with-pony).

- Andrew Turley proposed a [Pony unsession at Strange Loop](https://github.com/strangeloop/StrangeLoop2019/wiki/Unsessions#getting-in-the-saddle-with-the-pony-programming-language). If you're going to Strange Loop and you'd like to see this happen, please add your name to the "interested" section.

- Andrew Turley wrote a [little program](https://github.com/aturley/pony-sync-helper) that grabs all of the recently updated issues in the ponylang org on GitHub and creates a little report for the sync. If you're interested in seeing how to do things like use the GitHub HTTP API from Pony you can check it out.

## RFCs

Interested in making a change, or keeping up with changes to Pony? Check out the [RFC repo](https://github.com/ponylang/rfcs). Contributors welcome!

### Ready For Vote

- [Pass LLVM command line arguments to ponyc](https://github.com/ponylang/rfcs/pull/153)


text:
using std::string;

namespace Glucose {

enum class NeuroSolverMode { NONE, NEURO, RAND };

NeuroSolverMode neuro_parse_solver_mode(std::string const & mode);

struct NeuroSATConfig {
    NeuroSolverMode mode{NeuroSolverMode::NONE};
    string          server{"NULL"};
    unsigned        timeout_s{UINT32_MAX};
    float           n_secs_pause{0.0};
    float           n_secs_pause_inc{0.0};
    unsigned        max_lclause_size{0};
    unsigned        max_n_nodes_cells{0};
    float           itau{0.0};
    float           scale{0.0};
    bool            call_if_too_big{false};
    string          neuro_outfile{"out"};
};

struct NeuroSATState {
    std::unique_ptr<neurosat::NeuroSATServer::Stub> stub;
    unsigned n_calls{0};
    unsigned n_fails{0};
    float    n_secs_gpu{0.0};
    clock_t  t_start{};
    clock_t  t_next{};
    float    n_secs_next_pause{0.0};
    bool     has_called{false};
    bool     original_too_big{false};

    float n_secs_user() const { return (double) (clock() - t_start) / CLOCKS_PER_SEC; }
};

}