text:
import pytest

from mollie.api.error import IdentifierError
from mollie.api.objects.capture import Capture
from mollie.api.objects.chargeback import Chargeback
from mollie.api.objects.customer import Customer
from mollie.api.objects.mandate import Mandate
from mollie.api.objects.method import Method
from mollie.api.objects.order import Order
from mollie.api.objects.payment import Payment
from mollie.api.objects.refund import Refund
from mollie.api.objects.settlement import Settlement
from mollie.api.objects.subscription import Subscription

from .utils import assert_list_object

PAYMENT_ID = "tr_7UhSN1zuXS"
REFUND_ID = "re_4qqhO89gsT"
CHARGEBACK_ID = "chb_n9z0tp"
CUSTOMER_ID = "cst_8wmqcHMN4U"
SETTLEMENT_ID = "stl_jDk30akdN"
MANDATE_ID = "mdt_h3gAaD5zP"
SUBSCRIPTION_ID = "sub_rVKGtNd6s3"
ORDER_ID = "ord_kEn1PlbGa"

def test_list_payments(client, response):
    """Retrieve a list of payments."""
    response.get("https://api.mollie.com/v2/payments", "payments_list")

    payments = client.payments.list()
    assert_list_object(payments, Payment)

def test_create_payment(client, response):
    """Create a new payment."""
    response.post("https://api.mollie.com/v2/payments", "payment_single")

    payment = client.payments.create(
        {
            "amount": {"currency": "EUR", "value": "10.00"},
            "description": "Order #12345",
            "redirectUrl": "https://webshop.example.org/order/12345/",
            "webhookUrl": "https://webshop.example.org/payments/webhook/",
            "method": "ideal",
        }
    )
    assert payment.id == PAYMENT_ID

def test_cancel_payment(client, response):
    """Cancel existing payment."""
    response.delete(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}", "payment_canceled", 200)

    canceled_payment = client.payments.delete(PAYMENT_ID)
    assert isinstance(canceled_payment, Payment)
    assert canceled_payment.is_canceled() is True
    assert canceled_payment.canceled_at == "2018-03-20T09:28:37+00:00"
    assert canceled_payment.id == PAYMENT_ID

def test_cancel_payment_invalid_id(client):
    """Verify that an invalid payment id is validated and an error is raised."""
    with pytest.raises(IdentifierError) as excinfo:
        client.payments.delete("invalid")
    assert str(excinfo.value) == "Invalid payment ID 'invalid', it should start with 'tr_'."

def test_get_single_payment(client, response):
    """Retrieve a single payment by payment id."""
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}", "payment_single_no_links")

    payment = client.payments.get(PAYMENT_ID)
    assert isinstance(payment, Payment)
    # properties
    assert payment.resource == "payment"
    assert payment.id == PAYMENT_ID
    assert payment.mode == "test"
    assert payment.created_at == "2018-03-20T09:13:37+00:00"
    assert payment.status == Payment.STATUS_OPEN
    assert payment.is_cancelable is False
    assert payment.paid_at is None
    assert payment.canceled_at is None
    assert payment.authorized_at is None
    assert payment.expires_at == "2018-03-20T09:28:37+00:00"
    assert payment.expired_at is None
    assert payment.failed_at is None
    assert payment.amount == {"value": "10.00", "currency": "EUR"}
    assert payment.amount_refunded is None
    assert payment.amount_remaining is None
    assert payment.amount_captured == {"currency": "EUR", "value": "1.00"}
    assert payment.amount_chargedback == {"value": "5.00", "currency": "EUR"}
    assert payment.description == "Order #12345"
    assert payment.redirect_url == "https://webshop.example.org/order/12345/"
    assert payment.webhook_url == "https://webshop.example.org/payments/webhook/"
    assert payment.method == Method.IDEAL
    assert payment.metadata == {"order_id": "12345"}
    assert payment.locale is None
    assert payment.country_code is None
    assert payment.profile_id == "pfl_QkEhN94Ba"
    assert payment.customer_id == CUSTOMER_ID
    assert payment.sequence_type == Payment.SEQUENCETYPE_RECURRING
    assert payment.application_fee is None
    assert payment.details is None
    assert payment.routing is not None
    # properties from _links
    assert payment.checkout_url == "https://www.mollie.com/payscreen/select-method/7UhSN1zuXS"
    assert payment.changepaymentstate_url is None
    assert payment.payonline_url is None
    assert payment.refunds is not None
    assert payment.chargebacks is not None
    assert payment.captures is not None
    # additional methods
    assert payment.is_open() is True
    assert payment.is_pending() is False
    assert payment.is_canceled() is False
    assert payment.is_expired() is False
    assert payment.is_paid() is False
    assert payment.is_failed() is False
    assert payment.is_authorized() is False
    assert payment.has_refunds() is False
    assert payment.has_chargebacks() is False
    assert payment.has_captures() is False
    assert payment.has_split_payments() is True
    assert payment.can_be_refunded() is False
    assert payment.has_sequence_type_first() is False
    assert payment.has_sequence_type_recurring() is True

def test_get_payment_invalid_id(client):
    with pytest.raises(IdentifierError) as excinfo:
        client.payments.get("invalid")
    assert str(excinfo.value) == "Invalid payment ID 'invalid', it should start with 'tr_'."

def test_payment_get_related_refunds(client, response):
    """Retrieve a list of refunds related to a payment."""
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}", "payment_single")
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}/refunds", "refunds_list")

    payment = client.payments.get(PAYMENT_ID)
    refunds = payment.refunds.list()
    assert_list_object(refunds, Refund)

def test_payment_get_related_chargebacks(client, response):
    """Get chargebacks related to payment id."""
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}", "payment_single")
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}/chargebacks", "chargebacks_list")

    payment = client.payments.get(PAYMENT_ID)
    chargebacks = payment.chargebacks.list()
    assert_list_object(chargebacks, Chargeback)

def test_payment_get_related_captures(client, response):
    """Get captures related to payment."""
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}", "payment_single")
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}/captures", "captures_list")

    payment = client.payments.get(PAYMENT_ID)
    captures = payment.captures.list()
    assert_list_object(captures, Capture)

def test_payment_get_related_settlement(client, response):
    """Get the settlement related to the payment."""
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}", "payment_single")
    response.get(f"https://api.mollie.com/v2/settlements/{SETTLEMENT_ID}", "settlement_single")

    payment = client.payments.get(PAYMENT_ID)
    assert payment.settlement_id == SETTLEMENT_ID
    assert payment.settlement_amount == {"currency": "EUR", "value": "39.75"}

    settlement = payment.get_settlement()
    assert isinstance(settlement, Settlement)
    assert settlement.id == SETTLEMENT_ID

def test_payment_get_related_mandate(client, response):
    """Get the mandate related to the payment."""
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}", "payment_single")
    response.get(f"https://api.mollie.com/v2/customers/{CUSTOMER_ID}/mandates/{MANDATE_ID}", "customer_mandate_single")

    payment = client.payments.get(PAYMENT_ID)
    mandate = payment.get_mandate()
    assert isinstance(mandate, Mandate)
    assert mandate.id == MANDATE_ID

def test_payment_get_related_subscription(client, response):
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}", "payment_single")
    response.get(
        f"https://api.mollie.com/v2/customers/{CUSTOMER_ID}/subscriptions/{SUBSCRIPTION_ID}", "subscription_single"
    )

    payment = client.payments.get(PAYMENT_ID)
    subscription = payment.get_subscription()
    assert isinstance(subscription, Subscription)
    assert subscription.id == SUBSCRIPTION_ID

def test_payment_get_related_customer(client, response):
    """Get customer related to payment."""
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}", "payment_single")
    response.get(f"https://api.mollie.com/v2/customers/{CUSTOMER_ID}", "customer_single")

    payment = client.payments.get(PAYMENT_ID)
    customer = payment.get_customer()
    assert isinstance(customer, Customer)
    assert customer.id == CUSTOMER_ID

def test_payment_get_related_order(client, response):
    response.get(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}", "payment_single")
    response.get(f"https://api.mollie.com/v2/orders/{ORDER_ID}", "order_single")

    payment = client.payments.get(PAYMENT_ID)
    order = payment.get_order()
    assert isinstance(order, Order)
    assert order.id == ORDER_ID

def test_update_payment(client, response):
    """Update an existing payment."""
    response.patch(f"https://api.mollie.com/v2/payments/{PAYMENT_ID}", "payment_updated")

    data = {
        "description": "Order #12346",
        "redirectUrl": "https://webshop.example.org/order/12346/",
        "webhookUrl": "https://webshop.example.org/payments/webhook/",
        "metadata": {"order_id": "12346"},
    }
    updated_payment = client.payments.update(PAYMENT_ID, data)
    assert isinstance(updated_payment, Payment)
    assert updated_payment.description == "Order #12346"

def test_update_payment_invalid_id(client):
    data = {}
    with pytest.raises(IdentifierError) as excinfo:
        client.payments.update("invalid", data)
    assert str(excinfo.value) == "Invalid payment ID 'invalid', it should start with 'tr_'."


text:
using System;
using System.Collections;
using System.Collections.Generic;

namespace wslib.Negotiate.Extensions
{
    public class ExtensionParams : IEnumerable<Tuple<string, string>>
    {
        private readonly List<Tuple<string, string>> p = new List<Tuple<string, string>>();

        public void Add(string name)
        {
            Add(name, string.Empty);
        }

        public void Add(string name, string value)
        {
            p.Add(Tuple.Create(name, value));
        }

        public IEnumerator<Tuple<string, string>> GetEnumerator()
        {
            return p.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    class ExtensionRequest
    {
        public readonly string Token;
        public readonly ExtensionParams Params;

        public ExtensionRequest(string token, ExtensionParams parameters)
        {
            Token = token;
            Params = parameters;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
export MACHTYPE=x86_64
export BINDIR=$(pwd)/bin
mkdir -p $BINDIR
(cd kent/src/lib && make)
(cd kent/src/jkOwnLib && make)
(cd kent/src/hg/lib && make)
(cd kent/src/utils/newPythonProg && make)
mkdir -p $PREFIX/bin
cp bin/newPythonProg $PREFIX/bin
chmod +x $PREFIX/bin/newPythonProg


text:
namespace gorc {
namespace game {
namespace world {
namespace sounds {
namespace components {

class sound {
public:
    uid(54554757);

    sf::Sound internal_sound;
    bool has_played = false;

    bool do_distance_attenuation = false;
    float minimum_attenuation_radius = 0.0f;
    float maximum_attenuation_radius = 1.0f;
    vector<3> position;

    linear_eased<float> pitch, volume;
    float stop_delay = 0.0f;

    sound();

    sound(sound const &) = delete;
    sound(sound &&) = delete;
    sound& operator=(sound const &) = delete;
    sound& operator=(sound &&) = delete;
};

}
}
}
}
}


text:
ALTER TABLE environment_authentication ADD COLUMN IF NOT EXISTS managedkey BOOLEAN;

UPDATE environment_authentication SET managedkey = false;

-- //@UNDO
-- SQL to undo the change goes here.

ALTER TABLE environment_authentication DROP COLUMN IF EXISTS managedkey;


text:
package asw.efood.common.api.command;

public interface Command {

}


text:
@interface NameAndColorCell()
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutlet UILabel *colorLabel;

@end

@implementation NameAndColorCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
//        CGRect nameLabelRect = CGRectMake(0, 5, 70, 15);
//        UILabel *nameMarker = [[UILabel alloc] initWithFrame:nameLabelRect];
//        nameMarker.textAlignment = NSTextAlignmentRight;
//        nameMarker.text = @"name";
//        nameMarker.font = [UIFont boldSystemFontOfSize:12];
//        [self.contentView addSubview:nameMarker];
//
//        CGRect colorLabelRect = CGRectMake(0, 26, 70, 15);
//        UILabel *coloerMaker = [[UILabel alloc] initWithFrame:colorLabelRect];
//        coloerMaker.textAlignment = NSTextAlignmentRight;
//        coloerMaker.text = @"Color:";
//        coloerMaker.font = [UIFont boldSystemFontOfSize:12];
//        [self.contentView addSubview:coloerMaker];
//
//        CGRect nameValueRect = CGRectMake(80, 5, 200, 15);
//        _nameLabel = [[UILabel alloc] initWithFrame:nameValueRect];
//        [self.contentView addSubview:_nameLabel];
//
//        CGRect colorValueRect = CGRectMake(80, 25, 200, 15);
//        _colorLabel = [[UILabel alloc] initWithFrame:colorValueRect];
//        [self.contentView addSubview:_colorLabel];
    }
    return self;
}

- (void)setName:(NSString *)name{
    if (![name isEqualToString:_name]) {
        _name = [name copy];
        self.nameLabel.text = _name;
    }
}

- (void)setColor:(NSString *)color{
    if (![color isEqualToString:_color]) {
        _color = [color copy];
        self.colorLabel.text = _color;
    }
}
@end


text:
"""JointMap Tests."""

# Dependency imports

import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.bijectors import bijector_test_util
from tensorflow_probability.python.bijectors import exp
from tensorflow_probability.python.bijectors import invert
from tensorflow_probability.python.bijectors import joint_map
from tensorflow_probability.python.bijectors import ldj_ratio
from tensorflow_probability.python.bijectors import reshape
from tensorflow_probability.python.bijectors import scale
from tensorflow_probability.python.bijectors import shift
from tensorflow_probability.python.bijectors import softplus
from tensorflow_probability.python.internal import test_util

@test_util.test_all_tf_execution_regimes
class JointMapBijectorTest(test_util.TestCase):
  """Tests the correctness of the Y = JointMap({nested}) transformation."""

  def assertShapeIs(self, expect_shape, observed):
    self.assertEqual(expect_shape, np.asarray(observed))

  def testBijector(self):
    bij = joint_map.JointMap({
        'a': exp.Exp(),
        'b': scale.Scale(2.),
        'c': shift.Shift(3.)
    })

    a = np.asarray([[[1, 2], [2, 3]]], dtype=np.float32)   # shape=[1, 2, 2]
    b = np.asarray([[0, 4]], dtype=np.float32)             # shape=[1, 2]
    c = np.asarray([[5, 6]], dtype=np.float32)             # shape=[1, 2]

    inputs = {'a': a, 'b': b, 'c': c}  # Could be inputs to forward or inverse.
    event_ndims = {'a': 1, 'b': 0, 'c': 0}

    self.assertStartsWith(bij.name, 'jointmap_of_exp_and_scale')
    self.assertAllCloseNested({'a': np.exp(a), 'b': b * 2., 'c': c + 3},
                              self.evaluate(bij.forward(inputs)))
    self.assertAllCloseNested({'a': np.log(a), 'b': b / 2., 'c': c - 3},
                              self.evaluate(bij.inverse(inputs)))

    fldj = self.evaluate(bij.forward_log_det_jacobian(inputs, event_ndims))
    self.assertEqual((1, 2), fldj.shape)
    self.assertAllClose(np.sum(a, axis=-1) + np.log(2), fldj)

    ildj = self.evaluate(bij.inverse_log_det_jacobian(inputs, event_ndims))
    self.assertEqual((1, 2), ildj.shape)
    self.assertAllClose(-np.log(a).sum(axis=-1) - np.log(2), ildj)

  def testBijectorWithDeepStructure(self):
    bij = joint_map.JointMap({
        'a': exp.Exp(),
        'bc': joint_map.JointMap([scale.Scale(2.),
                                  shift.Shift(3.)])
    })

    a = np.asarray([[[1, 2], [2, 3]]], dtype=np.float32)   # shape=[1, 2, 2]
    b = np.asarray([[0, 4]], dtype=np.float32)             # shape=[1, 2]
    c = np.asarray([[5, 6]], dtype=np.float32)             # shape=[1, 2]

    inputs = {'a': a, 'bc': [b, c]}  # Could be inputs to forward or inverse.
    event_ndims = {'a': 1, 'bc': [0, 0]}

    self.assertStartsWith(bij.name, 'jointmap_of_exp_and_jointmap_of_')
    self.assertAllCloseNested({'a': np.exp(a), 'bc': [b * 2., c + 3]},
                              self.evaluate(bij.forward(inputs)))
    self.assertAllCloseNested({'a': np.log(a), 'bc': [b / 2., c - 3]},
                              self.evaluate(bij.inverse(inputs)))

    fldj = self.evaluate(bij.forward_log_det_jacobian(inputs, event_ndims))
    self.assertEqual((1, 2), fldj.shape)
    self.assertAllClose(np.sum(a, axis=-1) + np.log(2), fldj)

    ildj = self.evaluate(bij.inverse_log_det_jacobian(inputs, event_ndims))
    self.assertEqual((1, 2), ildj.shape)
    self.assertAllClose(-np.log(a).sum(axis=-1) - np.log(2), ildj)

  def testBatchShapeBroadcasts(self):
    bij = joint_map.JointMap({
        'a': exp.Exp(),
        'b': scale.Scale(10.)
    },
                             validate_args=True)
    self.assertStartsWith(bij.name, 'jointmap_of_exp_and_scale')

    a = np.asarray([[[1, 2]], [[2, 3]]], dtype=np.float32)  # shape=[2, 1, 2]
    b = np.asarray([[0, 1, 2]], dtype=np.float32)  # shape=[1, 3]

    inputs = {'a': a, 'b': b}  # Could be inputs to forward or inverse.

    self.assertAllClose(
        a.sum(axis=-1) + np.log(10.),
        self.evaluate(bij.forward_log_det_jacobian(inputs, {'a': 1, 'b': 0})))

    self.assertAllClose(
        a.sum(axis=-1) + 3 * np.log(10.),
        self.evaluate(bij.forward_log_det_jacobian(inputs, {'a': 1, 'b': 1})))

  @test_util.disable_test_for_backend(
      disable_numpy=True,
      reason='NumPy backend overrides dtypes in __init__.')
  def testMixedDtypeLogDetJacobian(self):
    bij = joint_map.JointMap({
        'a': scale.Scale(tf.constant(1, dtype=tf.float16)),
        'b': scale.Scale(tf.constant(2, dtype=tf.float32)),
        'c': scale.Scale(tf.constant(3, dtype=tf.float64))
    })

    fldj = bij.forward_log_det_jacobian(
        x={'a': 4, 'b': 5, 'c': 6},
        event_ndims=dict.fromkeys('abc', 0))
    self.assertDTypeEqual(fldj, np.float64)
    self.assertAllClose(np.log(1) + np.log(2) + np.log(3), self.evaluate(fldj))

  def test_inverse_has_event_ndims(self):
    bij_reshape = invert.Invert(joint_map.JointMap([reshape.Reshape([])]))
    bij_reshape.inverse_event_ndims([10])  # expect [9]
    self.assertEqual(bij_reshape.inverse_event_ndims([10]), [9])

  @test_util.disable_test_for_backend(
      disable_numpy=True, disable_jax=True,
      reason='Numpy and JAX have no notion of CompositeTensor/saved_model.')
  def testCompositeTensor(self):
    e = exp.Exp()
    sp = softplus.Softplus()
    aff = scale.Scale(scale=2.)
    bij = joint_map.JointMap(bijectors=[e, sp, aff])
    self.assertIsInstance(bij, tf.__internal__.CompositeTensor)

    # Bijector may be flattened into `Tensor` components and rebuilt.
    flat = tf.nest.flatten(bij, expand_composites=True)
    unflat = tf.nest.pack_sequence_as(bij, flat, expand_composites=True)
    self.assertIsInstance(unflat, joint_map.JointMap)

    # Bijector may be input to a `tf.function`-decorated callable.
    @tf.function
    def call_forward(bij, x):
      return bij.forward(x)

    x = [1., 2., 3.]
    self.assertAllCloseNested(call_forward(unflat, x), bij.forward(x))

    # Type spec can be encoded/decoded.
    enc = tf.__internal__.saved_model.encode_structure(bij._type_spec)
    dec = tf.__internal__.saved_model.decode_proto(enc)
    self.assertEqual(bij._type_spec, dec)

  def testNonCompositeTensor(self):
    e = exp.Exp()
    s = bijector_test_util.NonCompositeTensorScale(scale=tf.constant(3.))
    bij = joint_map.JointMap(bijectors=[e, s])
    self.assertNotIsInstance(bij, tf.__internal__.CompositeTensor)
    self.assertAllCloseNested(
        bij.forward([1., 1.]), [e.forward(1.), s.forward(1.)])

  def testLDJRatio(self):
    q = joint_map.JointMap({
        'a': exp.Exp(),
        'b': scale.Scale(2.),
        'c': shift.Shift(3.)
    })
    p = joint_map.JointMap({
        'a': exp.Exp(),
        'b': scale.Scale(3.),
        'c': shift.Shift(4.)
    })

    a = np.asarray([[[1, 2], [2, 3]]], dtype=np.float32)   # shape=[1, 2, 2]
    b = np.asarray([[0, 4]], dtype=np.float32)             # shape=[1, 2]
    c = np.asarray([[5, 6]], dtype=np.float32)             # shape=[1, 2]

    x = {'a': a, 'b': b, 'c': c}
    y = {'a': a + 1, 'b': b + 1, 'c': c + 1}
    event_ndims = {'a': 1, 'b': 0, 'c': 0}

    fldj_ratio_true = p.forward_log_det_jacobian(
        x, event_ndims) - q.forward_log_det_jacobian(y, event_ndims)
    fldj_ratio = ldj_ratio.forward_log_det_jacobian_ratio(
        p, x, q, y, event_ndims)
    self.assertAllClose(fldj_ratio_true, fldj_ratio)

    ildj_ratio_true = p.inverse_log_det_jacobian(
        x, event_ndims) - q.inverse_log_det_jacobian(y, event_ndims)
    ildj_ratio = ldj_ratio.inverse_log_det_jacobian_ratio(
        p, x, q, y, event_ndims)
    self.assertAllClose(ildj_ratio_true, ildj_ratio)

    event_ndims = {'a': 1, 'b': 2, 'c': 0}

    fldj_ratio_true = p.forward_log_det_jacobian(
        x, event_ndims) - q.forward_log_det_jacobian(y, event_ndims)
    fldj_ratio = ldj_ratio.forward_log_det_jacobian_ratio(
        p, x, q, y, event_ndims)
    self.assertAllClose(fldj_ratio_true, fldj_ratio)

    ildj_ratio_true = p.inverse_log_det_jacobian(
        x, event_ndims) - q.inverse_log_det_jacobian(y, event_ndims)
    ildj_ratio = ldj_ratio.inverse_log_det_jacobian_ratio(
        p, x, q, y, event_ndims)
    self.assertAllClose(ildj_ratio_true, ildj_ratio)

if __name__ == '__main__':
  test_util.main()


text:
package vn.edu.vnu.uet.nlp.smt.extended;

import vn.edu.vnu.uet.nlp.smt.utils.Utils;

public class SingleAlignment {
	int src;
	int trg;

	private int hashCode;

	public SingleAlignment(int src, int trg) {
		super();
		this.src = src;
		this.trg = trg;
		hashCode = Utils.generateTwoIntegersHashCode(src, trg);
	}

	public int getSrc() {
		return src;
	}

	public int getTrg() {
		return trg;
	}

	@Override
	public int hashCode() {
		return hashCode;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		SingleAlignment other = (SingleAlignment) obj;
		if (other.hashCode() != obj.hashCode())
			return false;
		return true;
	}

}


text:
<!DOCTYPE html>

    <title>Introduction Question: Efficiency 2</title>

Which of these is NOT a definition for
            efficiency in a computer program?

It runs in linear time

It solves the problem within the required resource contraints

It requires fewer resources than known alternatives

One definition for an efficient program is that it runs
              within the required resource constraints.

One definition for an efficient program is that it
              requires fewer resources than known alternatives.

Many efficient programs require more than linear
              time. Sometimes linear time is not efficient for a given
              problem.


text:
package org.apache.flink.runtime.io.network.partition.consumer;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.core.memory.MemorySegmentProvider;
import org.apache.flink.runtime.event.TaskEvent;
import org.apache.flink.runtime.io.network.ConnectionID;
import org.apache.flink.runtime.io.network.ConnectionManager;
import org.apache.flink.runtime.io.network.PartitionRequestClient;
import org.apache.flink.runtime.io.network.buffer.Buffer;
import org.apache.flink.runtime.io.network.buffer.BufferListener;
import org.apache.flink.runtime.io.network.buffer.BufferProvider;
import org.apache.flink.runtime.io.network.buffer.BufferRecycler;
import org.apache.flink.runtime.io.network.buffer.NetworkBuffer;
import org.apache.flink.runtime.io.network.metrics.InputChannelMetrics;
import org.apache.flink.runtime.io.network.partition.PartitionNotFoundException;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.util.ExceptionUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;

import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;

/**
 * An input channel, which requests a remote partition queue.
 */
public class RemoteInputChannel extends InputChannel implements BufferRecycler, BufferListener {

	/** ID to distinguish this channel from other channels sharing the same TCP connection. */
	private final InputChannelID id = new InputChannelID();

	/** The connection to use to request the remote partition. */
	private final ConnectionID connectionId;

	/** The connection manager to use connect to the remote partition provider. */
	private final ConnectionManager connectionManager;

	/**
	 * The received buffers. Received buffers are enqueued by the network I/O thread and the queue
	 * is consumed by the receiving task thread.
	 */
	private final ArrayDeque<Buffer> receivedBuffers = new ArrayDeque<>();

	/**
	 * Flag indicating whether this channel has been released. Either called by the receiving task
	 * thread or the task manager actor.
	 */
	private final AtomicBoolean isReleased = new AtomicBoolean();

	/** Client to establish a (possibly shared) TCP connection and request the partition. */
	private volatile PartitionRequestClient partitionRequestClient;

	/**
	 * The next expected sequence number for the next buffer. This is modified by the network
	 * I/O thread only.
	 */
	private int expectedSequenceNumber = 0;

	/** The initial number of exclusive buffers assigned to this channel. */
	private int initialCredit;

	/** The available buffer queue wraps both exclusive and requested floating buffers. */
	private final AvailableBufferQueue bufferQueue = new AvailableBufferQueue();

	/** The number of available buffers that have not been announced to the producer yet. */
	private final AtomicInteger unannouncedCredit = new AtomicInteger(0);

	/** The number of required buffers that equals to sender's backlog plus initial credit. */
	@GuardedBy("bufferQueue")
	private int numRequiredBuffers;

	/** The tag indicates whether this channel is waiting for additional floating buffers from the buffer pool. */
	@GuardedBy("bufferQueue")
	private boolean isWaitingForFloatingBuffers;

	/** Global memory segment provider to request and recycle exclusive buffers (only for credit-based). */
	@Nonnull
	private final MemorySegmentProvider memorySegmentProvider;

	public RemoteInputChannel(
		SingleInputGate inputGate,
		int channelIndex,
		ResultPartitionID partitionId,
		ConnectionID connectionId,
		ConnectionManager connectionManager,
		int initialBackOff,
		int maxBackoff,
		InputChannelMetrics metrics,
		@Nonnull MemorySegmentProvider memorySegmentProvider) {

		super(inputGate, channelIndex, partitionId, initialBackOff, maxBackoff,
			metrics.getNumBytesInRemoteCounter(), metrics.getNumBuffersInRemoteCounter());

		this.connectionId = checkNotNull(connectionId);
		this.connectionManager = checkNotNull(connectionManager);
		this.memorySegmentProvider = memorySegmentProvider;
	}

	/**
	 * Assigns exclusive buffers to this input channel, and this method should be called only once
	 * after this input channel is created.
	 */
	void assignExclusiveSegments() throws IOException {
		checkState(initialCredit == 0, "Bug in input channel setup logic: exclusive buffers have " +
			"already been set for this input channel.");

		Collection<MemorySegment> segments = checkNotNull(memorySegmentProvider.requestMemorySegments());
		checkArgument(!segments.isEmpty(), "The number of exclusive buffers per channel should be larger than 0.");

		initialCredit = segments.size();
		numRequiredBuffers = segments.size();

		synchronized (bufferQueue) {
			for (MemorySegment segment : segments) {
				bufferQueue.addExclusiveBuffer(new NetworkBuffer(segment, this), numRequiredBuffers);
			}
		}
	}

	// ------------------------------------------------------------------------
	// Consume
	// ------------------------------------------------------------------------

	/**
	 * Requests a remote subpartition.
	 */
	@VisibleForTesting
	@Override
	public void requestSubpartition(int subpartitionIndex) throws IOException, InterruptedException {
		if (partitionRequestClient == null) {
			// Create a client and request the partition
			try {
				partitionRequestClient = connectionManager.createPartitionRequestClient(connectionId);
			} catch (IOException e) {
				// IOExceptions indicate that we could not open a connection to the remote TaskExecutor
				throw new PartitionConnectionException(partitionId, e);
			}

			partitionRequestClient.requestSubpartition(partitionId, subpartitionIndex, this, 0);
		}
	}

	/**
	 * Retriggers a remote subpartition request.
	 */
	void retriggerSubpartitionRequest(int subpartitionIndex) throws IOException {
		checkState(partitionRequestClient != null, "Missing initial subpartition request.");

		if (increaseBackoff()) {
			partitionRequestClient.requestSubpartition(
				partitionId, subpartitionIndex, this, getCurrentBackoff());
		} else {
			failPartitionRequest();
		}
	}

	@Override
	Optional<BufferAndAvailability> getNextBuffer() throws IOException {
		checkState(!isReleased.get(), "Queried for a buffer after channel has been closed.");
		checkState(partitionRequestClient != null, "Queried for a buffer before requesting a queue.");

		checkError();

		final Buffer next;
		final boolean moreAvailable;

		synchronized (receivedBuffers) {
			next = receivedBuffers.poll();
			moreAvailable = !receivedBuffers.isEmpty();
		}

		numBytesIn.inc(next.getSize());
		numBuffersIn.inc();
		return Optional.of(new BufferAndAvailability(next, moreAvailable, getSenderBacklog()));
	}

	// ------------------------------------------------------------------------
	// Task events
	// ------------------------------------------------------------------------

	@Override
	void sendTaskEvent(TaskEvent event) throws IOException {
		checkState(!isReleased.get(), "Tried to send task event to producer after channel has been released.");
		checkState(partitionRequestClient != null, "Tried to send task event to producer before requesting a queue.");

		checkError();

		partitionRequestClient.sendTaskEvent(partitionId, event, this);
	}

	// ------------------------------------------------------------------------
	// Life cycle
	// ------------------------------------------------------------------------

	@Override
	public boolean isReleased() {
		return isReleased.get();
	}

	@Override
	void notifySubpartitionConsumed() {
		// Nothing to do
	}

	/**
	 * Releases all exclusive and floating buffers, closes the partition request client.
	 */
	@Override
	void releaseAllResources() throws IOException {
		if (isReleased.compareAndSet(false, true)) {

			// Gather all exclusive buffers and recycle them to global pool in batch, because
			// we do not want to trigger redistribution of buffers after each recycle.
			final List<MemorySegment> exclusiveRecyclingSegments = new ArrayList<>();

			synchronized (receivedBuffers) {
				Buffer buffer;
				while ((buffer = receivedBuffers.poll()) != null) {
					if (buffer.getRecycler() == this) {
						exclusiveRecyclingSegments.add(buffer.getMemorySegment());
					} else {
						buffer.recycleBuffer();
					}
				}
			}
			synchronized (bufferQueue) {
				bufferQueue.releaseAll(exclusiveRecyclingSegments);
			}

			if (exclusiveRecyclingSegments.size() > 0) {
				memorySegmentProvider.recycleMemorySegments(exclusiveRecyclingSegments);
			}

			// The released flag has to be set before closing the connection to ensure that
			// buffers received concurrently with closing are properly recycled.
			if (partitionRequestClient != null) {
				partitionRequestClient.close(this);
			} else {
				connectionManager.closeOpenChannelConnections(connectionId);
			}
		}
	}

	private void failPartitionRequest() {
		setError(new PartitionNotFoundException(partitionId));
	}

	@Override
	public String toString() {
		return "RemoteInputChannel [" + partitionId + " at " + connectionId + "]";
	}

	// ------------------------------------------------------------------------
	// Credit-based
	// ------------------------------------------------------------------------

	/**
	 * Enqueue this input channel in the pipeline for notifying the producer of unannounced credit.
	 */
	private void notifyCreditAvailable() {
		checkState(partitionRequestClient != null, "Tried to send task event to producer before requesting a queue.");

		partitionRequestClient.notifyCreditAvailable(this);
	}

	/**
	 * Exclusive buffer is recycled to this input channel directly and it may trigger return extra
	 * floating buffer and notify increased credit to the producer.
	 *
	 * @param segment The exclusive segment of this channel.
	 */
	@Override
	public void recycle(MemorySegment segment) {
		int numAddedBuffers;

		synchronized (bufferQueue) {
			// Similar to notifyBufferAvailable(), make sure that we never add a buffer
			// after releaseAllResources() released all buffers (see below for details).
			if (isReleased.get()) {
				try {
					memorySegmentProvider.recycleMemorySegments(Collections.singletonList(segment));
					return;
				} catch (Throwable t) {
					ExceptionUtils.rethrow(t);
				}
			}
			numAddedBuffers = bufferQueue.addExclusiveBuffer(new NetworkBuffer(segment, this), numRequiredBuffers);
		}

		if (numAddedBuffers > 0 && unannouncedCredit.getAndAdd(numAddedBuffers) == 0) {
			notifyCreditAvailable();
		}
	}

	public int getNumberOfAvailableBuffers() {
		synchronized (bufferQueue) {
			return bufferQueue.getAvailableBufferSize();
		}
	}

	public int getNumberOfRequiredBuffers() {
		return numRequiredBuffers;
	}

	public int getSenderBacklog() {
		return numRequiredBuffers - initialCredit;
	}

	@VisibleForTesting
	boolean isWaitingForFloatingBuffers() {
		return isWaitingForFloatingBuffers;
	}

	/**
	 * The Buffer pool notifies this channel of an available floating buffer. If the channel is released or
	 * currently does not need extra buffers, the buffer should be returned to the buffer pool. Otherwise,
	 * the buffer will be added into the <tt>bufferQueue</tt> and the unannounced credit is increased
	 * by one.
	 *
	 * @param buffer Buffer that becomes available in buffer pool.
	 * @return NotificationResult indicates whether this channel accepts the buffer and is waiting for
	 *  	more floating buffers.
	 */
	@Override
	public NotificationResult notifyBufferAvailable(Buffer buffer) {
		NotificationResult notificationResult = NotificationResult.BUFFER_NOT_USED;
		try {
			synchronized (bufferQueue) {
				checkState(isWaitingForFloatingBuffers,
					"This channel should be waiting for floating buffers.");

				// Important: make sure that we never add a buffer after releaseAllResources()
				// released all buffers. Following scenarios exist:
				// 1) releaseAllResources() already released buffers inside bufferQueue
				// -> then isReleased is set correctly
				// 2) releaseAllResources() did not yet release buffers from bufferQueue
				// -> we may or may not have set isReleased yet but will always wait for the
				// lock on bufferQueue to release buffers
				if (isReleased.get() || bufferQueue.getAvailableBufferSize() >= numRequiredBuffers) {
					isWaitingForFloatingBuffers = false;
					return notificationResult;
				}

				bufferQueue.addFloatingBuffer(buffer);

				if (bufferQueue.getAvailableBufferSize() == numRequiredBuffers) {
					isWaitingForFloatingBuffers = false;
					notificationResult = NotificationResult.BUFFER_USED_NO_NEED_MORE;
				} else {
					notificationResult = NotificationResult.BUFFER_USED_NEED_MORE;
				}
			}

			if (unannouncedCredit.getAndAdd(1) == 0) {
				notifyCreditAvailable();
			}
		} catch (Throwable t) {
			setError(t);
		}
		return notificationResult;
	}

	@Override
	public void notifyBufferDestroyed() {
		// Nothing to do actually.
	}

	// ------------------------------------------------------------------------
	// Network I/O notifications (called by network I/O thread)
	// ------------------------------------------------------------------------

	/**
	 * Gets the currently unannounced credit.
	 *
	 * @return Credit which was not announced to the sender yet.
	 */
	public int getUnannouncedCredit() {
		return unannouncedCredit.get();
	}

	/**
	 * Gets the unannounced credit and resets it to <tt>0</tt> atomically.
	 *
	 * @return Credit which was not announced to the sender yet.
	 */
	public int getAndResetUnannouncedCredit() {
		return unannouncedCredit.getAndSet(0);
	}

	/**
	 * Gets the current number of received buffers which have not been processed yet.
	 *
	 * @return Buffers queued for processing.
	 */
	public int getNumberOfQueuedBuffers() {
		synchronized (receivedBuffers) {
			return receivedBuffers.size();
		}
	}

	public int unsynchronizedGetNumberOfQueuedBuffers() {
		return Math.max(0, receivedBuffers.size());
	}

	public int unsynchronizedGetExclusiveBuffersUsed() {
		return Math.max(0, initialCredit - bufferQueue.exclusiveBuffers.size());
	}

	public int unsynchronizedGetFloatingBuffersAvailable() {
		return Math.max(0, bufferQueue.floatingBuffers.size());
	}

	public InputChannelID getInputChannelId() {
		return id;
	}

	public int getInitialCredit() {
		return initialCredit;
	}

	public BufferProvider getBufferProvider() throws IOException {
		if (isReleased.get()) {
			return null;
		}

		return inputGate.getBufferProvider();
	}

	/**
	 * Requests buffer from input channel directly for receiving network data.
	 * It should always return an available buffer in credit-based mode unless
	 * the channel has been released.
	 *
	 * @return The available buffer.
	 */
	@Nullable
	public Buffer requestBuffer() {
		synchronized (bufferQueue) {
			return bufferQueue.takeBuffer();
		}
	}

	/**
	 * Receives the backlog from the producer's buffer response. If the number of available
	 * buffers is less than backlog + initialCredit, it will request floating buffers from the buffer
	 * pool, and then notify unannounced credits to the producer.
	 *
	 * @param backlog The number of unsent buffers in the producer's sub partition.
	 */
	void onSenderBacklog(int backlog) throws IOException {
		int numRequestedBuffers = 0;

		synchronized (bufferQueue) {
			// Similar to notifyBufferAvailable(), make sure that we never add a buffer
			// after releaseAllResources() released all buffers (see above for details).
			if (isReleased.get()) {
				return;
			}

			numRequiredBuffers = backlog + initialCredit;
			while (bufferQueue.getAvailableBufferSize() < numRequiredBuffers && !isWaitingForFloatingBuffers) {
				Buffer buffer = inputGate.getBufferPool().requestBuffer();
				if (buffer != null) {
					bufferQueue.addFloatingBuffer(buffer);
					numRequestedBuffers++;
				} else if (inputGate.getBufferProvider().addBufferListener(this)) {
					// If the channel has not got enough buffers, register it as listener to wait for more floating buffers.
					isWaitingForFloatingBuffers = true;
					break;
				}
			}
		}

		if (numRequestedBuffers > 0 && unannouncedCredit.getAndAdd(numRequestedBuffers) == 0) {
			notifyCreditAvailable();
		}
	}

	public void onBuffer(Buffer buffer, int sequenceNumber, int backlog) throws IOException {
		boolean recycleBuffer = true;

		try {

			final boolean wasEmpty;
			synchronized (receivedBuffers) {
				// Similar to notifyBufferAvailable(), make sure that we never add a buffer
				// after releaseAllResources() released all buffers from receivedBuffers
				// (see above for details).
				if (isReleased.get()) {
					return;
				}

				if (expectedSequenceNumber != sequenceNumber) {
					onError(new BufferReorderingException(expectedSequenceNumber, sequenceNumber));
					return;
				}

				wasEmpty = receivedBuffers.isEmpty();
				receivedBuffers.add(buffer);
				recycleBuffer = false;
			}

			++expectedSequenceNumber;

			if (wasEmpty) {
				notifyChannelNonEmpty();
			}

			if (backlog >= 0) {
				onSenderBacklog(backlog);
			}
		} finally {
			if (recycleBuffer) {
				buffer.recycleBuffer();
			}
		}
	}

	public void onEmptyBuffer(int sequenceNumber, int backlog) throws IOException {
		boolean success = false;

		synchronized (receivedBuffers) {
			if (!isReleased.get()) {
				if (expectedSequenceNumber == sequenceNumber) {
					expectedSequenceNumber++;
					success = true;
				} else {
					onError(new BufferReorderingException(expectedSequenceNumber, sequenceNumber));
				}
			}
		}

		if (success && backlog >= 0) {
			onSenderBacklog(backlog);
		}
	}

	public void onFailedPartitionRequest() {
		inputGate.triggerPartitionStateCheck(partitionId);
	}

	public void onError(Throwable cause) {
		setError(cause);
	}

	private static class BufferReorderingException extends IOException {

		private static final long serialVersionUID = -888282210356266816L;

		private final int expectedSequenceNumber;

		private final int actualSequenceNumber;

		BufferReorderingException(int expectedSequenceNumber, int actualSequenceNumber) {
			this.expectedSequenceNumber = expectedSequenceNumber;
			this.actualSequenceNumber = actualSequenceNumber;
		}

		@Override
		public String getMessage() {
			return String.format("Buffer re-ordering: expected buffer with sequence number %d, but received %d.",
				expectedSequenceNumber, actualSequenceNumber);
		}
	}

	/**
	 * Manages the exclusive and floating buffers of this channel, and handles the
	 * internal buffer related logic.
	 */
	private static class AvailableBufferQueue {

		/** The current available floating buffers from the fixed buffer pool. */
		private final ArrayDeque<Buffer> floatingBuffers;

		/** The current available exclusive buffers from the global buffer pool. */
		private final ArrayDeque<Buffer> exclusiveBuffers;

		AvailableBufferQueue() {
			this.exclusiveBuffers = new ArrayDeque<>();
			this.floatingBuffers = new ArrayDeque<>();
		}

		/**
		 * Adds an exclusive buffer (back) into the queue and recycles one floating buffer if the
		 * number of available buffers in queue is more than the required amount.
		 *
		 * @param buffer The exclusive buffer to add
		 * @param numRequiredBuffers The number of required buffers
		 *
		 * @return How many buffers were added to the queue
		 */
		int addExclusiveBuffer(Buffer buffer, int numRequiredBuffers) {
			exclusiveBuffers.add(buffer);
			if (getAvailableBufferSize() > numRequiredBuffers) {
				Buffer floatingBuffer = floatingBuffers.poll();
				floatingBuffer.recycleBuffer();
				return 0;
			} else {
				return 1;
			}
		}

		void addFloatingBuffer(Buffer buffer) {
			floatingBuffers.add(buffer);
		}

		/**
		 * Takes the floating buffer first in order to make full use of floating
		 * buffers reasonably.
		 *
		 * @return An available floating or exclusive buffer, may be null
		 * if the channel is released.
		 */
		@Nullable
		Buffer takeBuffer() {
			if (floatingBuffers.size() > 0) {
				return floatingBuffers.poll();
			} else {
				return exclusiveBuffers.poll();
			}
		}

		/**
		 * The floating buffer is recycled to local buffer pool directly, and the
		 * exclusive buffer will be gathered to return to global buffer pool later.
		 *
		 * @param exclusiveSegments The list that we will add exclusive segments into.
		 */
		void releaseAll(List<MemorySegment> exclusiveSegments) {
			Buffer buffer;
			while ((buffer = floatingBuffers.poll()) != null) {
				buffer.recycleBuffer();
			}
			while ((buffer = exclusiveBuffers.poll()) != null) {
				exclusiveSegments.add(buffer.getMemorySegment());
			}
		}

		int getAvailableBufferSize() {
			return floatingBuffers.size() + exclusiveBuffers.size();
		}
	}
}


text:
using System;
using System.Data;

namespace Vertigo.Live
{
    public abstract class SqlBulkCopyReader : IDataReader
    {
        // derived must implement only these three
        public abstract bool Read();
        public abstract object GetValue(int i);
        public abstract int FieldCount { get; }

        // empty methods derived classes may want to implement
        public virtual int GetOrdinal(string name) { throw new NotImplementedException(); }
        public virtual void Close() { }
        public virtual void Dispose() { }
        public virtual object this[int i] { get { throw new NotImplementedException(); } }
        public virtual int Depth { get { throw new NotImplementedException(); } }
        public virtual bool IsClosed { get { throw new NotImplementedException(); } }
        public virtual int RecordsAffected { get { throw new NotImplementedException(); } }
        public virtual DataTable GetSchemaTable() { throw new NotImplementedException(); }
        public virtual bool NextResult() { throw new NotImplementedException(); }
        public virtual object this[string name] { get { throw new NotImplementedException(); } }
        public virtual bool GetBoolean(int i) { throw new NotImplementedException(); }
        public virtual byte GetByte(int i) { throw new NotImplementedException(); }
        public virtual long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { throw new NotImplementedException(); }
        public virtual char GetChar(int i) { throw new NotImplementedException(); }
        public virtual long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { throw new NotImplementedException(); }
        public virtual IDataReader GetData(int i) { throw new NotImplementedException(); }
        public virtual string GetDataTypeName(int i) { throw new NotImplementedException(); }
        public virtual DateTime GetDateTime(int i) { throw new NotImplementedException(); }
        public virtual decimal GetDecimal(int i) { throw new NotImplementedException(); }
        public virtual double GetDouble(int i) { throw new NotImplementedException(); }
        public virtual Type GetFieldType(int i) { throw new NotImplementedException(); }
        public virtual float GetFloat(int i) { throw new NotImplementedException(); }
        public virtual Guid GetGuid(int i) { throw new NotImplementedException(); }
        public virtual short GetInt16(int i) { throw new NotImplementedException(); }
        public virtual int GetInt32(int i) { throw new NotImplementedException(); }
        public virtual long GetInt64(int i) { throw new NotImplementedException(); }
        public virtual string GetName(int i) { throw new NotImplementedException(); }
        public virtual string GetString(int i) { throw new NotImplementedException(); }
        public virtual int GetValues(object[] values) { throw new NotImplementedException(); }
        public virtual bool IsDBNull(int i) { throw new NotImplementedException(); }
    }
}


text:
title: "Asteroids & Netwire"
-----

Since my initial foray into functional reactive programming using Netwire, I
decided to challenge my newly acquired knowledge by attempting a larger project.
I eventually decided to build a clone of the classic Atari game -
[Asteroids](https://en.wikipedia.org/wiki/Asteroids_%28arcade_game%29). I'm happy
to announce that I've now reached a point at which I'm happy to call this
complete, and want to share my findings with you in this blog post. Before we go
into that, here's a look at the finished product:

<iframe width="420" height="315" src="//www.youtube.com/embed/0A63Wc4xLIc" frameborder="0" allowfullscreen></iframe>

## Why Asteroids?

I chose Asteroids as it felt like a complete game that would require solving a
few distinct challenges. Firstly, Asteroids features different types of objects - the
player's ship, the asteroids themselves, bullets, and UFOs. Each of these
objects have slightly different behaviours - both on their own and when
interacting with other objects. For example, the player ship can be interacted
with by the player, but also destroyed by asteroids and UFOs.

Asteroids is also one of the simplest dynamic worlds I can think of. The amount
of objects on screen varies with time, and each object has an independent life
time. Independent objects with variable lifetimes are an integral part of
almost any game now, so I decided to start simple and see if I could uncover any
elementary approaches to this.

Another important aspect of any game is that of varying state. The game
itself varies in state depending on the number of asteroids on screen. When the
count reaches zero, the game starts again with a higher number of asteroids and
the score roles over. This management of a state at a much granular level than
frame by frame motion felt like it would be an area worth exploring.

Finally, Asteroids felt like an achievable goal for a single person still
learning technology. The rendering is extremely simplistic, as are the physics
themselves. Because of this, I was able to go a little further than planned, and
ended up building a small sound engine and particle system.

## Proud Moments

Along with finishing the game itself, there are a few smaller parts of the
project that I feel especially proud of.

### A Functional Reactive Sound Engine

As I approached the end of the project, I felt like it wasn't a true Asteroids
clone unless I had some lo-fi sounds to accompany gameplay. Feeling confident
with Netwire, I decided it would be fun to synthesize sounds myself with code
rather than using prerecorded sounds. As such, I developed a tiny little
synthesizer using Netwire

As an example, here's how I generate explosion sounds:

```haskell
explosion = decay 2 . gate . (rateReduce &&& 0.4) .  (quantize &&& 500) .
              (noise &&& 0.2)
```

So my explosion sound is random noise, quantized to 20%, sampled at 500hZ, and
gated at 40%. This random noise decays linearly over 2 seconds to 0. After 2
seconds, this wire inhibits. I then use a little function to "render" a `Wire`
to an SDL `Chunk`, and am able to play the sound whenever I need to.

This has made synthesizing sounds a really fun (and especially geeky!)
experience. The sound DSL could be improved; one notable problem is that
currently it's a little strange that parameters aren't quite paired up with the
function they are a parameter too. For example, to apply 20% quantization, one
must write:

```haskell
quantize . (noise &&& 0.2)
```

Which may read more like 0.2 being a parameter to `noise`, not `quantize`. Arrow
notation may help here, but I went for a one-liner than did the job. However,
some sounds are expressed elegantly without arrow notation due to `Wire`s being
instances of the `Num` type class:

```haskell
ufo = for (1 / 3) . sin . ((sin . 3) * 200 + 100)
```

`sin` is a `Wire` taking frequency as input, and producing an amplitude between
-1 and 1. In this sound, I take a 3hZ sine wave, amplify it 200 times and
offset that by 100Hz. I then feed this into another sine oscillator, in order to
produce a pitch that flucuates to produce a cheesy UFO sound. The overloading of
the `Num` type class lets me treat the amplification and offset stages as normal
arithmetic, which I find particularly elegant.

### Particle System

Another bit of polish to the game was adding a rudimentary particle system to
use for asteroid explosions. The particle system itself is just a few lines of
code:

```haskell
particleSystems
  :: (Applicative m, MonadRandom m) => Wire e m [V2 Double] [V2 Double]
particleSystems = go []
 where
  go systems = mkGen $ \dt newSystemLocations -> do
    stepped <- mapM (\w -> stepWire w dt ()) systems

    let alive = [ (r, w) | (Right r, w) <- stepped ]
    spawned <- concat <$> mapM spawnParticles newSystemLocations

    return (Right (map fst alive), go $ map snd alive ++ spawned)

  spawnParticles at = do
    n <- getRandomR (4, 8)
    replicateM n $ do
      velocity <- randomVelocity (5, 10)
      life <- getRandomR (1, 3)
      return ((for life <!> ()). integrateVector at . pure velocity)
```

This wire takes as its input, a list of locations to create new particle
systems. As output, it produces a list of all particles. Each particle system
has a random amount of particles, each alive for a random duration and moving
with a random velocity from the particle systems origin. I wrote this code
essentially in a single attempt, and the output was just what I was looking for.

## Expressive Events

The event system in Netwire takes a while to get your head around, but it can
ultimately lead to succinct expression of events. The `isShooting` event is one
of my favourite's here, and it's defined as:

```haskell
isShooting =
  asSoonAs (keyDown SDL.SDLK_SPACE) >>> (once --> coolDown >>> isShooting)
 where
  coolDown =
    arr head . multicast [ after 0.05, asSoonAs (not . keyDown SDL.SDLK_SPACE) ]
```

This event reads very naturally. The player is shooting as long as the space key
is held down, at which point they shoot once, and then enter a cool down period.
I use `multicast` to combine two events as you would combine booleans under
conjunction with `&&` - inhibiting until both 0.05s have elapsed and the player
has released the space key during or after this interval. Once both of these
criteria are met, the event repeats. This leads to shooting happening at most
once every 0.05s, and requires the player to toggle the space bar - as I find this
type of interaction pleasing for this type of game (as it feels more energetic and
increases tension).

Another similar example of chaining events is to determine when a UFO should
spawn:

```haskell
ufoSpawned = (once --> ufoSpawned) . wackelkontaktM (1 / 1000) . after 30
```

`wackelkontaktM` is an awfully named wire, but it's essentially a wire that only
produces with a given probability. Thus a UFO spawns once after 30 seconds, and
then with a probability of 1/1000. After a UFO spawns, we repeat the event,
waiting at least 30 seconds.

I will admit that these events do take a little bit of trial and error to get
the behaviour you want. Usually, you'll find that wires can be composed in
various different orders, and the composition is not necessarily equal.

For example, we might assume that `ufoSpawned` could be rewriten as:

```haskell
ufoSpawned = once . wackelkontaktM (1 / 1000) . after 30 --> ufoSpawned
```

But this will never spawn UFOs, and has significantly different semantics,
despite reading very similarly. Perhaps this is a drawback of very expressive
DSLs!

## Difficulties

### Understanding ArrowLoop Is Important

In my previous post about Netwire, I said:

> ArrowLoop is far too magical for me to understand [..], but thankfully we have
> arrow notation in Haskell to allow us to easily create loops.

This is true, but it only lets you go so far. As I developed my clone, I needed
to use recursive bindings in order to implement collisions. At that time, I
didn't understand how `ArrowLoop` really worked, and naively assuming that it
wolud Do the Right Thing. The result of such a naive approach can be summarized
with one word and a few symbols that any Haskell programmer would dread to see:
`<<loop>>` - the computation will never produce a value as it forms an infinite
loop.

My original approach attempted to use definitions relative to the current frame
in a mutually recursive way: a frame's collisions depended on the positions
of objects alive in the frame, but the notion of life depended on the current
frame's collisions. As you can see - there is no way to produce an answer if we
phrase equations in this form.

The solution is to understand that ArrowLoop needs a base case, just as
recursion does, in order to produce an answer. I finally solved my problem by
operating on the alive entities from the *previous* frame (using the `delay`
`Wire`), and start with a base case of the empty list on the first frame.

Unfortunately, nothing in the types will prevent you from making such
nonsensical bindings. I wonder if there is a possibility to encode this
information in the type system, and [Productive Programming Using Guarded
Recursion](http://bentnib.org/productive.pdf) immediately comes to mind - though
that paper is still beyond me so it may not apply. Nonetheless, I'm convinced
there may be at least something that can be done.

### Space Leaks

I encountered only a single space leak in my clone, which is extremely
promising. At one stage of development, I needed to improve the rendering of
asteroids from being simple circles to polygons. I decided that it would be
easiest to express asteroids as a list of vector's from the origin of varying
magnitude, and I originally codified this as a behavior such that:

> spikes = keep . randomSpikes

The `keep` `Wire` holds the first value produced by `randomSpikes` and always
produces it thereupon. However, a composition of this form will still do some
work on every frame (even if that work is just building up thunks) up until the
`keep` `Wire` is actually reached. In my case I ended up building up so many
`randomSpike` invocations I eventually exhausted the stack. I didn't spend time
working out why this would cause such a drastic space leak and not get garbage
collected (that may be a bug in the `keep` `Wire`, or it may be in my usage).
Eitherway, naively combining wires like this can bite you - so it's worth seeing
if things can be expressed in a different way. In the end, I chose to improve
the `randomSpikes` wire to produce a single result, and then switch it's
behavior to be a constant wire.

### Managing Wire Collections

It took me a while to formulate a way to express collections of wires that can
grow and shrink. For example, when the player is shooting, a new bullet needs to
join the world and interact with other objects, but should also be able to
destroy itself as bullets have a finite lifetime.

In the end, I ended up pairing behaviour values at specific instants with the
`Wire` that will produce the next instant value. Thus this is almost as if I am
reifying wires themselves. By doing this, I am now able to build a list of
`Wire`s present in the *next* frame based on the *current* values.

I make use of this technique with the main collision `Wire`. `collision` takes
as its input a list of bullet positions, paired with the wire to produce the
position of the bullet at the next frame, and likewise for UFOs and asteroids.
`collision` then filters these lists by taking various Cartesian products and
determine what is colliding at what isn't. The final result is a list of active
bullets, active asteroids, destroyed asteroids, and so on.

I can step a collection of these `Wire`s with the following:

```haskell
stepWires :: Monad m => Wire e m [Wire e m () b] [(b, Wire e m () b)]
stepWires = mkFixM $ \dt objects -> do
  stepped <- mapM (\o -> stepWire o dt ()) objects
  return $ Right [ (o, w') | (Right o, w') <- stepped ]
```

As we can see, this takes a `Wire` collection as input, and produces a list of
behaviours along with their next `Wire`. I'm not convinced this is necessarily
the best way to do this, but it feels like a more functional approach when
compared to other alternatives such as inventing unique identifiers for each
object and storing this all in a `Map`.

## Other Difficulties

The major difficulties I had in implementing this game were inherent to the game
itself, and so while my experience was certainly not bug free, I'm really happy
that the majority of problems were due to bad assumptions about the game logic
itself.

For example, I started with bullets being spawned at the centre of the ship
itself, moving with a fixed velocity determined by the player's rotation. Once I
added player-bullet collisions due to UFO's firing, the player would immediately
explode whenever they shot as their own bullet would collide with themselves for
a single frame. Offsetting the bullet is the easiest fix here.

There are similar bugs due to bad reasoning, such as incosistent vector/matrix
multiplication, but again these were not due to choice of technology. Perhaps these
too could be further reduced by leveraging the type system, but currently I'm
quite happy with the current pragmatic balance between correctness and
programmer productivity.

## Conclusion

I thoroughly enjoyed building this game using Haskell and Netwire - to the point
where I became a little bit addicted to the project. The more I learn about
Netwire, the more fluently I'm able to express certain behaviours very
naturally. Having state encapsulated in each wire independently is an extremely
powerful technique for managing state, and for the most part has meant that I
don't have to think about state at all.

Netwire seems to almost require a certain discipline in programming - but
thankfully it's a discipline that we should all follow as much as possible
anyway. That discipline is short, focused, functions. Everytime I tried to
create complicated wires I ran into problems, and as soon as I started to break
things apart into smaller wires and compose them together I could once again
reason about my program and progress to the desired result.

The event model for Netwire can make it quite simple to add instanteous events,
though again it also requires a little bit of upfront thinking to decide which
type of composition is appropriate.

Hopefully this post should convince people that game programming is certainly
possible. More importantly, game programming in Haskell is possible and it
*doesn't* require threading everything through state monads or otherwise writing
imperative code. Netwire does require a little bit of thinking about how you are
going to phrase certain relationships, but I found that this thinking was at a
very abstract level in order to determine who depends on whom - rather than fine
grained implementation details. This is the type of thinking that I *enjoy*
doing, and expect to do as a programmer. It's fantastic that Netwire lets me
focus on this, allowing me to separate it from the rest of the programming.

The full code to my clone can be found at
[on Github](http://github.com/ocharles/netwire-classics/). If you want to build
it, you'll need `lens`, `linear`, `netwire`, `SDL`, and `SDL-mixer` from
Hackage. I may get round to writing a cabal file for this at some point!


text:
package com.health.surfaceviews;

public class Constants {
//	XXX:Drawing modes
	public static final int FREE_DRAWING = 1000;
	public static final int LINE_DRAWING = 1001;
	public static final int RECT_DRAWING = 1002;
	public static final int SELECT = 1003;

	public static final int WAVE = 1004;
}


text:
This utility is a set of commands to process text data that represent Rubik's cubes and moves via CLI.

## Contents

* [Getting Started](#getting-started)

Command References:

* [rubiks-search](#rubiks-search)
* [rubiks-enumerate](#rubiks-enumerate)
* [rubiks-scramble](#rubiks-scramble)
* [rubiks-apply](#rubiks-apply)
* [rubiks-reverse](#rubiks-reverse)
* [rubiks-mirror](#rubiks-mirror)

Appendix:

* [Cube Notation](#cube-notation)
* [Move Notation](#move-notation)

## Getting Started

### Taking a glance

    $ make
    $ ./bin/rubiks-search -h

### Installing commands

    $ make
    $ [sudo] make install
    $ which rubiks-search
    /usr/local/bin/rubiks-search

Note: The `Makefile` is specifically for `Linux` (or `OS X`). It may not work on `Windows`.

## rubiks-search

Given initial and target Rubik's cube placements as input, the command finds steps that will turn the initial cube into
the target cube.

This is based on a brute-force algorithm that attempts all the combinations of steps to match the cube with the target,
where a simple optimization with parallel slices is applied so that obviously unnecessary steps are omitted.

The maximum search depth is set to 8 by default, which already takes a long time (possibly several hours).
On the other hand, the number of steps required to solve an arbitrary Rubik's cube is known to be 20.
Thus, this program is not useful to solve a generic cube.
In fact, there appear to be no known perfectly optimal algorithm to solve a generic cube.

This program is rather intended to be a simple utility to discover optimal steps for a particular part of practical
methods, such as the LBL method.

### Usage

    $ rubiks-search <<END

           W Y W
           Y W Y
           W Y W

    R O R  B G B  O R O  G B G
    R O R  B G B  O R O  G B G
    R O R  B G B  O R O  G B G

           Y W Y
           W Y W
           Y W Y

           W W W
           W W W
           W W W

    O O O  G G G  R R R  B B B
    O O O  G G G  R R R  B B B
    O O O  G G G  R R R  B B B

           Y Y Y
           Y Y Y
           Y Y Y

    END

Output:

    # Depth: 1
    #  0 result(s)
    # Depth: 2
    #  0 result(s)
    # Depth: 3
    #  0 result(s)
    # Depth: 4
    F2 B2 R2 L2
    R2 L2 F2 B2
    #  2 result(s)

Note: Sample input data files are found in the `data` directory.

### Default Options

    $ rubiks-search -n1 -N8 -i -j -p -r -l -s -m

### Depth Options

    -n DEPTH   Set minimum depth (default = 1) and maximum depth (unless -N is given)
    -N DEPTH   Set maximum depth (default = 8)

### Input Options

    -i/-j   Read STDIN for the initial/target cube (default)
    -I/-J   Use the default cube as the initial/target input instead of reading STDIN

### Output Options

    -q/-Q   Enable/disable quiet mode to suppress printing progress in STDERR

### Turn Options

    -p/-P   Enable/disable primary (clockwise) quarter turns         | U F R L B D
    -r/-R   Enable/disable reverse (counter-clockwise) quarter turns | U' F' R' L' B' D'
    -l/-L   Enable/disable half (180 degrees) turns                  | U2 F2 R2 L2 B2 D2

### Slice Options

    -s/-S   Enable/disable single face turns                         | U F R L B D
    -m/-M   Enable/disable middle slice turns                        | M S E
    -d/-D   Enable/disable double-slice turns                        | u f r l b d
    -t/-T   Enable/disable cube rotations (triple-slice turns)       | x y z

## rubiks-enumerate

Enumerates all the combinations of steps that are used by `rubiks-search` algorithm.

### Usage

    $ rubiks-enumerate

Output:

    U
    U'
    U2
    F
    F'
    F2
    R
    R'
    R2
    L
    L'
    L2
    B
    B'
    B2
    D
    D'
    D2
    M
    M'
    M2
    S
    S'
    S2
    E
    E'
    E2

### Default Options

    $ rubiks-enumerate -n1 -N1 -p -r -l -s -m

### Depth Options

    -n DEPTH   Set minimum depth (default = 1) and maximum depth (unless -N is given)
    -N DEPTH   Set maximum depth (default = 1)

### Turn Options

    -p/-P   Enable/disable primary (clockwise) quarter turns         | U F R L B D
    -r/-R   Enable/disable reverse (counter-clockwise) quarter turns | U' F' R' L' B' D'
    -l/-L   Enable/disable half (180 degrees) turns                  | U2 F2 R2 L2 B2 D2

### Slice Options

    -s/-S   Enable/disable single face turns                         | U F R L B D
    -m/-M   Enable/disable middle slice turns                        | M S E
    -d/-D   Enable/disable double-slice turns                        | u f r l b d
    -t/-T   Enable/disable cube rotations (triple-slice turns)       | x y z

## rubiks-scramble

Scrambles a Rubik's cube given as STDIN with random rotations.

### Usage

    $ rubiks-scramble <<END

           W W W
           W W W
           W W W

    O O O  G G G  R R R  B B B
    O O O  G G G  R R R  B B B
    O O O  G G G  R R R  B B B

           Y Y Y
           Y Y Y
           Y Y Y

    END

Alternative form to start with a default Rubik's cube:

    $ rubiks-scramble -I

Output:

           Y O O
           B W Y
           Y Y G

    R O O  B O W  O B W  B G B
    R O Y  G G W  B R B  R B G
    R Y W  R W R  W O G  Y W G

           G G B
           R Y W
           Y R O

### Default Options

    $ rubiks-scramble -n20 -i -o -p -r -l -s -m

### Depth Options

    -n DEPTH   Set the number of turns (default = 20)

### Input Options

    -i   Read STDIN for the initial cube (default)
    -I   Use the default cube as the initial input instead of reading STDIN

### Output Options

    -o/-O   Print the scrambled cube (default)
    -u/-U   Print the rotation steps used to scramble the cube
    -v/-V   Print the reverse steps to solve the scrambled cube

### Turn Options

    -p/-P   Enable/disable primary (clockwise) quarter turns         | U F R L B D
    -r/-R   Enable/disable reverse (counter-clockwise) quarter turns | U' F' R' L' B' D'
    -l/-L   Enable/disable half (180 degrees) turns                  | U2 F2 R2 L2 B2 D2

### Slice Options

    -s/-S   Enable/disable single face turns                         | U F R L B D
    -m/-M   Enable/disable middle slice turns                        | M S E
    -d/-D   Enable/disable double-slice turns                        | u f r l b d
    -t/-T   Enable/disable cube rotations (triple-slice turns)       | x y z

## rubiks-apply

Applies a given Rubik's cube with a given list of rotation steps. A result cube is printed per input line.

### Usage

    $ rubiks-apply <<END

           W W W
           W W W
           W W W

    O O O  G G G  R R R  B B B
    O O O  G G G  R R R  B B B
    O O O  G G G  R R R  B B B

           Y Y Y
           Y Y Y
           Y Y Y

    F2 B2 R2 L2

    END

Alternative form to start with a default Rubik's cube:

    $ rubiks-apply -I <<END

    F2 B2 R2 L2

    END

Output:

           W Y W
           Y W Y
           W Y W

    R O R  B G B  O R O  G B G
    R O R  B G B  O R O  G B G
    R O R  B G B  O R O  G B G

           Y W Y
           W Y W
           Y W Y

### Default Options

    $ rubiks-apply -i

### Input Options

    -i   Read STDIN for the initial cube (default)
    -I   Use the default cube as the initial input instead of reading STDIN

## rubiks-reverse

Reverses a given list of rotation steps in such a way that the reverse steps can be used to revert the cube after
applying the steps.

### Usage

    $ rubiks-reverse <<END

    R  L' M2 U' F  S2

    END

Output:

    S2 F' U  M2 L  R'

## rubiks-mirror

Generates mirrored steps of given rotation steps. A mirror is based on a perspective view from the direction at the
corner of `U`, `F` and `R` where the left and right hand sides (`F` and `R`) are inverted.

### Usage

    $ rubiks-mirror <<END

    R  L' M2 U' F  S2

    END

Output:

    F' B  S2 U  R' M2

## Cube Notation

A Rubik's cube is represented by 54 characters in the order of the projected diagram depicted as below:

           W W W
           W W W
           W W W

    O O O  G G G  R R R  B B B
    O O O  G G G  R R R  B B B
    O O O  G G G  R R R  B B B

           Y Y Y
           Y Y Y
           Y Y Y

The above example intentionally uses color code, `W` for white, `G` for green, `R` for red, `O` for orange,
`B` for blue, and `Y` for yellow.
However, all the CLI commands are designed in a way that any arbitrary characters are accepted for any squares,
even without checking the physically possible configurations.

For example, some other character (`.` in the below) can represent yet unknown or variable square:

           W W W
           W W W
           W W W

    O O O  G G G  R R R  B B B
    . O .  . G .  . R .  . B .
    . . .  . . .  . . .  . . .

           . . .
           . . .
           . . .

Below is another example that represents unique squares to keep track of all the places distinctively:

           A B C
           D E F
           G H I

    a b c  J K L  S T U  j k l
    d e f  M N O  V W X  m n o
    g h i  P Q R  Y Z !  p q r

           s t u
           v w x
           y z ?

When a program (such as `rubiks-search`) reads a cube notation from STDIN, it simply picks up 54 characters,
excluding whitespaces.
Thus, the input can alternatively be as compact as below:

    WWWWWWWWW
    OOOGGGRRRBBB
    OOOGGGRRRBBB
    OOOGGGRRRBBB
    YYYYYYYYY

Note this is *not* the same order as listing the characters face by face.

    W W W W W W W W W
    O O O O O O O O O
    G G G G G G G G G
    R R R R R R R R R
    B B B B B B B B B
    Y Y Y Y Y Y Y Y Y
    # This does not work as intended.

The actual face orientations are interpreted as below:

              -------
             |       |
             |   U   |
             |  [0]  |
      ------- ------- ------- -------
     |       |       |       |       |
     |   L   |   F   |   R   |   B   |
     |  [3]  |  [1]  |  [2]  |  [4]  |
      ------- ------- ------- -------
             |       |
             |   D   |
             |  [5]  |
              -------

where `U` is for Up, `F` is for Front, `R` is for Right, `L` is for Left, `B` is for Back, and `D` is for Down.
The index subscripts indicate the order of the internal data structure.

Further broken down, each square in a face is indexed as below:

              -------
             | 0 1 2 |
             | 3 4 5 |
             | 6 7 8 |
      ------- ------- ------- -------
     | 0 1 2 | 0 1 2 | 0 1 2 | 0 1 2 |
     | 3 4 5 | 3 4 5 | 3 4 5 | 3 4 5 |
     | 6 7 8 | 6 7 8 | 6 7 8 | 6 7 8 |
      ------- ------- ------- -------
             | 0 1 2 |
             | 3 4 5 |
             | 6 7 8 |
              -------

## Move Notation

Single-face turns are represented by the faces that are rotated:

    U - Up
    F - Front
    R - Right
    L - Left
    B - Back
    D - Down

The direction of the turn is *clockwise* unless the notations are annotated:

    U  - Clockwise quarter turn
    U' - Counter-clockwise quarter turn
    U2 - Half turn

Middle-slice turns are represented by additional three characters:

    M - Middle   (the layer between L and R; turn direction as L)
    S - Standing (the layer between F and B; turn direction as F)
    E - Equator  (the layer between U and D; turn direction as D)

Double-slice turns are represented by lower case letters:

    u - Up    (U + E')
    f - Front (F + S)
    r - Right (R + M')
    l - Left  (L + M)
    b - Back  (B + S')
    d - Down  (D + E)

Triple-slice turns (cube rotations) are represented by x,y,z-axis characters:

    x - Rotate the entire cube on R
    y - Rotate the entire cube on U
    z - Rotate the entire cube on F

A sequence of move steps are represented by multiple turn symbols, separated by white-spaces:

    U F' M2 u y' L


text:
require 'active_support'
require 'active_support/core_ext/digest/uuid'

module Digest
  module UUID
    UUID_REGEX_FORMAT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.freeze

    # Takes a UUID string of varying formats and cleans it. It will strip invalid characters,
    # such as leading and trailing brackets as well as whitespace. The result is a lowercased,
    # canonical UUID string.
    #
    # If the +guid+ argument is nil or blank, then nil is returned. If the +guid+ is already
    # clean, then no additional cleaning occurs, and it is returned as-is.
    #
    # @param guid [String] A string that should more or less represent a UUID.
    # @return [String] A lowercase v4 UUID string stripped of any extraneous characters.
    #
    def self.clean(guid)
      return nil if guid.nil?
      g = guid.to_s.downcase
      return nil if g.strip.empty?
      return g if g.length == 36 && g =~ UUID_REGEX_FORMAT
      g.delete!('^0-9a-f')
      g.sub!(/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/, '\1-\2-\3-\4-\5')
    end
  end
end


text:
#pragma once

#include <SQLiteCpp/Exception.h>

namespace SQLite
{

// Forward declaration
class Database;

/**
 * @brief RAII encapsulation of a SQLite Transaction.
 *
 * A Transaction is a way to group multiple SQL statements into an atomic secured operation;
 * either it succeeds, with all the changes committed to the database file,
 * or if it fails, all the changes are rolled back to the initial state.
 *
 * Resource Acquisition Is Initialization (RAII) means that the Transaction
 * begins in the constructor and is rollbacked in the destructor, so that there is
 * no need to worry about memory management or the validity of the underlying SQLite Connection.
 *
 * This method also offers big performances improvements compared to individually executed statements.
 *
 * Thread-safety: a Transaction object shall not be shared by multiple threads, because :
 * 1) in the SQLite "Thread Safe" mode, "SQLite can be safely used by multiple threads
 *    provided that no single database connection is used simultaneously in two or more threads."
 * 2) the SQLite "Serialized" mode is not supported by SQLiteC++,
 *    because of the way it shares the underling SQLite precompiled statement
 *    in a custom shared pointer (See the inner class "Statement::Ptr").
 */
class Transaction
{
public:
    /**
     * @brief Begins the SQLite transaction
     *
     * @param[in] aDatabase the SQLite Database Connection
     *
     * Exception is thrown in case of error, then the Transaction is NOT initiated.
     */
    explicit Transaction(Database& aDatabase);

    /**
     * @brief Safely rollback the transaction if it has not been committed.
     */
    virtual ~Transaction();

    /**
     * @brief Commit the transaction.
     */
    void commit();

private:
    // Transaction must be non-copyable
    Transaction(const Transaction&);
    Transaction& operator=(const Transaction&);
    /// @}

private:
    Database&   mDatabase;  //!< Reference to the SQLite Database Connection
    bool        mbCommited; //!< True when commit has been called
};

}  // namespace SQLite


text:
import sys
from math import exp
import numpy as np
# README:
#
# This is an example python script for the external_Pk mode of Class.
# It generates the primordial spectrum of LambdaCDM.
# It can be edited and used directly, though keeping a copy of it is recommended.
#
# Two (maybe three) things need to be edited:
#
# 1. The name of the parameters needed for the calculation of Pk.
#    "sys.argv[1]" corresponds to "custom1" in Class, an so on
a=np.zeros(5)
try :
    a[0]           = float(sys.argv[1])
    a[1]           = float(sys.argv[2])
    a[2]           = float(sys.argv[3])
    a[3]           = float(sys.argv[4])
    a[4]           = float(sys.argv[5])

# Error control, no need to touch
except IndexError :
    raise IndexError("It seems you are calling this script with too few arguments.")
except ValueError :
    raise ValueError("It seems some of the arguments are not correctly formatted. "+
                     "Remember that they must be floating point numbers.")

A=2.41e-9
k_0=.05
n_s=.972
# 3. Limits for k and precision:
#    Check that the boundaries are correct for your case.
#    It is safer to set k_per_decade primordial slightly bigger than that of Class.

k_min  = 1.e-6
k_max  = 10.
k_per_decade_primordial = 200.

# 2. The function giving P(k), including the necessary import statements.
#    Insid
def P(k) :
    p=(k/k_0)**(n_s-1.)
    for i in range(5):
        p=p+a[i]*np.cos(np.log(k/k_0)*2*np.pi*(i+1)/7/np.log(10))
    return p*A

#
#
# And nothing should need to be edited from here on.
#

# Filling the array of k's
ks = [float(k_min)]
while ks[-1] <= float(k_max) :
    ks.append(ks[-1]*10.**(1./float(k_per_decade_primordial)))

# Filling the array of Pk's
for k in ks :
    P_k = P(k)
    print "%.18g %.18g" % (k, P_k)


text:
using System;

namespace EF7ConsoleApp
{
    public class Program
    {
        public static void Main()
        {
            using (var db = new BloggingContext())
            {
                db.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
                var count = db.SaveChanges();
                Console.WriteLine("{0} records saved to database", count);

                Console.WriteLine();
                Console.WriteLine("All blogs in database:");
                foreach (var blog in db.Blogs)
                {
                    Console.WriteLine(" - {0}", blog.Url);
                }
            }
        }
    }
}


text:
<?php

$autoloadFile = __DIR__ . '/../vendor/autoload.php';

if (!file_exists($autoloadFile)) {
    die("Autoloader is missing. " .
        "Did you forget to install the dependencies? " .
        "('composer install --dev')\n");
}

require_once $autoloadFile;


text:
import unittest

from cwr.parser.encoder.dictionary import IPIBaseDictionaryEncoder

"""
Acknowledgement to dictionary encoding tests.

The following cases are tested:
"""

__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__status__ = 'Development'

class TestIPIBaseEncoding(unittest.TestCase):
    def setUp(self):
        self._encoder = IPIBaseDictionaryEncoder()

    def test_encoded(self):
        encoded = self._encoder.encode('T-123456789-1')

        self.assertEqual('T-123456789-1', encoded)


text:
package com.fx.text.index;

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

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fx.text.pojo.IndexPojo;

public class BaseIndex {
	private static Logger log = LoggerFactory.getLogger(BaseIndex.class);

	protected static boolean add(IndexWriter iwriter, String id, String text) {
		try {
			if (id != null && !id.isEmpty() && text != null && !text.isEmpty()) {
				Document doc = new Document();
				doc.add(new Field("id", id, TextField.TYPE_STORED));
				doc.add(new Field("text", text, TextField.TYPE_STORED));

				iwriter.addDocument(doc);
				iwriter.commit();

				log.info("lucene add:" + id + "\t" + text);
				return true;
			}
		} catch (Exception e) {
			log.error(e.toString(), e);
			throw new RuntimeException("write lucene failed", e);
		}
		return false;
	}

	protected static boolean write(IndexWriter iwriter, String id, String text) {
		try {
			if (id != null && !id.isEmpty() && text != null && !text.isEmpty()) {
				Document doc = new Document();
				doc.add(new Field("id", id, TextField.TYPE_STORED));
				doc.add(new Field("text", text, TextField.TYPE_STORED));

				iwriter.updateDocument(new Term("id", id), doc);
				iwriter.commit();

				log.info("lucene write:" + id + "\t" + text);
				return true;
			}
		} catch (Exception e) {
			log.error(e.toString(), e);
			throw new RuntimeException("update lucene failed", e);
		}
		return false;
	}

	protected static boolean writeList(IndexWriter iwriter, List<IndexPojo> list) {
		try {
			if (list != null && !list.isEmpty()) {
				for (IndexPojo t : list) {
					Document doc = new Document();
					doc.add(new Field("id", t.getId(), TextField.TYPE_STORED));
					doc.add(new Field("text", t.getText(), TextField.TYPE_STORED));

					iwriter.updateDocument(new Term("id", t.getId()), doc);
					log.info("lucene write:" + t.getId() + "\t" + t.getText());
				}
				iwriter.commit();

				return true;
			}
		} catch (Exception e) {
			log.error(e.toString(), e);
			throw new RuntimeException("update lucene failed", e);
		}
		return false;
	}

	protected static boolean delete(IndexWriter iwriter, String id) {
		try {
			if (id != null && !id.isEmpty()) {
				iwriter.deleteDocuments(new Term("id", id));
				iwriter.commit();

				log.info("lucene delete:" + id);
				return true;
			}
		} catch (Exception e) {
			log.error(e.toString(), e);
			throw new RuntimeException("delete lucene failed", e);
		}
		return false;
	}

	protected static List<String> query(DirectoryReader ireader, Analyzer analyzer, String text, int max) {
		try {
			if (text != null && !text.isEmpty() && ireader != null && analyzer != null) {
				IndexSearcher isearcher = new IndexSearcher(ireader);
				// Parse a simple query that searches for "text":
				QueryParser parser = new QueryParser("text", analyzer);
				Query query = parser.parse(text);
				ScoreDoc[] hits = isearcher.search(query, max).scoreDocs;

				// Iterate through the results:
				List<String> list = new ArrayList<String>();
				if (hits != null && hits.length > 0) {
					for (ScoreDoc hit : hits) {
						Document hitDoc = isearcher.doc(hit.doc);
						if (hitDoc != null) {
							log.info("lucene find '" + text + "' in id:" + hitDoc.get("id") + "\t" + hit.score);
							list.add(hitDoc.get("id"));
						}
					}
				}
				return list;
			}
		} catch (Exception e) {
			log.error(e.toString(), e);
			throw new RuntimeException("query lucene failed", e);
		}
		return null;
	}

}


text:
/**
 * AngularUI - The companion suite for AngularJS
 * @version v0.3.2 - 2013-01-30
 * @link http://angular-ui.github.com
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */

angular.module('ui.config', []).value('ui.config', {});
angular.module('ui.filters', ['ui.config']);
angular.module('ui.directives', ['ui.config']);
angular.module('ui', ['ui.filters', 'ui.directives', 'ui.config']);

/**
 * General-purpose validator for ngModel.
 * angular.js comes with several built-in validation mechanism for input fields (ngRequired, ngPattern etc.) but using
 * an arbitrary validation function requires creation of a custom formatters and / or parsers.
 * The ui-validate directive makes it easy to use any function(s) defined in scope as a validator function(s).
 * A validator function will trigger validation on both model and input changes.
 *
 * @example <input ui-validate=" 'myValidatorFunction($value)' ">
 * @example <input ui-validate="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }">
 * @example <input ui-validate="{ foo : '$value > anotherModel' }" ui-validate-watch=" 'anotherModel' ">
 * @example <input ui-validate="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }" ui-validate-watch=" { foo : 'anotherModel' } ">
 *
 * @param ui-validate {string|object literal} If strings is passed it should be a scope's function to be used as a validator.
 * If an object literal is passed a key denotes a validation error key while a value should be a validator function.
 * In both cases validator function should take a value to validate as its argument and should return true/false indicating a validation result.
 */
angular.module('ui.directives').directive('uiValidate', function () {

  return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, elm, attrs, ctrl) {
      var validateFn, watch, validators = {},
        validateExpr = scope.$eval(attrs.uiValidate);

      if (!validateExpr) return;

      if (angular.isString(validateExpr)) {
        validateExpr = { validator: validateExpr };
      }

      angular.forEach(validateExpr, function (expression, key) {
        validateFn = function (valueToValidate) {
          if (scope.$eval(expression, { '$value' : valueToValidate })) {
            ctrl.$setValidity(key, true);
            return valueToValidate;
          } else {
            ctrl.$setValidity(key, false);
            return undefined;
          }
        };
        validators[key] = validateFn;
        ctrl.$formatters.push(validateFn);
        ctrl.$parsers.push(validateFn);
      });

      // Support for ui-validate-watch
      if (attrs.uiValidateWatch) {
        watch = scope.$eval(attrs.uiValidateWatch);
        if (angular.isString(watch)) {
          scope.$watch(watch, function(){
            angular.forEach(validators, function(validatorFn, key){
              validatorFn(ctrl.$modelValue);
            });
          });
        } else {
          angular.forEach(watch, function(expression, key){
            scope.$watch(expression, function(){
              validators[key](ctrl.$modelValue);
            });
          });
        }
      }
    }
  };
});


text:
package com.bombardier.plugin.utils;

import hudson.EnvVars;
import hudson.model.AbstractBuild;
import hudson.model.Executor;
import hudson.model.FreeStyleProject;
import hudson.model.Label;
import hudson.model.Node;
import hudson.model.Project;
import hudson.slaves.EnvironmentVariablesNodeProperty;

import java.io.IOException;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.Set;

import com.bombardier.plugin.DTBuild;
import com.bombardier.plugin.DTJob;
import com.bombardier.plugin.misc.GenericEntry;
import com.bombardier.plugin.misc.PrintMessages;

import jenkins.model.Jenkins;
import jenkins.model.Jenkins.MasterComputer;

/**
 * A set of utilities used to perform actions on/with {@link Node}s
 *
 * @author Samuil Dragnev
 * @since 1.0
 */
public class NodeUtils {
	/**
	 * Returns the environment variables for the given {@link Node}.
	 *
	 * @param node
	 *            The {@link Node} to get the environment variables from
	 * @param additionalEnvironment
	 *            environment added to the environment from the {@link Node}.
	 *            Take precedence over environment from the {@link Node}.
	 * @return the environment variables for the given {@link Node}
	 * @since 1.0
	 */
	public static EnvVars getEnvironment(Node node,
			EnvVars additionalEnvironment) {
		EnvVars envVars = new EnvVars();
		EnvironmentVariablesNodeProperty env = node.getNodeProperties().get(
				EnvironmentVariablesNodeProperty.class);
		if (env != null) {
			envVars.putAll(env.getEnvVars());
		}
		envVars.overrideAll(additionalEnvironment);
		return envVars;
	}

	/**
	 * Used to get all available {@link Nodes}s in the {@link Label} that are
	 * not the Master node.
	 *
	 * @param build
	 *            the current build
	 * @param set
	 *            the {@link Label} assigned to the {@link DTJob}.
	 * @return a {@link Set} of all available nodes
	 * @throws Exception
	 * @since 1.0
	 */
	public static Set<Node> getAllAvailableNodes(AbstractBuild<?, ?> build)
			throws Exception {
		Set<Node> nodes = new HashSet<Node>();
		checkNodes(build);
		for (Node node : getAssignedNodes(build)) {
			if (node.toComputer().isOnline()) {
				if (node.equals(build.getBuiltOn())) {
					nodes.add(node);
				} else {
					if (node.toComputer().isIdle()) {
						nodes.add(node);
					}
				}
			}
		}

		if (nodes.size() < 2) {
			throw PrintMessages.throwNotEnoughSlaves(nodes.size());
		}
		return nodes;
	}

	/**
	 * Used define additional environment variable for a particular {@link Node}
	 * .
	 *
	 * @param node
	 *            the {@link Node}
	 * @param build
	 *            the current build
	 * @return a new Entry of a node and it's additional environment variables
	 * @throws IOException
	 * @throws Exception
	 * @since 1.0
	 */
	public static GenericEntry<Node, EnvVars> createEnvVarsForNode(Node node,
			AbstractBuild<?, ?> build, String listFile) throws IOException,
			Exception {
		if (node != null) {
			String nodeTestEnv = ((DTBuild) build).getTestJob()
					.getSlaveTestEnv();
			String projectName = ((DTBuild) build).getTestJob()
					.getDisplayName();
			EnvVars additionalEnvironment = new EnvVars();
			additionalEnvironment.put("$TEST_ENV", nodeTestEnv + "/");
			additionalEnvironment.put("$TEST_LIST", projectName + "/"
					+ listFile);
			additionalEnvironment.put("$TARGET_SCRIPT", projectName + "/"
					+ FilePathUtils.getPathToTargetScript(build).getName());
			additionalEnvironment.put("$TEST_WS", FilePathUtils
					.getPathToRootProjectWorkspaceOnNode(node, build)
					.getRemote()
					+ "/");
			return new GenericEntry<Node, EnvVars>(node, additionalEnvironment);
		} else {
			return null;
		}
	}

	/**
	 * Used to delete all Project used to lock the Slave {@link Node}s
	 * executors.
	 *
	 * @param nodes
	 *            the set of Nodes
	 * @param build
	 *            the current build
	 * @throws IOException
	 * @throws InterruptedException
	 * @since 1.0
	 */
	public static void deleteLockingProjects(final Set<Node> nodes,
			final AbstractBuild<?, ?> build, PrintStream stream)
			throws IOException, InterruptedException {
		for (Node node : nodes) {
			for (Executor e : node.toComputer().getExecutors()) {
				String lockProjectName = NodeUtils.getLockedProjectName(build
						.getProject().getName(), node, e);
				deleteLockingProject(lockProjectName, stream);
			}
		}
	}

	/**
	 * Used to delete the auto generated projects used to lock the used
	 * {@link Node}s.
	 *
	 * @param lockProjectName
	 *            the locked project name
	 * @throws IOException
	 * @throws InterruptedException
	 * @since 1.0
	 */
	public static void deleteLockingProject(String lockProjectName,
			PrintStream stream) throws IOException, InterruptedException {
		for (@SuppressWarnings("rawtypes")
		Project p : Jenkins.getInstance().getAllItems(FreeStyleProject.class)) {
			if (lockProjectName.equalsIgnoreCase(p.getName())) {
				while (p.isBuilding()) {
					Thread.sleep(1000);
				}
				p.delete();
				stream.println("Project - " + p.getName()
						+ " has been deleted!");
			}
		}
	}

	/**
	 * Used to generate the name for the Project used to lock a {@link Node}'s
	 * executor.
	 *
	 * @param mainProjectName
	 *            the main Project's name
	 * @param node
	 *            the node
	 * @param exec
	 *            the node's executor
	 * @return the name of the Locking Project
	 */
	public static String getLockedProjectName(String mainProjectName,
			Node node, Executor exec) {
		return mainProjectName + "-Locking-" + node.getDisplayName()
				+ exec.getDisplayName();
	}

	/**
	 * Used to get the assigned node for this project used in the build process,
	 * specified by their {@link Label}
	 *
	 * @param build
	 *            the current build
	 * @return the set of {@link Node}s
	 * @since 1.0
	 */
	private static Set<Node> getAssignedNodes(AbstractBuild<?, ?> build) {
		return ((DTBuild) build).getTestJob().getAssignedLabel().getNodes();
	}

	/**
	 * Used to validate the configurations in regards to the specified
	 * {@link Label} and the {@link Node}s associated with it.
	 *
	 * @param build
	 *            the current build
	 * @throws Exception
	 * @since 1.0
	 */
	private static void checkNodes(AbstractBuild<?, ?> build) throws Exception {
		Label label = ((DTBuild) build).getTestJob().getAssignedLabel();

		// Check if the Nodes label is set
		if (label == null) {
			throw PrintMessages.throwLabelIsNotSet();
		}

		// Check if the Job is being build on the Master
		if (build.getBuiltOn().toComputer() instanceof MasterComputer) {
			throw PrintMessages.throwCannotBuildOnMaster();
		}
	}
}


text:
\hypertarget{dir_efa92380cced29a084ea12f32f1d1e93}{}\section{src/test/java/com/ahmet Directory Reference}
\label{dir_efa92380cced29a084ea12f32f1d1e93}\index{src/test/java/com/ahmet Directory Reference@{src/test/java/com/ahmet Directory Reference}}
\subsection*{Files}
\begin{DoxyCompactItemize}
\end{DoxyCompactItemize}


text:
const suman = require('suman');  //using npm link

var Test = suman.init(module, {
    interface: 'TDD'
});

//

console.log('developer debugging output');

function promiseTimeout(val) {
    return new Promise(function (resolve) {
        setTimeout(resolve.bind(null, val * 3), 100);
    });
}

Test.suite('@Test1-EMpty', {parallel: false, bail: true}, function (assert, william) {

    console.log('william:', william);

    this.test('passes right away', function *() {
        // var val = yield promiseTimeout(yield promiseTimeout(4));
        // console.log('val:',val);
        assert.equal(36, yield promiseTimeout(yield promiseTimeout(4)));
    });

    this.test('fails right away', function () {
        throw new Error('chuck');
    });

    this.test('should never run if bail is set to true', function () {
        assert(true);
    });
});


text:
<?php

namespace Sinergi\Emails\Tests;

use PHPUnit_Framework_TestCase;

class ExampleTest extends PHPUnit_Framework_TestCase
{
    public function testTrue()
    {
        $this->assertTrue(true);
    }
}


text:
var nodemailer = require('nodemailer');
var smtpPool = require('nodemailer-smtp-pool');
var postfixQueue = require('./postfixQueue');

function build() {
    var transporter = nodemailer.createTransport(smtpPool({
        host: global.config.email.smtp.host,
        port: global.config.email.smtp.port,
        secure: global.config.email.smtp.ssl,
        auth: {
            user: global.config.email.address,
            pass: global.config.email.password
        },
        // use up to 5 parallel connections
        maxConnections: 5,
        // do not send more than 10 messages per connection
        maxMessages: 10,
        // no not send more than 5 messages in a second
        rateLimit: 5
    }));
    return transporter;
}

exports.client = build();
exports.build = build;

exports.send = function (email, callback) {
    postfixQueue.push(email, function (err, result) {
        if (err) {
            console.log(err);
            callback(err);
        } else {
            callback(null, result);
        }
    });
};

function setSendStatus(emailId, status) {
    global.db.models.email.update({
        sendStatus: status
    }, {
        where: {
            emailId: emailId
        }
    });
}

setInterval(function () {
    postfixQueue.pop(function (err, result) {
        if (err) {
            console.log(err);
        } else if (result) {
            if (result.status) {
                var emailId = result.content.emailId;
                var emailTTL = result.content.TTL;
                delete result.content.emailId;
                delete result.content.TTL;
                exports.client.sendMail(result.content, function (err, info) {
                    if (err) {
                        result.content.emailId = emailId;
                        result.content.emailTTL = emailTTL;
                        postfixQueue.push(result, function (err, result) {
                            if (err) {
                                console.log(err);
                                setSendStatus(emailId, '失败');
                            }
                        });
                    } else {
                        setSendStatus(emailId, '成功');
                    }
                });
            } else {
                setSendStatus(result.content.emailId, '失败');
            }
        }
    });
}, 3000);