text:
package org.jivesoftware.openfire.net;

import org.jivesoftware.openfire.spi.ConnectionConfiguration;
import org.jivesoftware.openfire.spi.EncryptionArtifactFactory;
import org.jivesoftware.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import java.nio.ByteBuffer;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.Arrays;

/**
 * Creates and initializes the SSLContext instance to use to secure the plain connection. This
 * class is also responsible for encoding and decoding the encrypted data and place it into
 * the corresponding the {@link ByteBuffer}.
 *
 * @author Artur Hefczyc
 * @author Hao Chen
 */
public class TLSWrapper {

    private static final Logger Log = LoggerFactory.getLogger(TLSWrapper.class);

    /*
     * Enables logging of the SSLEngine operations.
     */
    private boolean logging = false;

    private SSLEngine tlsEngine;
    private SSLEngineResult tlsEngineResult;

    private int netBuffSize;
    private int appBuffSize;

    public TLSWrapper(ConnectionConfiguration configuration, boolean clientMode ) {

        try
        {
            final EncryptionArtifactFactory factory = new EncryptionArtifactFactory( configuration );
            if ( clientMode )
            {
                tlsEngine = factory.createClientModeSSLEngine();
            }
            else
            {
                tlsEngine = factory .createServerModeSSLEngine();
            }

            final SSLSession sslSession = tlsEngine.getSession();

            netBuffSize = sslSession.getPacketBufferSize();
            appBuffSize = sslSession.getApplicationBufferSize();
        }
        catch ( NoSuchAlgorithmException | KeyManagementException | KeyStoreException | UnrecoverableKeyException ex )
        {
            Log.error("TLSHandler startup problem. SSLContext initialisation failed.", ex );
        }
    }

    public int getNetBuffSize() {
        return netBuffSize;
    }

    public int getAppBuffSize() {
        return appBuffSize;
    }

    /**
     * Returns whether unwrap(ByteBuffer, ByteBuffer) will accept any more inbound data messages and
     * whether wrap(ByteBuffer, ByteBuffer) will produce any more outbound data messages.
     *
     * @return true if the TLSHandler will not consume anymore network data and will not produce any
     *         anymore network data.
     */
    public boolean isEngineClosed() {
        return (tlsEngine.isOutboundDone() && tlsEngine.isInboundDone());
    }

    public void enableLogging(boolean logging) {
        this.logging = logging;
    }

    /**
     * Attempts to decode SSL/TLS network data into a subsequence of plaintext application data
     * buffers. Depending on the state of the TLSWrapper, this method may consume network data
     * without producing any application data (for example, it may consume handshake data.)
     *
     * If this TLSWrapper has not yet started its initial handshake, this method will automatically
     * start the handshake.
     *
     * @param net a ByteBuffer containing inbound network data
     * @param app a ByteBuffer to hold inbound application data
     * @return a ByteBuffer containing inbound application data
     * @throws SSLException A problem was encountered while processing the data that caused the
     *             TLSHandler to abort.
     */
    public ByteBuffer unwrap(ByteBuffer net, ByteBuffer app) throws SSLException {
        ByteBuffer out = app;
        out = resizeApplicationBuffer(out);// guarantees enough room for unwrap

        // Record a hex dump of the buffer, but only when logging on level 'debug'.
        // Create the dump before the buffer is being passed to tlsEngine, to ensure
        // that the original content of the buffer is logged.
        String hexDump = null;
        if ( Log.isDebugEnabled() )
        {
            final ByteBuffer bb = net.duplicate();
            final byte[] data = Arrays.copyOf( bb.array(), bb.limit() );
            hexDump = StringUtils.encodeHex( data );
        }

        try {
            tlsEngineResult = tlsEngine.unwrap( net, out );
        } catch ( SSLException e ) {
            if ( e.getMessage().startsWith( "Unsupported record version Unknown-" ) ) {
                Log.debug( "Buffer that wasn't TLS: {}", hexDump );
                throw new SSLException( "We appear to have received plain text data where we expected encrypted data. A common cause for this is a peer sending us a plain-text error message when it shouldn't send a message, but close the socket instead).", e );
            }
            else {
                throw e;
            }
        }
        log("server unwrap: ", tlsEngineResult);
        if (tlsEngineResult.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
            // If the result indicates that we have outstanding tasks to do, go
            // ahead and run them in this thread.
            doTasks();
        }
        return out;
    }

    /**
     * Attempts to encode a buffer of plaintext application data into TLS network data. Depending on
     * the state of the TLSWrapper, this method may produce network data without consuming any
     * application data (for example, it may generate handshake data).
     *
     * If this TLSWrapper has not yet started its initial handshake, this method will automatically
     * start the handshake.
     *
     * @param app a ByteBuffer containing outbound application data
     * @param net a ByteBuffer to hold outbound network data
     * @throws SSLException A problem was encountered while processing the data that caused the
     *             TLSWrapper to abort.
     */
    public void wrap(ByteBuffer app, ByteBuffer net) throws SSLException {
        tlsEngineResult = tlsEngine.wrap(app, net);
        log("server wrap: ", tlsEngineResult);
        if (tlsEngineResult.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
            // If the result indicates that we have outstanding tasks to do, go
            // ahead and run them in this thread.
            doTasks();
        }
    }

    /**
     * Signals that no more outbound application data will be sent on this TLSHandler.
     *
     * @throws SSLException never
     */
    public void close() throws SSLException {
        // Indicate that application is done with engine
        tlsEngine.closeOutbound();
    }

    /**
     * Returns the current status for this TLSHandler.
     *
     * @return the current TLSStatus
     */
    public TLSStatus getStatus() {
        if (tlsEngineResult != null && tlsEngineResult.getStatus() == Status.BUFFER_UNDERFLOW) {
            return TLSStatus.UNDERFLOW;
        } else {
            if (tlsEngineResult != null && tlsEngineResult.getStatus() == Status.CLOSED) {
                return TLSStatus.CLOSED;
            } else {
                switch (tlsEngine.getHandshakeStatus()) {
                case NEED_WRAP:
                    return TLSStatus.NEED_WRITE;
                case NEED_UNWRAP:
                    return TLSStatus.NEED_READ;
                default:
                    return TLSStatus.OK;
                }
            }
        }
    }

    private ByteBuffer resizeApplicationBuffer(ByteBuffer app) {
        // TODO Creating new buffers and copying over old one may not scale and may even be a
        // security risk. Consider using views. Thanks to Noah for the tip.
        if (app.remaining() < appBuffSize) {
            ByteBuffer bb = ByteBuffer.allocate(app.capacity() + appBuffSize);
            app.flip();
            bb.put(app);
            return bb;
        } else {
            return app;
        }
    }

    /*
      * Do all the outstanding handshake tasks in the current Thread.
      */
    private SSLEngineResult.HandshakeStatus doTasks() {

        Runnable runnable;

        /*
           * We could run this in a separate thread, but do in the current for now.
           */
        while ((runnable = tlsEngine.getDelegatedTask()) != null) {
            runnable.run();
        }
        return tlsEngine.getHandshakeStatus();
    }

    /*
      * Logging code
      */
    private boolean resultOnce = true;

    private void log(String str, SSLEngineResult result) {
        if (!logging) {
            return;
        }
        if (resultOnce) {
            resultOnce = false;
            Log.info("The format of the SSLEngineResult is: \n"
                    + "\t\"getStatus() / getHandshakeStatus()\" +\n"
                    + "\t\"bytesConsumed() / bytesProduced()\"\n");
        }
        HandshakeStatus hsStatus = result.getHandshakeStatus();
        Log.info(str + result.getStatus() + "/" + hsStatus + ", " + result.bytesConsumed() + "/"
                + result.bytesProduced() + " bytes");
        if (hsStatus == HandshakeStatus.FINISHED) {
            Log.info("\t...ready for application data");
        }
    }

    protected SSLEngine getTlsEngine() {
        return tlsEngine;
    }
}


text:
class ForVar {
	public static void main(String args[]) {
		int sum = 0;
		int fact = 1;

		// compute the factorial of the numbers through 5
		for(int i = 1; i <= 5; i++) {
			sum += i; // i is known throughout the loop
			fact *= i;
		}

		// but, i is not known here.

		System.out.println("Sum is " + sum);
		System.out.println("Factorial is " + fact);
	}
}

redpajama_set_name: RedPajamaGithub


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
include("../db/db.php");

$name = $_POST["name"];
$sex = $_POST["sex"];
$company = $_POST["company"];
$cellphone = $_POST["cellphone"];
$phone = $_POST["phone"];
$fax = $_POST["fax"];
$country = $_POST["country"];
$englishname = $_POST["englishname"];
$nickname = $_POST["nickname"];
$email = $_POST["email"];
$address = $_POST["address"];
$site = $_POST["site"];
$line = $_POST["line-id"];
$birthday = $_POST["birthday"];
$memo = $_POST["memo"];

	$sql = "INSERT INTO `crm_customers` (`name`, `phone`, `cellphone`, `fax`, `address`, `email`, `website`, `line`, `englishname`, `nickname`, `country`, `company`, `sex`, `birthday`, `memo`) VALUES ('$name', '$phone', '$cellphone', '$fax', '$address', '$email', '$site', '$line', '$englishname', '$englishname', '$country', '$company', '$sex', '$birthday', '$memo');";

	$result = mysql_query($sql);

	if($result){
                echo "<script>alert('新增成功');location.href='javascript:history.go(-1)';</script>";
        }else{
                echo "<script>alert('QQ\\n好像失敗了');location.href='javascript:history.go(-1)';</script>";
                //echo $sql;
                //echo mysql_error();
        }

?>


text:
package doobie.util

import shapeless._, shapeless.test._, shapeless.record._
import doobie.imports._
import org.specs2.mutable.Specification

object compositespec extends Specification {

  case class Woozle(a: (String, Int), b: Int :: String :: HNil, c: Boolean)

  case class LenStr1(n: Int, s: String)

  case class LenStr2(n: Int, s: String)
  object LenStr2 {
    implicit val LenStrMeta =
      Meta[String].nxmap[LenStr2](s => LenStr2(s.length, s), _.s)
  }

  "Composite" should {

    "exist for some fancy types" in {
      Composite[Int]
      Composite[(Int, Int)]
      Composite[(Int, Int, String)]
      Composite[(Int, (Int, String))]
      Composite[Woozle]

      // https://github.com/tpolecat/doobie/pull/126 was reverted because these
      // derivations were failing with SOE
      Composite[(Woozle, String)]
      Composite[(Int, Woozle :: Woozle :: String :: HNil)]

      true
    }

    "exist for shapeless record types" in {

      type DL = (Double, Long)
      type A = Record.`'foo -> Int, 'bar -> String, 'baz -> DL, 'quz -> Woozle`.T

      Composite[A]
      Composite[(A, A)]

      true
    }

    "select multi-column instance by default" in {
      Composite[LenStr1].length must_== 2
    }

    "select 1-column instance when available" in {
      Composite[LenStr2].length must_== 1
    }

    "work for products of ludicrous size (128)" in {
      Composite[
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int ::
        Int :: Int :: Int :: Int :: Int :: Int :: Int :: Int :: HNil]
      true
    }

    "work for specific example from #217" in {
      trait LocalDateTime
      implicit val MetaLocalDateTime: Meta[LocalDateTime] = null
      Composite[
        Option[String] :: Option[String] :: Option[String] :: Option[LocalDateTime] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[LocalDateTime] :: Option[LocalDateTime] ::
        Option[LocalDateTime] :: Option[LocalDateTime] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[String] :: Option[BigDecimal] ::
        Option[String] :: Option[BigDecimal] :: Option[BigDecimal] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[BigDecimal] :: Option[BigDecimal] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[String] :: Option[String] ::
        Option[String] :: Option[String] :: Option[BigDecimal] :: Option[BigDecimal] ::
        Option[String] :: HNil]
      true
    }

  }

}


text:
public class Member {
    private int memberID;
    private String fName, lName;
    private double donationAmount;

    public Member() {
        this(1000, "John", "Smith", 250.0);
    }
    public Member(String fn, String ln) {
        this(1001, fn, ln, 500.0);
    }
    public Member(int memberID, String fName, String lName, double donationAmount) {
        this.memberID = memberID;
        this.fName = fName;
        this.lName = lName;
        this.donationAmount= donationAmount;
    }

    public void displayMemberInfo(){
        System.out.println("MemberID          = " + memberID);
        System.out.println("Member First Name = " + fName);
        System.out.println("Member Last Name  = " + lName);
        System.out.println("Member Donation   = " + donationAmount);
    }

    @Override
    public String toString(){
        return ("MemberID          = " + memberID +
                "\nMember First Name = " + fName +
                "\nMember Last Name  = " + lName +
                "\nMember Donation   = " + donationAmount);
    }
}


text:
<?php

namespace Go\Zend\Framework\Tests\Advice;

/**
 * @package Go\Zend\Framework\Tests\Advice
 */
class TestAdvice
{
    public function getTest($parameter)
    {
    }
}


text:
- make transform-methods relative as default (breaking change)
- added `morph()` method to `SVG.PathArray` -> __TODO!__
- added `'random'` option and `randomize()` method to `SVG.Color` -> __TODO!__
- added `parents()` method to get an array of all parenting elements -> __TODO!__
- added support for css selectors with the `parent()` method -> __TODO!__
- added `enqueue()` method to `SVG.FX` -> __TODO!__
- added `ungroup()` method -> __TODO!__ [thanks to Peter Uithoven]
- fixed a bug in clipping and masking where empty nodes persists after removal -> __TODO!__
- fixed a bug in IE11 with `mouseenter` and `mouseleave` -> __TODO!__
- added `precision()` method to round numeric element attributes -> __TODO!__
- added specs for `SVG.FX` -> __TODO!__

# 2.1.1

- added custom context binding to event callback (default is the element the event is binded to)

# 2.1.0 (20/09/2015)

- added transform to pattern and gradients (#383)
- fixed clone of textnodes (#369)
- fixed transformlists in IE (#372)
- fixed typo that leads to broken gradients (#370)
- fixed animate radius for circles (#367)

# 2.0.2 (22/06/2015)

- Fixed zoom consideration in circle and ellipse

# 2.0.1 (21/06/2015)

- fixed bug with `doc()` which always should return root svg
- removed target reference from use which caused bugs in `dmove()` and `use()` with external file
- added possibility to remove all events from a certain namespace
- fixed bug in `SVG.FX` when animating with `plot()`
- removed scale consideration in `move()` duo to incompatibilities with other move-functions e.g. in `SVG.PointArray`

# 2.0.0 (11/06/2015)

- implemented an SVG adoption system to be able to manipulate existing SVG's not created with svg.js
- changed `parent` reference on elements to `parent()` method
- using `CustomEvent` instead of `Event` to be able to fire events with a `detail` object [thanks @Fuzzyma]
- added polyfill for IE9 and IE10 custom events [thanks @Fuzzyma]
- added DOM query selector with the `select()` method globally or on parent elements
- added the intentionally neglected `SVG.Circle` element
- fixed bug in `radius()` method when `y` value equals `0`
- renamed `SVG.TSpan` class to `SVG.Tspan` to play nice with the adoption system
- added `rx()` and `ry()` to `SVG.Rect`, `SVG.Circle`, `SVG.Ellispe` and `SVG.FX`
- changed `array` reference to `array()` method on `SVG.Polyline`, `SVG.Polygon` and `SVG.Path`
- completely reworked `clone()` method to use the adoption system
- added support to clone manually built text elements
- added `svg.wiml.js` plugin to plugins list
- added `ctm()` method to for matrix-centric transformations
- added `morph()` method to `SVG.Matrix`
- added support for new matrix system to `SVG.FX`
- completely reworked transformations to be chainable and more true to their nature
- changed `lines` reference to `lines()` on `SVG.Text`
- changed `track` reference to `track()` on `SVG.Text`
- changed `textPath` reference to `textPath()` on `SVG.Text`
- added raw svg import functionality with the `svg()` method
- reworked sup-pixel offset implementation to be more compact
- added `native()` method to elements and matrix to get to the native api
- added `untransform()` method to remove all transformations
- switched from Ruby's `rake` to Node's `gulp` for building [thanks to Alex Ewerlöf]
- added coding style description to README
- changed `to()` method to `at()` method in `SVG.FX`
- added reverse functionality for animations
- documented the `situation` object in `SVG.FX`
- renamed `SVG.SetFX` to `SVG.FX.Set`
- added distinction between relative and absolute matrix transformations
- implemented the `element()` method using the `SVG.Bare` class to create elements that are not described by SVG.js
- removed `SVG.Symbol` but kept the `symbol()` method using the new `element()` method
- reworked `SVG.Number` to return new instances with calculations rather than itself
- added `w` and `h` properties as shorthand for `width` and `height` to `SVG.BBox`
- added `SVG.TBox` to get a bounding box that is affected by transformation values
- reworked animatable matrix rotations
- fixed a bug where events are not detached properly
- added event-based or complete detaching of event listeners in `off()` method

# 1.0.0-rc.9 (17/06/2014)

- added `SVG.Marker`
- added `SVG.Symbol`
- added `first()` and `last()` methods to `SVG.Set`
- added `length()` method to `SVG.Text` and `SVG.TSpan` to calculate total text length
- `SVG.get()` will now also fetch elements with a `xlink:href="#elementId"` or `url(#elementId)` value given
- added `reference()` method to get referenced elements from a given attribute value
- fixed infinite loop in viewbox when element has a percentage width / height [thanks @shabegger]

# 1.0.0-rc.8 (12/06/2014)

- fixed bug in `SVG.off`
- fixed offset by window scroll position in `rbox()` [thanks @bryhoyt]

# 1.0.0-rc.7 (11/06/2014)

- calling `after()` when calling `stop(true)` (fulfill flag) [thanks @vird]
- added `classes()`, `hasClass()`, `addClass()`, `removeClass()` and `toggleClass()` [thanks @pklingem]
- fixed a bug where `Element#style()` would not save empty values in IE11 [thanks @Shtong]
- fixed `SVG is not defined error` [thanks @anvaka]
- fixed a bug in `move()`on text elements with a string based value
- binding events listeners to svg.js instance
- text element fires `rebuild` event whenever the `rebuild()` method is called
- fix for `text()` method on text element when acting as getter [thanks @Lochemage]
- fix in `style()` method with a css string [thanks @TobiasHeckel]

# 1.0.0-rc.6 (03/03/2014)

- fine-tuned text element positioning
- fixed a bug in text `dy()` method
- added `leading()` method to `SVG.FX`
- removed internal representation for `style`
- added `reverse()` method to `SVG.Array` (and thereby also to `SVG.PointArray` and `SVG.PathArray`)
- added `fulfill` option to `stop()` method in `SVG.FX` to finalise animations
- calling `at()` method directly on morphable svg.js instances in `SVG.FX` module
- moved most `_private` methods to local named functions
- moved helpers to a separate file
- added more output values to `bbox()` and `rbox()` methods

# 1.0.0-rc.5 (14/02/2014)

- added `plain()` method to `SVG.Text` element to add plain text content, without tspans
- added `plain()` method to parent elements to create a text element without tspans
- updated `SVG.TSpan` to accept nested tspan elements, not unlike the `text()` method in `SVG.Text`
- removed the `relative()` method in favour of `dx()`, `dy()` and `dmove()`
- switched form objects to arrays in `SVG.PathArray` for compatibility with other libraries and better performance on parsing and rendering (up-to 48% faster than 1.0.0-rc.4)
- refined docs on element-specific methods and `SVG.PathArray` structure
- added `build()` to enable/disable build mode
- removed verbose style application to tspans
- reworked `leading()` implementation to be more font-size "aware"
- refactored the `attr` method on `SVG.Element`
- applied Helvetica as default font
- building `SVG.FX` class with `SVG.invent()` function

# 1.0.0-rc.4 (04/02/2014)

- switched to `MAJOR`.`MINOR`.`PATCH` versioning format to play nice with package managers
- made svg.pattern.js part of the core library
- automatic pattern creation by passing an image url or instance as `fill` attribute on elements
- added `loaded()` method to image tag
- fix in `animate('=').to()`
- added `pointAt()` method to `SVG.Path`, wrapping the native `getPointAtLength()`
- moved `length()` method to sugar module
- fix for arcs in patharray `toString()` method [thanks @dotnetCarpenter]

# v1.0rc3 (03/02/2014)

- fix for html-less documents
- added the `SVG.invent` function to ease invention of new elements
- using `SVG.invent` to generate core shapes as well for leaner code
- added second values for `animate('2s')`
- fix for arcs in patharray `toString()` method
- added `length()` mehtod to path, wrapping the native `getTotalLength()`

# v1.0rc2 (01/02/2014)

- added `index()` method to `SVG.Parent` and `SVG.Set`
- modified `cx()` and `cy()` methods on elements with native `x`, `y`, `width` and `height` attributes for better performance
- added `morph()` and `at()` methods to `SVG.Number` for unit morphing

# v1.0rc1 (31/01/2014)

- added `SVG.PathArray` for real path transformations
- removed `unbiased` system for paths
- enabled proportional resizing on `size()` method with `null` for either `width` or `height` values
- moved data module to separate file
- `data()` method now accepts object for for multiple key / value assignments
- added `bbox()` method to `SVG.Set`
- added `relative()` method for moves relative to the current position
- added `morph()` and `at()` methods to `SVG.Color` for color morphing

# v0.38 (28/01/2014)

- added `loop()` method to `SVG.FX`
- switched from `setInterval` to `requestAnimFrame` for animations

# v0.37 (26/01/2014)

- added `get()` to `SVG.Set`
- moved `SVG.PointArray` to a separate file

# v0.36 (25/01/2014)

- added `linkTo()`, `addTo()` and `putIn()` methods on `SVG.Element`
- provided more detailed documentation on parent elements

# v0.35 (23/01/2014)

- added `SVG.A` element with the `link()`

# v0.34 (23/01/2014)

- added `pause()` and `play()` to `SVG.FX`
- storing animation values in `situation` object

# v0.33 (22/01/2014)

- added `has()` method to `SVG.Set`
- added `width()` and `height()` as setter and getter methods on all shapes
- moved sub-pixel offset fix to be an optional method (e.g. `SVG('drawing').fixSubPixelOffset()`)
- added `replace()` method to elements
- added `radius()` method to `SVG.Rect` and `SVG.Ellipse`
- added reference to parent node in defs
- merged plotable.js and path.js

# v0.32

- added library to [cdnjs](http://cdnjs.com)


text:
package com.github.dlisin.graylog.plugin.output.email;

import org.graylog2.plugin.Message;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;

public class MessageGroupTest {
  @Test
  public void testCreateWithoutFields() throws Exception {
    Message message = createMessage("zeus", "mysql");
    MessageGroup group = new MessageGroup(Collections.emptyList(), message);

    assertThat(group.getGroupByFields()).isEmpty();
  }

  @Test
  public void testCreateWithSingleField() throws Exception {
    Message message = createMessage("zeus", "mysql");
    MessageGroup group = new MessageGroup(Collections.singletonList("host"), message);

    assertThat(group.getGroupByFields()).containsOnly(entry("host", "zeus"));
  }

  @Test
  public void testCreateWithMultipleFields() throws Exception {
    Message message = createMessage("zeus", "mysql");
    MessageGroup group = new MessageGroup(Arrays.asList("host", "service"), message);

    assertThat(group.getGroupByFields()).containsOnly(entry("host", "zeus"), entry("service", "mysql"));
  }

  @Test
  public void testEquals() throws Exception {
    Message message1 = createMessage("zeus", "mysql");
    MessageGroup group1 = new MessageGroup(Arrays.asList("host", "service"), message1);

    Message message2 = createMessage("zeus", "mysql");
    MessageGroup group2 = new MessageGroup(Arrays.asList("host", "service"), message2);

    Message message3 = createMessage("zeus", "nginx");
    MessageGroup group3 = new MessageGroup(Arrays.asList("host", "service"), message3);

    assertThat(group1).isEqualTo(group2);
    assertThat(group1).isNotEqualTo(group3);

    assertThat(group2).isEqualTo(group1);
    assertThat(group2).isNotEqualTo(group3);

    assertThat(group3).isNotEqualTo(group1);
    assertThat(group3).isNotEqualTo(group2);
  }

  private Message createMessage(final String host, final String service) {
    return MessageMock.createMessage(new HashMap<String, Object>() {{
      put("host", host);
      put("service", service);
    }});
  }
}


text:
#pragma once
#include <aws/batch/Batch_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/batch/model/EFSTransitEncryption.h>
#include <aws/batch/model/EFSAuthorizationConfig.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Batch
{
namespace Model
{

  /**
   *
This is used when you're using an Amazon Elastic File System file system for
   * job storage. For more information, see Amazon
   * EFS Volumes in the Batch User Guide.

See Also:
   AWS
   * API Reference

   */
  class AWS_BATCH_API EFSVolumeConfiguration
  {
  public:
    EFSVolumeConfiguration();
    EFSVolumeConfiguration(Aws::Utils::Json::JsonView jsonValue);
    EFSVolumeConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The Amazon EFS file system ID to use.

     */
    inline const Aws::String& GetFileSystemId() const{ return m_fileSystemId; }

    /**
     *
The Amazon EFS file system ID to use.

     */
    inline bool FileSystemIdHasBeenSet() const { return m_fileSystemIdHasBeenSet; }

    /**
     *
The Amazon EFS file system ID to use.

     */
    inline void SetFileSystemId(const Aws::String& value) { m_fileSystemIdHasBeenSet = true; m_fileSystemId = value; }

    /**
     *
The Amazon EFS file system ID to use.

     */
    inline void SetFileSystemId(Aws::String&& value) { m_fileSystemIdHasBeenSet = true; m_fileSystemId = std::move(value); }

    /**
     *
The Amazon EFS file system ID to use.

     */
    inline void SetFileSystemId(const char* value) { m_fileSystemIdHasBeenSet = true; m_fileSystemId.assign(value); }

    /**
     *
The Amazon EFS file system ID to use.

     */
    inline EFSVolumeConfiguration& WithFileSystemId(const Aws::String& value) { SetFileSystemId(value); return *this;}

    /**
     *
The Amazon EFS file system ID to use.

     */
    inline EFSVolumeConfiguration& WithFileSystemId(Aws::String&& value) { SetFileSystemId(std::move(value)); return *this;}

    /**
     *
The Amazon EFS file system ID to use.

     */
    inline EFSVolumeConfiguration& WithFileSystemId(const char* value) { SetFileSystemId(value); return *this;}

    /**
     *
The directory within the Amazon EFS file system to mount as the root
     * directory inside the host. If this parameter is omitted, the root of the Amazon
     * EFS volume is used instead. Specifying / has the same effect as
     * omitting this parameter. The maximum length is 4,096 characters.

     *
If an EFS access point is specified in the authorizationConfig,
     * the root directory parameter must either be omitted or set to /,
     * which enforces the path set on the Amazon EFS access point.

     */
    inline const Aws::String& GetRootDirectory() const{ return m_rootDirectory; }

    /**
     *
The directory within the Amazon EFS file system to mount as the root
     * directory inside the host. If this parameter is omitted, the root of the Amazon
     * EFS volume is used instead. Specifying / has the same effect as
     * omitting this parameter. The maximum length is 4,096 characters.

     *
If an EFS access point is specified in the authorizationConfig,
     * the root directory parameter must either be omitted or set to /,
     * which enforces the path set on the Amazon EFS access point.

     */
    inline bool RootDirectoryHasBeenSet() const { return m_rootDirectoryHasBeenSet; }

    /**
     *
The directory within the Amazon EFS file system to mount as the root
     * directory inside the host. If this parameter is omitted, the root of the Amazon
     * EFS volume is used instead. Specifying / has the same effect as
     * omitting this parameter. The maximum length is 4,096 characters.

     *
If an EFS access point is specified in the authorizationConfig,
     * the root directory parameter must either be omitted or set to /,
     * which enforces the path set on the Amazon EFS access point.

     */
    inline void SetRootDirectory(const Aws::String& value) { m_rootDirectoryHasBeenSet = true; m_rootDirectory = value; }

    /**
     *
The directory within the Amazon EFS file system to mount as the root
     * directory inside the host. If this parameter is omitted, the root of the Amazon
     * EFS volume is used instead. Specifying / has the same effect as
     * omitting this parameter. The maximum length is 4,096 characters.

     *
If an EFS access point is specified in the authorizationConfig,
     * the root directory parameter must either be omitted or set to /,
     * which enforces the path set on the Amazon EFS access point.

     */
    inline void SetRootDirectory(Aws::String&& value) { m_rootDirectoryHasBeenSet = true; m_rootDirectory = std::move(value); }

    /**
     *
The directory within the Amazon EFS file system to mount as the root
     * directory inside the host. If this parameter is omitted, the root of the Amazon
     * EFS volume is used instead. Specifying / has the same effect as
     * omitting this parameter. The maximum length is 4,096 characters.

     *
If an EFS access point is specified in the authorizationConfig,
     * the root directory parameter must either be omitted or set to /,
     * which enforces the path set on the Amazon EFS access point.

     */
    inline void SetRootDirectory(const char* value) { m_rootDirectoryHasBeenSet = true; m_rootDirectory.assign(value); }

    /**
     *
The directory within the Amazon EFS file system to mount as the root
     * directory inside the host. If this parameter is omitted, the root of the Amazon
     * EFS volume is used instead. Specifying / has the same effect as
     * omitting this parameter. The maximum length is 4,096 characters.

     *
If an EFS access point is specified in the authorizationConfig,
     * the root directory parameter must either be omitted or set to /,
     * which enforces the path set on the Amazon EFS access point.

     */
    inline EFSVolumeConfiguration& WithRootDirectory(const Aws::String& value) { SetRootDirectory(value); return *this;}

    /**
     *
The directory within the Amazon EFS file system to mount as the root
     * directory inside the host. If this parameter is omitted, the root of the Amazon
     * EFS volume is used instead. Specifying / has the same effect as
     * omitting this parameter. The maximum length is 4,096 characters.

     *
If an EFS access point is specified in the authorizationConfig,
     * the root directory parameter must either be omitted or set to /,
     * which enforces the path set on the Amazon EFS access point.

     */
    inline EFSVolumeConfiguration& WithRootDirectory(Aws::String&& value) { SetRootDirectory(std::move(value)); return *this;}

    /**
     *
The directory within the Amazon EFS file system to mount as the root
     * directory inside the host. If this parameter is omitted, the root of the Amazon
     * EFS volume is used instead. Specifying / has the same effect as
     * omitting this parameter. The maximum length is 4,096 characters.

     *
If an EFS access point is specified in the authorizationConfig,
     * the root directory parameter must either be omitted or set to /,
     * which enforces the path set on the Amazon EFS access point.

     */
    inline EFSVolumeConfiguration& WithRootDirectory(const char* value) { SetRootDirectory(value); return *this;}

    /**
     *
Determines whether to enable encryption for Amazon EFS data in transit
     * between the Amazon ECS host and the Amazon EFS server. Transit encryption must
     * be enabled if Amazon EFS IAM authorization is used. If this parameter is
     * omitted, the default value of DISABLED is used. For more
     * information, see Encrypting
     * data in transit in the Amazon Elastic File System User Guide.

     */
    inline const EFSTransitEncryption& GetTransitEncryption() const{ return m_transitEncryption; }

    /**
     *
Determines whether to enable encryption for Amazon EFS data in transit
     * between the Amazon ECS host and the Amazon EFS server. Transit encryption must
     * be enabled if Amazon EFS IAM authorization is used. If this parameter is
     * omitted, the default value of DISABLED is used. For more
     * information, see Encrypting
     * data in transit in the Amazon Elastic File System User Guide.

     */
    inline bool TransitEncryptionHasBeenSet() const { return m_transitEncryptionHasBeenSet; }

    /**
     *
Determines whether to enable encryption for Amazon EFS data in transit
     * between the Amazon ECS host and the Amazon EFS server. Transit encryption must
     * be enabled if Amazon EFS IAM authorization is used. If this parameter is
     * omitted, the default value of DISABLED is used. For more
     * information, see Encrypting
     * data in transit in the Amazon Elastic File System User Guide.

     */
    inline void SetTransitEncryption(const EFSTransitEncryption& value) { m_transitEncryptionHasBeenSet = true; m_transitEncryption = value; }

    /**
     *
Determines whether to enable encryption for Amazon EFS data in transit
     * between the Amazon ECS host and the Amazon EFS server. Transit encryption must
     * be enabled if Amazon EFS IAM authorization is used. If this parameter is
     * omitted, the default value of DISABLED is used. For more
     * information, see Encrypting
     * data in transit in the Amazon Elastic File System User Guide.

     */
    inline void SetTransitEncryption(EFSTransitEncryption&& value) { m_transitEncryptionHasBeenSet = true; m_transitEncryption = std::move(value); }

    /**
     *
Determines whether to enable encryption for Amazon EFS data in transit
     * between the Amazon ECS host and the Amazon EFS server. Transit encryption must
     * be enabled if Amazon EFS IAM authorization is used. If this parameter is
     * omitted, the default value of DISABLED is used. For more
     * information, see Encrypting
     * data in transit in the Amazon Elastic File System User Guide.

     */
    inline EFSVolumeConfiguration& WithTransitEncryption(const EFSTransitEncryption& value) { SetTransitEncryption(value); return *this;}

    /**
     *
Determines whether to enable encryption for Amazon EFS data in transit
     * between the Amazon ECS host and the Amazon EFS server. Transit encryption must
     * be enabled if Amazon EFS IAM authorization is used. If this parameter is
     * omitted, the default value of DISABLED is used. For more
     * information, see Encrypting
     * data in transit in the Amazon Elastic File System User Guide.

     */
    inline EFSVolumeConfiguration& WithTransitEncryption(EFSTransitEncryption&& value) { SetTransitEncryption(std::move(value)); return *this;}

    /**
     *
The port to use when sending encrypted data between the Amazon ECS host and
     * the Amazon EFS server. If you don't specify a transit encryption port, it uses
     * the port selection strategy that the Amazon EFS mount helper uses. The value
     * must be between 0 and 65,535. For more information, see EFS mount
     * helper in the Amazon Elastic File System User Guide.

     */
    inline int GetTransitEncryptionPort() const{ return m_transitEncryptionPort; }

    /**
     *
The port to use when sending encrypted data between the Amazon ECS host and
     * the Amazon EFS server. If you don't specify a transit encryption port, it uses
     * the port selection strategy that the Amazon EFS mount helper uses. The value
     * must be between 0 and 65,535. For more information, see EFS mount
     * helper in the Amazon Elastic File System User Guide.

     */
    inline bool TransitEncryptionPortHasBeenSet() const { return m_transitEncryptionPortHasBeenSet; }

    /**
     *
The port to use when sending encrypted data between the Amazon ECS host and
     * the Amazon EFS server. If you don't specify a transit encryption port, it uses
     * the port selection strategy that the Amazon EFS mount helper uses. The value
     * must be between 0 and 65,535. For more information, see EFS mount
     * helper in the Amazon Elastic File System User Guide.

     */
    inline void SetTransitEncryptionPort(int value) { m_transitEncryptionPortHasBeenSet = true; m_transitEncryptionPort = value; }

    /**
     *
The port to use when sending encrypted data between the Amazon ECS host and
     * the Amazon EFS server. If you don't specify a transit encryption port, it uses
     * the port selection strategy that the Amazon EFS mount helper uses. The value
     * must be between 0 and 65,535. For more information, see EFS mount
     * helper in the Amazon Elastic File System User Guide.

     */
    inline EFSVolumeConfiguration& WithTransitEncryptionPort(int value) { SetTransitEncryptionPort(value); return *this;}

    /**
     *
The authorization configuration details for the Amazon EFS file system.

     */
    inline const EFSAuthorizationConfig& GetAuthorizationConfig() const{ return m_authorizationConfig; }

    /**
     *
The authorization configuration details for the Amazon EFS file system.

     */
    inline bool AuthorizationConfigHasBeenSet() const { return m_authorizationConfigHasBeenSet; }

    /**
     *
The authorization configuration details for the Amazon EFS file system.

     */
    inline void SetAuthorizationConfig(const EFSAuthorizationConfig& value) { m_authorizationConfigHasBeenSet = true; m_authorizationConfig = value; }

    /**
     *
The authorization configuration details for the Amazon EFS file system.

     */
    inline void SetAuthorizationConfig(EFSAuthorizationConfig&& value) { m_authorizationConfigHasBeenSet = true; m_authorizationConfig = std::move(value); }

    /**
     *
The authorization configuration details for the Amazon EFS file system.

     */
    inline EFSVolumeConfiguration& WithAuthorizationConfig(const EFSAuthorizationConfig& value) { SetAuthorizationConfig(value); return *this;}

    /**
     *
The authorization configuration details for the Amazon EFS file system.

     */
    inline EFSVolumeConfiguration& WithAuthorizationConfig(EFSAuthorizationConfig&& value) { SetAuthorizationConfig(std::move(value)); return *this;}

  private:

    Aws::String m_fileSystemId;
    bool m_fileSystemIdHasBeenSet = false;

    Aws::String m_rootDirectory;
    bool m_rootDirectoryHasBeenSet = false;

    EFSTransitEncryption m_transitEncryption;
    bool m_transitEncryptionHasBeenSet = false;

    int m_transitEncryptionPort;
    bool m_transitEncryptionPortHasBeenSet = false;

    EFSAuthorizationConfig m_authorizationConfig;
    bool m_authorizationConfigHasBeenSet = false;
  };

} // namespace Model
} // namespace Batch
} // namespace Aws


text:
from __future__ import absolute_import

import functools
import json
import math
import os
import platform
import re
import shutil
import time
from datetime import datetime
from glob import glob

import click
import zeroconf

from platformio import __version__, exception, proc
from platformio.compat import IS_MACOS, IS_WINDOWS
from platformio.fs import cd, load_json  # pylint: disable=unused-import
from platformio.proc import exec_command  # pylint: disable=unused-import

class memoized(object):
    def __init__(self, expire=0):
        expire = str(expire)
        if expire.isdigit():
            expire = "%ss" % int((int(expire) / 1000))
        tdmap = {"s": 1, "m": 60, "h": 3600, "d": 86400}
        assert expire.endswith(tuple(tdmap))
        self.expire = int(tdmap[expire[-1]] * int(expire[:-1]))
        self.cache = {}

    def __call__(self, func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            key = str(args) + str(kwargs)
            if key not in self.cache or (
                self.expire > 0 and self.cache[key][0] < time.time() - self.expire
            ):
                self.cache[key] = (time.time(), func(*args, **kwargs))
            return self.cache[key][1]

        wrapper.reset = self._reset
        return wrapper

    def _reset(self):
        self.cache.clear()

class throttle(object):
    def __init__(self, threshhold):
        self.threshhold = threshhold  # milliseconds
        self.last = 0

    def __call__(self, func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            diff = int(round((time.time() - self.last) * 1000))
            if diff < self.threshhold:
                time.sleep((self.threshhold - diff) * 0.001)
            self.last = time.time()
            return func(*args, **kwargs)

        return wrapper

def singleton(cls):
    """From PEP-318 http://www.python.org/dev/peps/pep-0318/#examples"""
    _instances = {}

    def get_instance(*args, **kwargs):
        if cls not in _instances:
            _instances[cls] = cls(*args, **kwargs)
        return _instances[cls]

    return get_instance

def get_systype():
    type_ = platform.system().lower()
    arch = platform.machine().lower()
    if type_ == "windows" and "x86" in arch:
        arch = "amd64" if "64" in arch else "x86"
    return "%s_%s" % (type_, arch) if arch else type_

def get_serial_ports(filter_hwid=False):
    try:
        # pylint: disable=import-outside-toplevel
        from serial.tools.list_ports import comports
    except ImportError:
        raise exception.GetSerialPortsError(os.name)

    result = []
    for p, d, h in comports():
        if not p:
            continue
        if not filter_hwid or "VID:PID" in h:
            result.append({"port": p, "description": d, "hwid": h})

    if filter_hwid:
        return result

    # fix for PySerial
    if not result and IS_MACOS:
        for p in glob("/dev/tty.*"):
            result.append({"port": p, "description": "n/a", "hwid": "n/a"})
    return result

# Backward compatibility for PIO Core <3.5
get_serialports = get_serial_ports

def get_logical_devices():
    items = []
    if IS_WINDOWS:
        try:
            result = proc.exec_command(
                ["wmic", "logicaldisk", "get", "name,VolumeName"]
            ).get("out", "")
            devicenamere = re.compile(r"^([A-Z]{1}\:)\s*(\S+)?")
            for line in result.split("\n"):
                match = devicenamere.match(line.strip())
                if not match:
                    continue
                items.append({"path": match.group(1) + "\\", "name": match.group(2)})
            return items
        except WindowsError:  # pylint: disable=undefined-variable
            pass
        # try "fsutil"
        result = proc.exec_command(["fsutil", "fsinfo", "drives"]).get("out", "")
        for device in re.findall(r"[A-Z]:\\", result):
            items.append({"path": device, "name": None})
        return items

    result = proc.exec_command(["df"]).get("out")
    devicenamere = re.compile(r"^/.+\d+\%\s+([a-z\d\-_/]+)$", flags=re.I)
    for line in result.split("\n"):
        match = devicenamere.match(line.strip())
        if not match:
            continue
        items.append({"path": match.group(1), "name": os.path.basename(match.group(1))})
    return items

def get_mdns_services():
    class mDNSListener(object):
        def __init__(self):
            self._zc = zeroconf.Zeroconf(interfaces=zeroconf.InterfaceChoice.All)
            self._found_types = []
            self._found_services = []

        def __enter__(self):
            zeroconf.ServiceBrowser(
                self._zc,
                [
                    "_http._tcp.local.",
                    "_hap._tcp.local.",
                    "_services._dns-sd._udp.local.",
                ],
                self,
            )
            return self

        def __exit__(self, etype, value, traceback):
            self._zc.close()

        def add_service(self, zc, type_, name):
            try:
                assert zeroconf.service_type_name(name)
                assert str(name)
            except (AssertionError, UnicodeError, zeroconf.BadTypeInNameException):
                return
            if name not in self._found_types:
                self._found_types.append(name)
                zeroconf.ServiceBrowser(self._zc, name, self)
            if type_ in self._found_types:
                s = zc.get_service_info(type_, name)
                if s:
                    self._found_services.append(s)

        def remove_service(self, zc, type_, name):
            pass

        def update_service(self, zc, type_, name):
            pass

        def get_services(self):
            return self._found_services

    items = []
    with mDNSListener() as mdns:
        time.sleep(3)
        for service in mdns.get_services():
            properties = None
            if service.properties:
                try:
                    properties = {
                        k.decode("utf8"): v.decode("utf8")
                        if isinstance(v, bytes)
                        else v
                        for k, v in service.properties.items()
                    }
                    json.dumps(properties)
                except UnicodeDecodeError:
                    properties = None

            items.append(
                {
                    "type": service.type,
                    "name": service.name,
                    "ip": ", ".join(service.parsed_addresses()),
                    "port": service.port,
                    "properties": properties,
                }
            )
    return items

def pioversion_to_intstr():
    """Legacy for  framework-zephyr/scripts/platformio/platformio-build-pre.py"""
    vermatch = re.match(r"^([\d\.]+)", __version__)
    assert vermatch
    return [int(i) for i in vermatch.group(1).split(".")[:3]]

def items_to_list(items):
    if isinstance(items, list):
        return items
    return [i.strip() for i in items.split(",") if i.strip()]

def items_in_list(needle, haystack):
    needle = items_to_list(needle)
    haystack = items_to_list(haystack)
    if "*" in needle or "*" in haystack:
        return True
    return set(needle) & set(haystack)

def parse_datetime(datestr):
    if "T" in datestr and "Z" in datestr:
        return datetime.strptime(datestr, "%Y-%m-%dT%H:%M:%SZ")
    return datetime.strptime(datestr)

def merge_dicts(d1, d2, path=None):
    if path is None:
        path = []
    for key in d2:
        if key in d1 and isinstance(d1[key], dict) and isinstance(d2[key], dict):
            merge_dicts(d1[key], d2[key], path + [str(key)])
        else:
            d1[key] = d2[key]
    return d1

def print_labeled_bar(label, is_error=False, fg=None, sep="="):
    terminal_width, _ = shutil.get_terminal_size()
    width = len(click.unstyle(label))
    half_line = sep * int((terminal_width - width - 2) / 2)
    click.secho("%s %s %s" % (half_line, label, half_line), fg=fg, err=is_error)

def humanize_duration_time(duration):
    if duration is None:
        return duration
    duration = duration * 1000
    tokens = []
    for multiplier in (3600000, 60000, 1000, 1):
        fraction = math.floor(duration / multiplier)
        tokens.append(int(round(duration) if multiplier == 1 else fraction))
        duration -= fraction * multiplier
    return "{:02d}:{:02d}:{:02d}.{:03d}".format(*tokens)

def strip_ansi_codes(text):
    return re.sub(r"\x1B\[\d+(;\d+){0,2}m", "", text)


text:
<?php

namespace Yajra\DataTables;

use Illuminate\Contracts\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Contracts\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Connection;
use Illuminate\Database\Query\Expression;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Yajra\DataTables\Utilities\Helper;

class QueryDataTable extends DataTableAbstract
{
    /**
     * Builder object.
     *
     * @var QueryBuilder
     */
    protected QueryBuilder $query;

    /**
     * Flag for ordering NULLS LAST option.
     *
     * @var bool
     */
    protected bool $nullsLast = false;

    /**
     * Flag to check if query preparation was already done.
     *
     * @var bool
     */
    protected bool $prepared = false;

    /**
     * Query callback for custom pagination using limit without offset.
     *
     * @var callable|null
     */
    protected $limitCallback = null;

    /**
     * Flag to keep the select bindings.
     *
     * @var bool
     */
    protected bool $keepSelectBindings = false;

    /**
     * @param  QueryBuilder  $builder
     */
    public function __construct(QueryBuilder $builder)
    {
        $this->query = $builder;
        $this->request = app('datatables.request');
        $this->config = app('datatables.config');
        $this->columns = $builder->columns;

        if ($this->config->isDebugging()) {
            $this->getConnection()->enableQueryLog();
        }
    }

    /**
     * @return \Illuminate\Database\Connection
     */
    public function getConnection(): Connection
    {
        /** @var Connection $connection */
        $connection = $this->query->getConnection();

        return $connection;
    }

    /**
     * Can the DataTable engine be created with these parameters.
     *
     * @param  mixed  $source
     * @return bool
     */
    public static function canCreate($source): bool
    {
        return $source instanceof QueryBuilder && ! ($source instanceof EloquentBuilder);
    }

    /**
     * Organizes works.
     *
     * @param  bool  $mDataSupport
     * @return \Illuminate\Http\JsonResponse
     *
     * @throws \Exception
     */
    public function make($mDataSupport = true): JsonResponse
    {
        try {
            $results = $this->prepareQuery()->results();
            $processed = $this->processResults($results, $mDataSupport);
            $data = $this->transform($results, $processed);

            return $this->render($data);
        } catch (\Exception $exception) {
            return $this->errorResponse($exception);
        }
    }

    /**
     * Prepare query by executing count, filter, order and paginate.
     *
     * @return $this
     */
    protected function prepareQuery(): static
    {
        if (! $this->prepared) {
            $this->totalRecords = $this->totalCount();

            $this->filterRecords();
            $this->ordering();
            $this->paginate();
        }

        $this->prepared = true;

        return  $this;
    }

    /**
     * Counts current query.
     *
     * @return int
     */
    public function count(): int
    {
        return $this->prepareCountQuery()->count();
    }

    /**
     * Prepare count query builder.
     *
     * @return QueryBuilder
     */
    public function prepareCountQuery(): QueryBuilder
    {
        $builder = clone $this->query;

        if ($this->isComplexQuery($builder)) {
            $table = $this->getConnection()->raw('('.$builder->toSql().') count_row_table');

            return $this->getConnection()->table($table)->setBindings($builder->getBindings());
        }

        $row_count = $this->wrap('row_count');
        $builder->select($this->getConnection()->raw("'1' as {$row_count}"));
        if (! $this->keepSelectBindings) {
            $builder->setBindings([], 'select');
        }

        return $builder;
    }

    /**
     * Check if builder query uses complex sql.
     *
     * @param  QueryBuilder|EloquentBuilder  $query
     * @return bool
     */
    protected function isComplexQuery($query): bool
    {
        return Str::contains(Str::lower($query->toSql()), ['union', 'having', 'distinct', 'order by', 'group by']);
    }

    /**
     * Wrap column with DB grammar.
     *
     * @param  string  $column
     * @return string
     */
    protected function wrap(string $column): string
    {
        return $this->getConnection()->getQueryGrammar()->wrap($column);
    }

    /**
     * Get paginated results.
     *
     * @return \Illuminate\Support\Collection<int, array>
     */
    public function results(): Collection
    {
        return $this->query->get();
    }

    /**
     * Keep the select bindings.
     *
     * @return $this
     */
    public function keepSelectBindings(): static
    {
        $this->keepSelectBindings = true;

        return $this;
    }

    /**
     * Perform column search.
     *
     * @return void
     */
    public function columnSearch(): void
    {
        $columns = $this->request->columns();

        foreach ($columns as $index => $column) {
            $column = $this->getColumnName($index);

            if (is_null($column)) {
                continue;
            }

            if (! $this->request->isColumnSearchable($index) || $this->isBlacklisted($column) && ! $this->hasFilterColumn($column)) {
                continue;
            }

            if ($this->hasFilterColumn($column)) {
                $keyword = $this->getColumnSearchKeyword($index, true);
                $this->applyFilterColumn($this->getBaseQueryBuilder(), $column, $keyword);
            } else {
                $column = $this->resolveRelationColumn($column);
                $keyword = $this->getColumnSearchKeyword($index);
                $this->compileColumnSearch($index, $column, $keyword);
            }
        }
    }

    /**
     * Check if column has custom filter handler.
     *
     * @param  string  $columnName
     * @return bool
     */
    public function hasFilterColumn(string $columnName): bool
    {
        return isset($this->columnDef['filter'][$columnName]);
    }

    /**
     * Get column keyword to use for search.
     *
     * @param  int  $i
     * @param  bool  $raw
     * @return string
     */
    protected function getColumnSearchKeyword(int $i, bool $raw = false): string
    {
        $keyword = $this->request->columnKeyword($i);
        if ($raw || $this->request->isRegex($i)) {
            return $keyword;
        }

        return $this->setupKeyword($keyword);
    }

    /**
     * Apply filterColumn api search.
     *
     * @param  QueryBuilder  $query
     * @param  string  $columnName
     * @param  string  $keyword
     * @param  string  $boolean
     * @return void
     */
    protected function applyFilterColumn($query, string $columnName, string $keyword, string $boolean = 'and'): void
    {
        $query = $this->getBaseQueryBuilder($query);
        $callback = $this->columnDef['filter'][$columnName]['method'];

        if ($this->query instanceof EloquentBuilder) {
            $builder = $this->query->newModelInstance()->newQuery();
        } else {
            $builder = $this->query->newQuery();
        }

        $callback($builder, $keyword);

        /** @var \Illuminate\Database\Query\Builder $baseQueryBuilder */
        $baseQueryBuilder = $this->getBaseQueryBuilder($builder);
        $query->addNestedWhereQuery($baseQueryBuilder, $boolean);
    }

    /**
     * Get the base query builder instance.
     *
     * @param  QueryBuilder|EloquentBuilder|null  $instance
     * @return QueryBuilder
     */
    protected function getBaseQueryBuilder($instance = null)
    {
        if (! $instance) {
            $instance = $this->query;
        }

        if ($instance instanceof EloquentBuilder) {
            return $instance->getQuery();
        }

        return $instance;
    }

    /**
     * Resolve the proper column name be used.
     *
     * @param  string  $column
     * @return string
     */
    protected function resolveRelationColumn(string $column): string
    {
        return $column;
    }

    /**
     * Compile queries for column search.
     *
     * @param  int  $i
     * @param  string  $column
     * @param  string  $keyword
     * @return void
     */
    protected function compileColumnSearch(int $i, string $column, string $keyword): void
    {
        if ($this->request->isRegex($i)) {
            $this->regexColumnSearch($column, $keyword);
        } else {
            $this->compileQuerySearch($this->query, $column, $keyword, '');
        }
    }

    /**
     * Compile regex query column search.
     *
     * @param  string  $column
     * @param  string  $keyword
     * @return void
     */
    protected function regexColumnSearch(string $column, string $keyword): void
    {
        $column = $this->wrap($column);

        switch ($this->getConnection()->getDriverName()) {
            case 'oracle':
                $sql = ! $this->config->isCaseInsensitive()
                    ? 'REGEXP_LIKE( '.$column.' , ? )'
                    : 'REGEXP_LIKE( LOWER('.$column.') , ?, \'i\' )';
                break;

            case 'pgsql':
                $column = $this->castColumn($column);
                $sql = ! $this->config->isCaseInsensitive() ? $column.' ~ ?' : $column.' ~* ? ';
                break;

            default:
                $sql = ! $this->config->isCaseInsensitive()
                    ? $column.' REGEXP ?'
                    : 'LOWER('.$column.') REGEXP ?';
                $keyword = Str::lower($keyword);
        }

        $this->query->whereRaw($sql, [$keyword]);
    }

    /**
     * Wrap a column and cast based on database driver.
     *
     * @param  string  $column
     * @return string
     */
    protected function castColumn(string $column): string
    {
        switch ($this->getConnection()->getDriverName()) {
            case 'pgsql':
                return 'CAST('.$column.' as TEXT)';
            case 'firebird':
                return 'CAST('.$column.' as VARCHAR(255))';
            default:
                return $column;
        }
    }

    /**
     * Compile query builder where clause depending on configurations.
     *
     * @param  QueryBuilder|EloquentBuilder  $query
     * @param  string  $column
     * @param  string  $keyword
     * @param  string  $boolean
     * @return void
     */
    protected function compileQuerySearch($query, string $column, string $keyword, string $boolean = 'or'): void
    {
        $column = $this->addTablePrefix($query, $column);
        $column = $this->castColumn($column);
        $sql = $column.' LIKE ?';

        if ($this->config->isCaseInsensitive()) {
            $sql = 'LOWER('.$column.') LIKE ?';
        }

        $query->{$boolean.'WhereRaw'}($sql, [$this->prepareKeyword($keyword)]);
    }

    /**
     * Patch for fix about ambiguous field.
     * Ambiguous field error will appear when query use join table and search with keyword.
     *
     * @param  QueryBuilder|EloquentBuilder  $query
     * @param  string  $column
     * @return string
     */
    protected function addTablePrefix($query, string $column): string
    {
        if (! str_contains($column, '.')) {
            $q = $this->getBaseQueryBuilder($query);
            $from = $q->from;

            /** @phpstan-ignore-next-line */
            if (! $from instanceof Expression) {
                if (str_contains($from, ' as ')) {
                    $from = explode(' as ', $from)[1];
                }

                $column = $from.'.'.$column;
            }
        }

        return $this->wrap($column);
    }

    /**
     * Prepare search keyword based on configurations.
     *
     * @param  string  $keyword
     * @return string
     */
    protected function prepareKeyword(string $keyword): string
    {
        if ($this->config->isStartsWithSearch()) {
            return "$keyword%";
        }

        if ($this->config->isCaseInsensitive()) {
            $keyword = Str::lower($keyword);
        }

        if ($this->config->isWildcard()) {
            $keyword = Helper::wildcardLikeString($keyword);
        }

        if ($this->config->isSmartSearch()) {
            $keyword = "%$keyword%";
        }

        return $keyword;
    }

    /**
     * Add custom filter handler for the give column.
     *
     * @param  string  $column
     * @param  callable  $callback
     * @return $this
     */
    public function filterColumn($column, callable $callback): static
    {
        $this->columnDef['filter'][$column] = ['method' => $callback];

        return $this;
    }

    /**
     * Order each given columns versus the given custom sql.
     *
     * @param  array  $columns
     * @param  string  $sql
     * @param  array  $bindings
     * @return $this
     */
    public function orderColumns(array $columns, $sql, $bindings = []): static
    {
        foreach ($columns as $column) {
            $this->orderColumn($column, str_replace(':column', $column, $sql), $bindings);
        }

        return $this;
    }

    /**
     * Override default column ordering.
     *
     * @param  string  $column
     * @param  string|\Closure  $sql
     * @param  array  $bindings
     * @return $this
     *
     * @internal string $1 Special variable that returns the requested order direction of the column.
     */
    public function orderColumn($column, $sql, $bindings = []): static
    {
        $this->columnDef['order'][$column] = compact('sql', 'bindings');

        return $this;
    }

    /**
     * Set datatables to do ordering with NULLS LAST option.
     *
     * @return $this
     */
    public function orderByNullsLast(): static
    {
        $this->nullsLast = true;

        return $this;
    }

    /**
     * Paginate dataTable using limit without offset
     * with additional where clause via callback.
     *
     * @param  callable  $callback
     * @return $this
     */
    public function limit(callable $callback): static
    {
        $this->limitCallback = $callback;

        return $this;
    }

    /**
     * Perform pagination.
     *
     * @return void
     */
    public function paging(): void
    {
        $start = $this->request->start();
        $length = $this->request->length();

        $limit = $length > 0 ? $length : 10;

        if (is_callable($this->limitCallback)) {
            $this->query->limit($limit);
            call_user_func_array($this->limitCallback, [$this->query]);
        } else {
            $this->query->skip($start)->take($limit);
        }
    }

    /**
     * Add column in collection.
     *
     * @param  string  $name
     * @param  string|callable  $content
     * @param  bool|int  $order
     * @return $this
     */
    public function addColumn($name, $content, $order = false): static
    {
        $this->pushToBlacklist($name);

        return parent::addColumn($name, $content, $order);
    }

    /**
     * Perform search using search pane values.
     *
     * @return void
     *
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    protected function searchPanesSearch(): void
    {
        /** @var string[] $columns */
        $columns = $this->request->get('searchPanes', []);

        foreach ($columns as $column => $values) {
            if ($this->isBlacklisted($column)) {
                continue;
            }

            if ($this->searchPanes[$column] && $callback = $this->searchPanes[$column]['builder']) {
                $callback($this->query, $values);
            } else {
                $this->query->whereIn($column, $values);
            }
        }
    }

    /**
     * Resolve callback parameter instance.
     *
     * @return QueryBuilder
     */
    protected function resolveCallbackParameter()
    {
        return $this->query;
    }

    /**
     * Perform default query orderBy clause.
     *
     * @return void
     *
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    protected function defaultOrdering(): void
    {
        collect($this->request->orderableColumns())
            ->map(function ($orderable) {
                $orderable['name'] = $this->getColumnName($orderable['column'], true);

                return $orderable;
            })
            ->reject(function ($orderable) {
                return $this->isBlacklisted($orderable['name']) && ! $this->hasOrderColumn($orderable['name']);
            })
            ->each(function ($orderable) {
                $column = $this->resolveRelationColumn($orderable['name']);

                if ($this->hasOrderColumn($column)) {
                    $this->applyOrderColumn($column, $orderable);
                } else {
                    $nullsLastSql = $this->getNullsLastSql($column, $orderable['direction']);
                    $normalSql = $this->wrap($column).' '.$orderable['direction'];
                    $sql = $this->nullsLast ? $nullsLastSql : $normalSql;
                    $this->query->orderByRaw($sql);
                }
            });
    }

    /**
     * Check if column has custom sort handler.
     *
     * @param  string  $column
     * @return bool
     */
    protected function hasOrderColumn(string $column): bool
    {
        return isset($this->columnDef['order'][$column]);
    }

    /**
     * Apply orderColumn custom query.
     *
     * @param  string  $column
     * @param  array  $orderable
     */
    protected function applyOrderColumn(string $column, array $orderable): void
    {
        $sql = $this->columnDef['order'][$column]['sql'];
        if ($sql === false) {
            return;
        }

        if (is_callable($sql)) {
            call_user_func($sql, $this->query, $orderable['direction']);
        } else {
            $sql = str_replace('$1', $orderable['direction'], $sql);
            $bindings = $this->columnDef['order'][$column]['bindings'];
            $this->query->orderByRaw($sql, $bindings);
        }
    }

    /**
     * Get NULLS LAST SQL.
     *
     * @param  string  $column
     * @param  string  $direction
     * @return string
     *
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    protected function getNullsLastSql($column, $direction): string
    {
        /** @var string $sql */
        $sql = $this->config->get('datatables.nulls_last_sql', '%s %s NULLS LAST');

        return str_replace(
            [':column', ':direction'],
            [$column, $direction],
            sprintf($sql, $column, $direction)
        );
    }

    /**
     * Perform global search for the given keyword.
     *
     * @param  string  $keyword
     * @return void
     */
    protected function globalSearch(string $keyword): void
    {
        $this->query->where(function ($query) use ($keyword) {
            collect($this->request->searchableColumnIndex())
                ->map(function ($index) {
                    return $this->getColumnName($index);
                })
                ->filter()
                ->reject(function ($column) {
                    return $this->isBlacklisted($column) && ! $this->hasFilterColumn($column);
                })
                ->each(function ($column) use ($keyword, $query) {
                    if ($this->hasFilterColumn($column)) {
                        $this->applyFilterColumn($query, $column, $keyword, 'or');
                    } else {
                        $this->compileQuerySearch($query, $column, $keyword);
                    }
                });
        });
    }

    /**
     * Append debug parameters on output.
     *
     * @param  array  $output
     * @return array
     */
    protected function showDebugger(array $output): array
    {
        $query_log = $this->getConnection()->getQueryLog();
        array_walk_recursive($query_log, function (&$item) {
            if (is_string($item)) {
                $item = utf8_encode($item);
            }
        });

        $output['queries'] = $query_log;
        $output['input'] = $this->request->all();

        return $output;
    }

    /**
     * Attach custom with meta on response.
     *
     * @param  array  $data
     * @return array
     */
    protected function attachAppends(array $data): array
    {
        $appends = [];
        foreach ($this->appends as $key => $value) {
            if (is_callable($value)) {
                $appends[$key] = value($value($this->getFilteredQuery()));
            } else {
                $appends[$key] = $value;
            }
        }

        return array_merge($data, $appends);
    }

    /**
     * Get filtered, ordered and paginated query.
     *
     * @return QueryBuilder
     */
    public function getFilteredQuery(): QueryBuilder
    {
        $this->prepareQuery();

        return $this->getQuery();
    }

    /**
     * Get query builder instance.
     *
     * @return QueryBuilder
     */
    public function getQuery(): QueryBuilder
    {
        return $this->query;
    }
}


text:
class FixBlankAncestries < ActiveRecord::Migration
  def up
    execute("UPDATE form_items SET ancestry = NULL WHERE ancestry = ''")
    execute("UPDATE option_nodes SET ancestry = NULL WHERE ancestry = ''")
  end

  def down
  end
end


text:
    This example shows how a the compress module can be used to create zip files and write them to
    a compatible ostream.  Files and directories can be added via istreams and filesystem paths.
--]]

-- the ostream could be other types, such as pipeostream, teeostream, memoryostream, etc.
local fostream = assert(require("poco.fileostream"))
local compress = assert(require("poco.zip.compress"))
local path = assert(require("poco.path"))

-- write the zip file to the output stream in the temp directory.
local output_zip_path = path(path.temp())
output_zip_path:setFileName("compress_example.zip")
local zfs = assert(fostream(output_zip_path:toString()))

-- create compress instance with the fileostream.
--- compress stores a reference to the fileostream to prevent GC,
--- so a reference does not need to be maintained by the caller.
--- additionally, the default true parameter for seekable must be false for
--- non-seekable istreams such as pipeistream, socketistream, etc.
local c = assert(compress(zfs))

-- print the list of file extensions that will get stored in the zipfile
-- via the STORE method rather than DEFLATE.
print("\nFile extensions using STORE method: ")
for k,v in pairs(c:getStoreExtensions()) do print(k,v) end

-- store a comment for the zip file and print it out.
c:setZipComment("example comment")
print("\nZip file comment:", c:getZipComment())

-- assume current working directory is the directory containing the examples.
local examples_path = assert(path(path.current()))
-- add all files and directories under the 'examples' directory to the zip file.
io.write(string.format("\nAdding recursive directory: %s\nto: %s\n", examples_path:toString(), output_zip_path:toString()))
assert(c:addRecursive(examples_path, "examples"))

-- add README.md to readme/README.md via the addFile function.
examples_path:popDirectory()
examples_path:setFileName("README.md")
io.write(string.format("\nAdding File: %s\nto: %s\n", examples_path:toString(), output_zip_path:toString()))
assert(c:addFile(examples_path, "readme/README.md"))

--[[ alternatively one could add a file via an poco istream via the addIStream function.
-- note that this source could be a memoryistream, pipeistream, socketistream, etc.
local fistream = assert(require("poco.fileistream"))
local fis = assert(fistream(examples_path:toString()))
--]]

-- finalize the zip file.
c:close()


text:
#!/usr/bin/perl -w

# options.pl: generate options dialog boxes

# Copyright (c) 2001-2015 Philip Kendall, Marek Januszewski, Stuart Brady

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# Author contact information:

# E-mail: philip-fuse@shadowmagic.org.uk

use strict;

use Fuse;
use Fuse::Dialog;

die "No data file specified" unless @ARGV;
my %combo_sets;
my %combo_default;

my @dialogs = Fuse::Dialog::read( shift @ARGV );

print Fuse::GPL( 'options.c: options dialog boxes',
                 '2001-2013 Philip Kendall, Marek Januszewski, Stuart Brady' ) . << "CODE";

/* This file is autogenerated from options.dat by options.pl.
   Do not edit unless you know what you\'re doing! */

#include <config.h>

#ifdef UI_WIN32                /* Use this file if we're using WIN32 */

#include <libspectrum.h>

#include "display.h"
#include "fuse.h"
#include "options.h"
#include "options_internals.h"
#include "periph.h"
#include "settings.h"
#include "ui/win32/win32internals.h"
#include "utils.h"

static int
option_enumerate_combo( const char * const *options, char *value, int count,
                        int def ) {
  int i;
  if( value != NULL ) {
    for( i = 0; i < count; i++) {
      if( !strcmp( value, options[ i ] ) )
        return i;
    }
  }
  return def;
}

CODE

foreach( @dialogs ) {

    foreach my $widget ( @{ $_->{widgets} } ) {

	foreach my $type ( $widget->{type} ) {

	    my $text = $widget->{text}; $text =~ tr/()//d;

	    if( $type eq "Combo" ) {
		my $n = 0;

		foreach( split( /\|/, $widget->{data1} ) ) {
		    if( /^\*/ ) {
			$combo_default{$widget->{value}} = $n;
		    }
		    $n++;
		}
		$n = 0;
		$widget->{data1} =~ s/^\*//;
		$widget->{data1} =~ s/\|\*/|/;
		if( not exists( $combo_sets{$widget->{data1}} ) ) {
		    $combo_sets{$widget->{data1}} = "$_->{name}_$widget->{value}_combo";

		    print << "CODE";

static const char * const $_->{name}_$widget->{value}_combo[] = {
CODE
		    foreach( split( /\|/, $widget->{data1} ) ) {
			print << "CODE";
  "$_",
CODE
			$n++;
		    }
		    print << "CODE";
};

static const int $_->{name}_$widget->{value}_combo_count = $n;

CODE
		} else {
		    print << "CODE";
\#define $_->{name}_$widget->{value}_combo $combo_sets{$widget->{data1}}
\#define $_->{name}_$widget->{value}_combo_count $combo_sets{$widget->{data1}}_count

CODE
		}
		print << "CODE";
int
option_enumerate_$_->{name}_$widget->{value}( void ) {
  return option_enumerate_combo( $_->{name}_$widget->{value}_combo,
                                 settings_current.$widget->{value},
                                 $_->{name}_$widget->{value}_combo_count,
                                 $combo_default{$widget->{value}} );
}

CODE
	    }
	}
    }

    my $idcname = uc( "IDC_OPT_$_->{name}" );
    my $optname = uc( "OPT_$_->{name}" );

print << "CODE";
static void
menu_options_$_->{name}_init( HWND hwndDlg )
{
  char buffer[80];
  int i;

  i = 0;
  buffer[0] = '\\0';
  if( buffer[i] ) {};          /* Shut gcc up */

CODE
    foreach my $widget ( @{ $_->{widgets} } ) {
	my $type = $widget->{type};

	if( $type eq "Checkbox" ) {
	    my $idcname = uc( "$widget->{value}" );
        print << "CODE";
  SendDlgItemMessage( hwndDlg, IDC_${optname}_${idcname}, BM_SETCHECK,
    settings_current.$widget->{value} ? BST_CHECKED : BST_UNCHECKED, 0 );

CODE
	} elsif( $widget->{type} eq "Entry" ) {
	    my $idcname = uc( "$widget->{value}" );
        print << "CODE";
  SendDlgItemMessage( hwndDlg, IDC_${optname}_${idcname}, EM_LIMITTEXT,
                      $widget->{data1}, 0 );
  /* FIXME This is asuming SendDlgItemMessage is not UNICODE */
  snprintf( buffer, 80, "%d", settings_current.$widget->{value} );
  SendDlgItemMessage( hwndDlg, IDC_${optname}_${idcname}, WM_SETTEXT,
                      0, (LPARAM) buffer );

CODE
	} elsif( $type eq "Combo" ) {
          my $idcname = uc( "$widget->{value}" );
          print << "CODE";
  for( i = 0; i < $_->{name}_$widget->{value}_combo_count; i++ ) {
    /* FIXME This is asuming SendDlgItemMessage is not UNICODE */
    SendDlgItemMessage( hwndDlg, IDC_${optname}_${idcname}, CB_ADDSTRING,
                        0, (LPARAM) $_->{name}_$widget->{value}_combo[i] );
  }
  SendDlgItemMessage( hwndDlg, IDC_${optname}_${idcname}, CB_SETCURSEL,
                      (LPARAM) $combo_default{$widget->{value}}, 0 );
  if( settings_current.$widget->{value} != NULL ) {
    for( i = 0; i < $_->{name}_$widget->{value}_combo_count; i++ ) {
      if( !strcmp( settings_current.$widget->{value},
                   $_->{name}_$widget->{value}_combo[i] ) ) {
        SendDlgItemMessage( hwndDlg, IDC_${optname}_${idcname},
                            CB_SETCURSEL, i, 0 );
      }
    }
  }
CODE
	} else {
          die "Unknown type `$type'";
        }
    }

print << "CODE";
}

static void
menu_options_$_->{name}_done( HWND hwndDlg )
{
  char buffer[80];

  buffer[0] = '\\0';
  if( buffer[0] ) {};          /* Shut gcc up */

CODE

    if( $_->{postcheck} ) {

      print << "CODE";
  /* Get a copy of current settings */
  settings_info original_settings;
  memset( &original_settings, 0, sizeof( settings_info ) );
  settings_copy( &original_settings, &settings_current );

CODE

    }

    foreach my $widget ( @{ $_->{widgets} } ) {
	my $type = $widget->{type};

	if( $type eq "Checkbox" ) {
	    my $idcname = uc( "$widget->{value}" );

	    print << "CODE";
  settings_current.$widget->{value} =
    IsDlgButtonChecked( hwndDlg, IDC_${optname}_${idcname} );

CODE
	} elsif( $widget->{type} eq "Entry" ) {
	    my $idcname = uc( "$widget->{value}" );
        print << "CODE";
  /* FIXME This is asuming SendDlgItemMessage is not UNICODE */
  SendDlgItemMessage( hwndDlg, IDC_${optname}_${idcname}, WM_GETTEXT,
                      80, (LPARAM) buffer );
  settings_current.$widget->{value} = atoi( buffer );

CODE
	} elsif( $widget->{type} eq "Combo" ) {
	    my $idcname = uc( "$widget->{value}" );
	    print << "CODE";
  libspectrum_free( settings_current.$widget->{value} );
  settings_current.$widget->{value} =
    utils_safe_strdup( $_->{name}_$widget->{value}_combo[
    SendDlgItemMessage( hwndDlg, IDC_${optname}_${idcname}, CB_GETCURSEL, 0, 0 ) ] );

CODE
        } else {
          die "Unknown type `$widget->{type}'";
        }
    }

    if( $_->{postcheck} ) {

      print << "CODE";
  int needs_hard_reset = $_->{postcheck}();

  /* Confirm reset */
  if( needs_hard_reset ) {
    ShowWindow( hwndDlg, SW_HIDE );

    if( !win32ui_confirm("Some options need to reset the machine. Reset?" ) ) {
      /* Cancel new settings */
      settings_copy( &settings_current, &original_settings );
      settings_free( &original_settings );

      ShowWindow( hwndDlg, SW_SHOW );
      return;
    }
  }

  settings_free( &original_settings );

CODE
    }

    print "  $_->{posthook}();\n\n" if $_->{posthook};

    print << "CODE";
  win32statusbar_set_visibility( settings_current.statusbar );
  display_refresh_all();

  EndDialog( hwndDlg, 0 );
}

static BOOL CALLBACK
menu_options_$_->{name}_proc( HWND hwndDlg, UINT msg, WPARAM wParam GCC_UNUSED,
                              LPARAM lParam GCC_UNUSED )
{
  switch( msg )
  {
    case WM_INITDIALOG:
    {
      /* FIXME: save the handle returned by LoadIcon() in win32ui.c */
      SendMessage( hwndDlg, WM_SETICON, ICON_SMALL,
                   (LPARAM)LoadIcon( fuse_hInstance, "win32_icon" ) );

      /* initialize the controls with current settings */
      menu_options_$_->{name}_init( hwndDlg );

      return TRUE;
    }

    case WM_COMMAND:
      switch( LOWORD( wParam ) )
      {
        case IDOK:
          /* Read the controls and apply the settings */
          menu_options_$_->{name}_done( hwndDlg );
          return 0;

        case IDCANCEL:
          EndDialog( hwndDlg, 0 );
          return 0;
      }
      break;

    case WM_CLOSE:
      EndDialog( hwndDlg, 0 );
      return 0;
  }

  return FALSE;
}

void
menu_options_$_->{name}( int action GCC_UNUSED )
{
  fuse_emulation_pause();

  DialogBox( fuse_hInstance, MAKEINTRESOURCE( IDD_$optname ),
             fuse_hWnd, (DLGPROC) menu_options_$_->{name}_proc );

  fuse_emulation_unpause();
}

CODE
}

    print << "CODE";

#endif                 /* #ifdef UI_WIN32 */

CODE


text:
.vimrc
=====

Feel [free to use it](LICENSE) and suggest improvements via Issues.
Keep in mind that I use it (mostly) for editing Python files.

Requirements
------------
- _Vim_ 7.3+ with Python support (check the latter with `vim --version | grep +python`)
- `exuberant-ctags` system package for `taglist.vim` plugin
- _Vim_ with `clipboard` support is recommended (_vim-gnome_ package in Debian)
- create virtualenvs for [Black](https://github.com/ambv/black) and (optionally) Neovim - see
  `" Black` and `" NeoVim` in [\_vimrc](_vimrc) for specific locations

Usage
-----
- Clone this repo
- Copy or symlink my `_vimrc` as your `~/.vimrc`
- Install _vim-plug_ on Linux:
    ```
    curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
        https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
    ```

    or read [here](https://github.com/junegunn/vim-plug#installation) for different platform
- `vim +PlugUpdate`

To see how to manage plugins please refer to the [vim-plug wiki](https://github.com/junegunn/vim-plug/wiki).


text:
CREATE INDEX expected_readers_reader_id ON expected_readers (reader_id);
CREATE INDEX read_receipts_reader_id ON read_receipts (reader_id);

-- +goose Down
DROP INDEX expected_readers_reader_id;
DROP INDEX read_receipts_reader_id;


text:
package com.github.edgar615.gateway.plugin.ip;

import com.github.edgar615.gateway.core.definition.ApiPlugin;
import com.github.edgar615.gateway.core.definition.ApiPluginFactory;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

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

/**
 * IP控制策略的工厂类.
 *
 * @author Edgar  Date 2016/10/21
 */
public class IpRestrictionFactory implements ApiPluginFactory {
    @Override
    public ApiPlugin decode(JsonObject jsonObject) {
        if (!jsonObject.containsKey("ip.restriction")) {
            return null;
        }
        JsonObject config = jsonObject.getJsonObject("ip.restriction", new JsonObject());
        JsonArray whiteArray = config.getJsonArray("whitelist", new JsonArray());
        JsonArray blackArray = config.getJsonArray("blacklist", new JsonArray());
        List<String> whitelist = new ArrayList<>();
        List<String> blacklist = new ArrayList<>();
        for (int i = 0; i < whiteArray.size(); i++) {
            whitelist.add(whiteArray.getString(i));
        }
        for (int i = 0; i < blackArray.size(); i++) {
            blacklist.add(blackArray.getString(i));
        }

        IpRestriction aclRestriction = new IpRestrictionImpl();
        whitelist.forEach(w -> aclRestriction.addWhitelist(w));
        blacklist.forEach(b -> aclRestriction.addBlacklist(b));
        return aclRestriction;
    }

    @Override
    public JsonObject encode(ApiPlugin plugin) {
        IpRestriction ipRestriction = (IpRestriction) plugin;
        return new JsonObject().put("ip.restriction", new JsonObject()
                .put("whitelist", new JsonArray(ipRestriction.whitelist()))
                .put("blacklist", new JsonArray(ipRestriction.blacklist())));
    }

    @Override
    public String name() {
        return IpRestriction.class.getSimpleName();
    }

    @Override
    public ApiPlugin create() {
        return new IpRestrictionImpl();
    }
}


text:
package org.apache.hadoop.hbase.exceptions;

import org.apache.yetus.audience.InterfaceAudience;

/**
 * Failed deserialization.
 */
@InterfaceAudience.Private
@SuppressWarnings("serial")
public class DeserializationException extends HBaseException {
  public DeserializationException() {
    super();
  }

  public DeserializationException(final String message) {
    super(message);
  }

  public DeserializationException(final String message, final Throwable t) {
    super(message, t);
  }

  public DeserializationException(final Throwable t) {
    super(t);
  }
}


text:
package com.sankholin.service.impl;

import com.sankholin.model.Prime;
import com.sankholin.service.IPrimeService;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@ApplicationScoped
public class PrimeService implements IPrimeService {

    private List<Prime> primes;

    @PostConstruct
    public void init() {
        //In real world, this will link up to persistent data tier.
        primes = new ArrayList<>();
        Prime prime = new Prime();
        prime.setId(UUID.randomUUID().toString());
        prime.setMessage("Initial message");
        prime.setContent("Probably initial content from persistent store.");
        primes.add(prime);

        prime = new Prime();
        prime.setId(UUID.randomUUID().toString());
        prime.setMessage("Second message");
        prime.setContent("This is second message. This should have " +
                "highlighted with yellow background.");
        primes.add(prime);
    }

    @Override
    public List<Prime> getPrimes() {
        return primes;
    }

    @Override
    public void addPrime(Prime prime) {
        primes.add(prime);
    }
}


text:
package org.apache.commons.math3.exception;

import org.apache.commons.math3.exception.util.Localizable;
import org.apache.commons.math3.exception.util.LocalizedFormats;

/**
 * Exception to be thrown when two sets of dimensions differ.
 *
 * @since 3.0
 * @version $Id$
 */
public class MultiDimensionMismatchException extends MathIllegalArgumentException {
    /** Serializable version Id. */
    private static final long serialVersionUID = -8415396756375798143L;

    /** Wrong dimensions. */
    private final Integer[] wrong;
    /** Correct dimensions. */
    private final Integer[] expected;

    /**
     * Construct an exception from the mismatched dimensions.
     *
     * @param wrong Wrong dimensions.
     * @param expected Expected dimensions.
     */
    public MultiDimensionMismatchException(Integer[] wrong,
                                           Integer[] expected) {
        this(LocalizedFormats.DIMENSIONS_MISMATCH, wrong, expected);
    }

    /**
     * Construct an exception from the mismatched dimensions.
     *
     * @param specific Message pattern providing the specific context of
     * the error.
     * @param wrong Wrong dimensions.
     * @param expected Expected dimensions.
     */
    public MultiDimensionMismatchException(Localizable specific,
                                           Integer[] wrong,
                                           Integer[] expected) {
        super(specific, wrong, expected);
        this.wrong = wrong.clone();
        this.expected = expected.clone();
    }

    /**
     * @return an array containing the wrong dimensions.
     */
    public Integer[] getWrongDimensions() {
        return wrong.clone();
    }
    /**
     * @return an array containing the expected dimensions.
     */
    public Integer[] getExpectedDimensions() {
        return expected.clone();
    }

    /**
     * @param index Dimension index.
     * @return the wrong dimension stored at {@code index}.
     */
    public int getWrongDimension(int index) {
        return wrong[index];
    }
    /**
     * @param index Dimension index.
     * @return the expected dimension stored at {@code index}.
     */
    public int getExpectedDimension(int index) {
        return expected[index];
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">

<erlref>

    <copyright>
      <year>2002</year>
      <year>2018</year>
      <holder>Ericsson AB, All Rights Reserved</holder>
    </copyright>
    <legalnotice>
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

  The Initial Developer of the Original Code is Ericsson AB.
    </legalnotice>

    <title>mnesia_frag_hash</title>
    <prepared>Håkan Mattsson</prepared>
    <responsible></responsible>
    <docno></docno>
    <approved></approved>
    <checked></checked>
    <date>2002-09-10</date>
    <rev>A</rev>
    <file>mnesia_frag_hash.sgml</file>

  <module>mnesia_frag_hash</module>
  <modulesummary>Defines mnesia_frag_hash callback behavior</modulesummary>
  <description>

This module defines a callback behavior for user-defined hash
      functions of fragmented tables.

Which module that is selected to implement the <c>mnesia_frag_hash</c>
      behavior for a particular fragmented table is specified together
      with the other <c>frag_properties</c>. The <c>hash_module</c> defines
      the module name. The <c>hash_state</c> defines the initial hash state.

This module implements dynamic hashing, which is a kind of hashing
      that grows nicely when new fragments are added. It is well
      suited for scalable hash tables.

  </description>

  <funcs>
    <func>
      <name>init_state(Tab, State) -> NewState | abort(Reason)</name>
      <fsummary>Initiates the hash state for a new table.</fsummary>
      <type>
        <v>Tab = atom()</v>
        <v>State = term()</v>
        <v>NewState = term()</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Starts when a fragmented table is
          created with the function <c>mnesia:create_table/2</c> or
          when a normal (unfragmented) table is converted to be a
          fragmented table with <c>mnesia:change_table_frag/2</c>.

Notice that the function <c>add_frag/2</c> is started
          one time for each of the other fragments (except number 1)
          as a part of the table creation procedure.

<c>State</c> is the initial value of the <c>hash_state</c>
          <c>frag_property</c>. <c>NewState</c> is stored as
          <c>hash_state</c> among the other <c>frag_properties</c>.

      </desc>
    </func>
    <func>
      <name>add_frag(State) -> {NewState, IterFrags, AdditionalLockFrags} | abort(Reason)</name>
      <fsummary>Starts when a new fragment is added to a fragmented table.</fsummary>
      <type>
        <v>State = term()</v>
        <v>NewState = term()</v>
        <v>IterFrags = [integer()]</v>
        <v>AdditionalLockFrags = [integer()]</v>
        <v>Reason = term()</v>
      </type>
      <desc>

To scale well, it is a good idea to ensure that the
          records are evenly distributed over all fragments, including
          the new one.

<c>NewState</c> is stored as <c>hash_state</c> among the
          other <c>frag_properties</c>.

As a part of the <c>add_frag</c> procedure, Mnesia iterates
          over all fragments corresponding to the <c>IterFrags</c> numbers
          and starts <c>key_to_frag_number(NewState,RecordKey)</c> for
          each record. If the new fragment differs from the old
          fragment, the record is moved to the new fragment.

As the <c>add_frag</c> procedure is a part of a schema
          transaction, Mnesia acquires write locks on the
          affected tables. That is, both the fragments corresponding
          to <c>IterFrags</c> and those corresponding to
          <c>AdditionalLockFrags</c>.

      </desc>
    </func>
    <func>
      <name>del_frag(State) ->  {NewState, IterFrags, AdditionalLockFrags} | abort(Reason)</name>
      <fsummary>Starts when a fragment is deleted from a fragmented table.</fsummary>
      <type>
        <v>State = term()</v>
        <v>NewState = term()</v>
        <v>IterFrags = [integer()]</v>
        <v>AdditionalLockFrags = [integer()]</v>
        <v>Reason = term()</v>
      </type>
      <desc>

<c>NewState</c> is stored as <c>hash_state</c> among the
          other <c>frag_properties</c>.

As a part of the <c>del_frag</c> procedure, Mnesia iterates
          over all fragments corresponding to the <c>IterFrags</c> numbers
          and starts <c>key_to_frag_number(NewState,RecordKey)</c> for
          each record. If the new fragment differs from the old
          fragment, the record is moved to the new fragment.

Notice that all records in the last fragment must be moved to
          another fragment, as the entire fragment is deleted.

As the <c>del_frag</c> procedure is a part of a schema
          transaction, Mnesia acquires write locks on the
          affected tables. That is, both the fragments corresponding
          to <c>IterFrags</c> and those corresponding to
          <c>AdditionalLockFrags</c>.

      </desc>
    </func>
    <func>
      <name>key_to_frag_number(State, Key) -> FragNum | abort(Reason)</name>
      <fsummary>Resolves the key of a record into a fragment number.</fsummary>
      <type>
        <v>FragNum = integer()</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Starts whenever Mnesia needs to determine
          which fragment a certain record belongs to. It is typically
          started at <c>read</c>, <c>write</c>, and <c>delete</c>.

      </desc>
    </func>
    <func>
      <name>match_spec_to_frag_numbers(State, MatchSpec) -> FragNums | abort(Reason)</name>
      <fsummary>Resolves a <c>MatchSpec</c> into a list of fragment numbers.</fsummary>
      <type>
        <v>MatcSpec = ets_select_match_spec()</v>
        <v>FragNums = [FragNum]</v>
        <v>FragNum = integer()</v>
        <v>Reason = term()</v>
      </type>
      <desc>

This function is called whenever Mnesia needs to determine
          which fragments that need to be searched for a <c>MatchSpec</c>.
          It is typically called by <c>select</c> and
          <c>match_object</c>.

      </desc>
    </func>
  </funcs>

    <title>See Also</title>

<seealso marker="mnesia:mnesia">mnesia(3)</seealso>

</erlref>