text:
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="minimal-ui, width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="icon" href="./favicon.ico" />
    <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Josefin+Sans:100,200,300,400,500,600,700,800,900">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>Sam G</title>
</head>

<body id="body">
    <div id="app" />
    <script src="src/public/bundle.js" type="text/javascript"></script>
    <script>
        (function(i, s, o, g, r, a, m) {
            i['GoogleAnalyticsObject'] = r;
            i[r] = i[r] || function() {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date();
            a = s.createElement(o),
                m = s.getElementsByTagName(o)[0];
            a.async = 1;
            a.src = g;
            m.parentNode.insertBefore(a, m)
        })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
        ga('create', 'UA-98208747-1', 'auto');
        ga('send', 'pageview');

    </script>
</body>

</html>


text:
<?php

namespace Liip\Registry\Adaptor\Decorator;

use Liip\Registry\Adaptor\Tests\RegistryTestCase;

class NormalizeDecoratorTest extends RegistryTestCase
{

    /**
     * @dataProvider normalizeValueDataprovider
     * @covers \Liip\Registry\Adaptor\Decorator\NormalizeDecorator::normalizeValue
     */
    public function testNormalizeValue($expected, $value)
    {
        $decorator = new NormalizeDecorator();

        $valueArray = $decorator->normalizeValue($value);

        $this->assertInternalType('array', $valueArray);
        $this->assertEquals($expected, $valueArray);
    }
    public static function normalizeValueDataprovider()
    {
        return array(
            'empty value' => array(array(), array()),
            'number value' => array(array('integer' => '1'), 1),
            'float value'  => array(array('double' => '1.1'), 1.1),
            'string value' => array(array('string' => '"blob"'), 'blob'),
            'array value' => array(array('array' => '{"tux":"gnu"}'), array('tux' => 'gnu')),
            'object value' => array(array('object' => '{"tux":"gnu"}'), (object) array('tux' => 'gnu')),
            'class instance value' => array(array('object' => '{"tux":"gnu"}'), new \ArrayObject(array('tux' => 'gnu'))),
        );
    }

    /**
     * @dataProvider denormalizeArrayDataprovider
     * @covers \Liip\Registry\Adaptor\Decorator\NormalizeDecorator::denormalizeValue
     */
    public function testDenormalizeArray($expected, $array)
    {
        $decorator = new NormalizeDecorator();

        $value = $decorator->denormalizeValue($array);

        $this->assertEquals($expected, $value);
    }
    public static function denormalizeArrayDataprovider()
    {
        return array(
            'normalized object array' => array(array((object) array('tux' => 'gnu')), array(array('object' => '{"tux":"gnu"}'))),
            'normalized number array' => array(array(1), array(array('integer' => 1))),
            'normalized float array'  => array(array(1.1), array(array('double'  => 1.1))),
            'normalized string array' => array(array('blob'), array(array('string' => '"blob"'))),
            'usual data' => array(array(array('tux' => 'mascott')), array(array('array' => '{"tux":"mascott"}'))),
            'no normalize data' => array(array((object)array('tux' => 'mascott')), array(array('{"tux":"mascott"}'))),
        );
    }

    /**
     * @covers \Liip\Registry\Adaptor\Decorator\NormalizeDecorator::denormalizeValue
     */
    public function testDenormalizeValueExpectingexception()
    {
        $decorator = new NormalizeDecorator();

        $this->setExpectedException('\Assert\InvalidArgumentException');
        $value = $decorator->denormalizeValue(array(array('{"tux":mascott}')));
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.benstatertots.brewerydb.beer.list.model;

import com.benstatertots.brewerydb.api.model.Category;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Style {

    @SerializedName("id")
    @Expose
    public long id;

    @SerializedName("name")
    @Expose
    public String name;

    @SerializedName("category")
    @Expose
    public Category category;

    @SerializedName("srmMax")
    @Expose
    public String srmMax;

    @SerializedName("ibuMax")
    @Expose
    public String ibuMax;

    @SerializedName("srmMin")
    @Expose
    public String srmMin;

    @SerializedName("description")
    @Expose
    public String description;

    @SerializedName("fgMin")
    @Expose
    public String fgMin;

    @SerializedName("ibuMin")
    @Expose
    public String ibuMin;

    @SerializedName("createDate")
    @Expose
    public String createDate;

    @SerializedName("fgMax")
    @Expose
    public String fgMax;

    @SerializedName("abvMax")
    @Expose
    public String abvMax;

    @SerializedName("ogMin")
    @Expose
    public String ogMin;

    @SerializedName("abvMin")
    @Expose
    public String abvMin;

    @SerializedName("categoryId")
    @Expose
    public long categoryId;

}


text:
/*
 * Copyright (C) 2020 ScyllaDB
 */
#pragma once

#if defined(__cpp_concepts) && __cpp_concepts >= 201907 && \
    defined(__cpp_lib_concepts) && __cpp_lib_concepts >= 201907

#define SEASTAR_CONCEPT(x...) x
#define SEASTAR_NO_CONCEPT(x...)

#else

#define SEASTAR_CONCEPT(x...)
#define SEASTAR_NO_CONCEPT(x...) x

#endif


text:
**The Scala API for Quantities, Units of Measure and Dimensional Analysis**

Squants is a framework of data types and a domain specific language (DSL) for representing Quantities,
their Units of Measure, and their Dimensional relationships.
The API supports typesafe dimensional analysis, improved domain models and more.
All types are immutable and thread-safe.

[Website](http:/www.squants.com/)
|
[GitHub](https://github.com/garyKeorkunian/squants)
|
[User Forum](https://groups.google.com/forum/#!forum/squants)
|
[Wiki](https://github.com/garyKeorkunian/squants/wiki)

### Current Versions
Current Release: **0.5.3**
([API Docs](https://oss.sonatype.org/service/local/repositories/releases/archive/com/squants/squants_2.11/0.5.3/squants_2.11-0.5.3-javadoc.jar/!/index.html#squants.package))

Development Build: **0.6.0-SNAPSHOT**
([API Docs](https://oss.sonatype.org/service/local/repositories/snapshots/archive/com/squants/squants_2.11/0.6.0-SNAPSHOT/squants_2.11-0.6.0-SNAPSHOT-javadoc.jar/!/index.html#squants.package))

[Release History](https://github.com/garyKeorkunian/squants/wiki/Release-History)

[![Build Status](https://travis-ci.org/garyKeorkunian/squants.png?branch=master)](https://travis-ci.org/garyKeorkunian/squants)

## Installation
Repository hosting for Squants is provided by Sonatype.
To use Squants in your SBT project add the following dependency to your build.

    "com.squants"  %% "squants"  % "0.5.3"
or

    "com.squants"  %% "squants"  % "0.6.0-SNAPSHOT"

To use Squants in your Maven project add the following dependency

```xml
<dependency>
    <groupId>com.squants</groupId>
    <artifactId>squants_2.11</artifactId>
    <version>0.5.3</version>
</dependency>
```

Beginning with Squants 0.4.x series, both Scala 2.10 and 2.11 builds are available.

To use Squants interactively in the Scala REPL, clone the git repo and run `sbt console`

    git clone https://github.com/garyKeorkunian/squants
    cd squants
    sbt console

## Better Dimensional Analysis
*The Trouble with Doubles*

When building programs that perform dimensional analysis, developers are quick to declare
quantities using a basic numeric type, usually Double.  While this may be satisfactory in some situations,
it can often lead to semantic and other logic issues.

For example, when using a Double to describe quantities of Energy (kWh) and Power (kW), it is possible
to compile a program that adds these two values together.  This is not appropriate as kW and kWh
measure quantities of two different dimensions.  The unit kWh is used to measure an amount of Energy used
or produced.  The unit kW is used to measure Power/Load, the rate at which Energy is being used
or produced, that is, Power is the first time derivative of Energy.

*Power = Energy / Time*

Consider the following code

```scala
val loadKw: Double = 1.2
val energyMwh: Double = 24.2
val sumKw = loadKw + energyMwh
```

which not only adds quantities of different dimensions (Power vs Energy),
it also fails to convert the scales implied in the val names (Mega vs Kilo).
Because this code compiles, detection of these errors is pushed further into the development cycle.

### Dimensional Type Safety

_Only quantities with the same dimensions may be compared, equated, added, or subtracted._

Squants helps prevent errors like these by type checking operations at compile time and
automatically applying scale and type conversions at run-time.  For example,

```scala
val load1: Power = Kilowatts(12)
val load2: Power = Megawatts(0.023)
val sum = load1 + load2
sum should be(Kilowatts(35))
sum should be(Megawatts(0.035))
```

is a valid assertion because Kilowatts and Megawatts are both units of Power.  Only the scale is
different and the library applies an appropriate conversion.  Also, notice that keeping track of
the scale within the value name is no longer needed.

```scala
val load: Power = Kilowatts(1.2)
val energy: Energy = KilowattHours(23.0)
val sum = load + energy // Invalid operation - does not compile
```
The unsupported operation in this expression prevents the code from compiling,
catching the error made when using Double in the example above.

### Dimensionally Correct Type Conversions

_One may take quantities with different dimensions, and multiply or divide them._

Dimensionally correct type conversions are a key feature of Squants.
Conversions are implemented by defining relationships between Quantity types using the * and / operators.

The following code demonstrates creating ratio between two quantities of the same dimension:

```scala
val ratio: Double = Days(1) / Hours(3)
ratio should be(8.0)
```

This code demonstrates use of Power's `*` method that takes a Time and returns an Energy:

```scala
val load: Power = Kilowatts(1.2)
val time: Time = Hours(2)
val energyUsed: Energy = load * time
energyUsed should be(KilowattHours(2.4))
```

This code demonstrates use of Energy's `/` method that takes a Time and returns a Power:

```scala
val aveLoad: Power = energyUsed / time
aveLoad should be(Kilowatts(1.2)
```

### Unit Conversions

Quantity values are based in the units used to create them.

```scala
val loadA: Power = Kilowatts(1200)  // returns Power: 1200.0 kW
val loadB: Power = Megawatts(1200)  // returns Power: 1200.0 MW
```

Since Squants properly equates values of a similar dimension, regardless of the unit,
there is typically no reason to explicitly convert from one to the other.
This is especially true if the user code is primarily performing dimensional analysis.

However, there are times when you may need to set a Quantity value to a specific unit (eg, for proper JSON encoding).

When necessary, a quantity can be converted to another unit using the `in` method.

```scala
val loadA = Kilowatts(1200)    // returns Power: 1200.0 kW
val loadB = loadA in Megawatts // returns Power: 1.2 MW
val loadC = loadA in Gigawatts // returns Power: 0.0012 GW
```

Sometimes you need to get the numeric portion of the quantity
(eg, for submission to an external service that requires a numeric in a specific unit or to perform analysis
beyond Squant's existing capabilities)

When necessary, the value can be extracted in the desired unit with the `to` method.

```scala
val load: Power = Kilowatts(1200)
val kw: Double = load to Kilowatts // returns 1200.0
val mw: Double = load to Megawatts // returns 1.2
val gw: Double = load to Gigawatts // returns 0.0012
```

Most types include methods with convenient aliases for the `to` methods.

```
val kw: Double = load toKilowatts // returns 1200.0
val mw: Double = load toMegawatts // returns 1.20
val gw: Double = load toGigawatts // returns 0.0012
```

NOTE - It is important to use the `to` method for extracting the numeric value,
as this ensures you will be getting the numeric value for the desired unit.
`Quantity.value` should not accessed directly.
To prevent improper usage, direct access to the `Quantity.value` field may be deprecated in a future version.

Creating strings formatted in the desired unit:

```scala
val kw: String = load toString Kilowatts // returns "1200.0 kW"
val mw: String = load toString Megawatts // returns "1.2 MW"
val gw: String = load toString Gigawatts // returns "0.0012 GW"
```

Creating Tuple2(Double, String) that includes a numeric value and unit symbol:

```scala
val load: Power = Kilowatts(1200)
val kw: Tuple2 = load toTuple               // returns (1200, "kW")
val mw: Tuple2 = load toTuple Megawatts     // returns (1.2, "MW)
val gw: Tuple2 = load toTuple Gigawatts     // returns (0.0012, "GW")
```

This can be useful for passing properly scaled quantities using to other processes
that do not use Squants, but need to know the value and unit using primitive types (Double, String)

Simple console based conversions (using DSL described below)

```scala
1.kilograms to Pounds       // returns 2.2046226218487757
2.1.pounds to Kilograms     // returns 0.952543977
100.C to Fahrenheit         // returns 212.0
```

### Approximations
Create an implicit Quantity value to be used as a tolerance in approximate equality comparisons.
Use the `approx` method (`=~`, `~=`, `≈` operator) like the `equals` method (`==` operator)

```scala
implicit val tolerance = Watts(.1)
val load = Kilowatts(2.0)
val reading = Kilowatts(1.9999)

 // uses implicit tolerance
load =~ reading should be(true)
load ≈ reading should be(true)
load approx reading should be(true)
```

The `=~` and `≈` are the preferred operators as they have the correct precedence for equality operations.
The `~=` is provided for those who wish to use a more natural looking approx operator using standard characters.
However, because of its lower precedence, user code may require parenthesis around these comparisons

### Vectors

All Quantity types in Squants represent the scalar value of a quantity.
That is, there is no direction information encoded in any of the Quantity types.
This is true even for Quantities which are normally vector quantities (ie. Velocity, Acceleration, etc).

Vector quantities in Squants are implemented as a case class that takes a variable parameter list of like quantities
representing a set of point coordinates in Cartesian space.
The dimensionality of the vector is determined by the number of arguments.
Most basic vector operations are currently supported (addition, subtraction, scaling, cross and dot products)

```scala
val vector = QuantityVector(Kilometers(1.2), Kilometers(4.3), Kilometers(2.3)
val magnitude: Length = vector.magnitude        // returns the scalar value of the vector
val normalized = vector.normalize(Kilometers)   // returns a corresponding vector scaled to 1 of the given unit

val vector2 = QuantityVector(Kilometers(1.2), Kilometers(4.3), Kilometers(2.3)
val vectorSum = vector + vector2        // returns the sum of two vectors
val vectorDiff = vector - vector2       // return the difference of two vectors
val vectorScaled = vector * 5           // returns vector scaled 5 times
val vectorReduced = vector / 5          // returns vector reduced 5 time
val vectorDouble = vector / 5.meters    // returns vector reduced and converted to DoubleVector
val dotProduct = vector * vectorDouble  // returns the Dot Product of vector and vectorDouble

val crossProduct = vector crossProduct vectorDouble  // currently only supported for 3-dimensional vectors
```

#### Dimensional conversions within Vector operations.
This feature is currently under development and the final implementation being evaluated.
The following type of operation is the goal.

```scala
val vectorLength = QuantityVector(Kilometers(1.2), Kilometers(4.3), Kilometers(2.3)
val vectorArea: QuantityVector[Area] = vectorLength * Kilometers(10)
val vectorVelocity: QuantityVector[Velocity] = vectorLength / Seconds(1)
```

Simple non-quantity (Double based) vectors are also supported

```scala
val vector = DoubleVector(1.2, 4.3, 2.3, 5.4)   // a Four-dimensional vector
```

## Market Package
Market Types are similar but not quite the same as other quantities in the library.
The primary type, Money, is derived from Quantity, and its Units of Measure are Currencies.
However, because the conversion multipliers between currency units can not be predefined,
many of the behaviors have been overridden and augmented to realize correct behavior.

### Money
A Quantity of purchasing power measured in units called Currencies.
Like other quantities, the Unit of Measures are used to create Money values.

```scala
val tenBucks: Money = USD(10)
val someYen: Money = JPY(1200)
val goldStash: Money = XAU(50)
val digitalStash: Money = BTC(50)
```

### Price
A Ratio between Money and another Quantity.
A Price value is typed on a Quantity and can be denominated in any defined Currency.

*Price = Money / Quantity*

```scala
val threeForADollar: Price[Dimensionless] = USD(1) / Each(3)
val energyPrice: Price[Energy] = USD(102.20) / MegawattHours(1)
val milkPrice: Price[Volume] = USD(4) / UsGallons(1)

val costForABunch: Money = threeForADollar * Dozen(10) // returns USD(40)
val energyCost: Money = energyPrice * MegawattHours(4) // returns USD(408.80)
val milkQuota: Volume = milkPrice * USD(20) // returns UsGallons(5)
```

### FX Support
Currency Exchange Rates are used to define the conversion factors between currencies

```scala
// create an exchange rate
val rate = CurrencyExchangeRate(USD(1), JPY(100))
// OR
val rate = USD / JPY(100)
// OR
val rate = JPY(100) -> USD(1)
// OR
val rate = JPY(100) toThe USD(1)

val someYen: Money = JPY(350)
val someBucks: Money = USD(23.50)

// Use the convert method which automatically converts the money to the 'other' currency
val dollarAmount: Money = rate.convert(someYen) // returns USD(3.5)
val yenAmount: Money = rate.convert(someBucks)  // returns JPY(2350)

// or just use the * operator in either direction (money * rate, or rate * money)
val dollarAmount2: Money = rate * someYen       // returns USD(3.5)
val yenAmount2: Money = someBucks * rate		// returns JPY(2350)
```

### Money Context
A MoneyContext can be implicitly declared to define default settings and applicable exchange rates within its scope.
This allows your application to work with a default currency based on an application configuration or other dynamic source.
It also provides support for updating exchange rates and using those rates for automatic conversions between currencies.
The technique and frequency chosen for exchange rate updates is completely in control of the application.

```scala
val exchangeRates = List(USD / CAD(1.05), USD / MXN(12.50), USD / JPY(100))
implicit val moneyContext = defaultMoneyContext withExchangeRates exchangeRates

val someMoney = Money(350) // 350 in the default Cur
val usdMoney: Money = someMoney in USD
val usdBigDecimal: BigDecimal = someMoney to USD
val yenCost: Money = (energyPrice * MegawattHours(5)) in JPY
val northAmericanSales: Money = (CAD(275) + USD(350) + MXN(290)) in USD
```

## Quantity Ranges
Used to represent a range of Quantity values between an upper and lower bound

```scala
val load1: Power = Kilowatts(1000)
val load2: Power = Kilowatts(5000)
val range: QuantityRange[Power] = QuantityRange(load1, load2)
```
Use multiplication and division to create a Seq of ranges from the original

```scala
// Create a Seq of 10 sequential ranges starting with the original and each the same size as the original
val rs1 = range * 10
// Create a Seq of 10 sequential ranges each 1/10th of the original size
val rs2 = range / 10
// Create a Seq of 10 sequential ranges each with a size of 400 kilowatts
val rs3 = range / Kilowatts(400)
```
Apply foreach, map and foldLeft/foldRight directly to QuantityRanges with a divisor

```scala
// foreach over each of the 400 kilometer ranges within the range
range.foreach(Kilometers(400)) {r => ???}
// map over each of 10 even parts of the range
range.map(10) {r => ???}
// fold over each 10 even parts of the range
range.foldLeft(10)(0) {(z, r) => ???}
```

NOTE - Because these implementations of foreach, map and fold* take a parameter (the divisor), these methods
are not compatible with Scala's for comprehensions.

## Natural Language DSL
Implicit conversions give the DSL some features that allows user code to express quantities in a
more naturally expressive and readable way.

Create Quantities using Unit Of Measure Factory objects (no implicits required)

```scala
val load = Kilowatts(100)
val time = Hours(3.75)
val money = USD(112.50)
val price = Price(money, MegawattHours(1))
```

Create Quantities using Unit of Measure names and/or symbols (uses implicits)

```scala
val load1 = 100 kW 			        // Simple expressions don't need dots
val load2 = 100 megaWatts
val time = 3.hours + 45.minutes     // Compound expressions may need dots
```

Create Quantities using operations between other Quantities

```scala
val energyUsed = 100.kilowatts * (3.hours + 45.minutes)
val price = 112.50.USD / 1.megawattHours
val speed = 55.miles / 1.hours
```

Create Quantities using formatted Strings

```scala
val load = Power("40 MW")		// 40 MW
```

Create Quantities using Tuples

```scala
val load = Power((40, "MW"))    // 40 MW
```

Use single unit values to simplify expressions

```scala
// Hours(1) == 1.hours == hour
val ramp = 100.kilowatts / hour
val speed = 100.kilometers / hour

// MegawattHours(1) == 1.megawattHours == megawattHour == MWh
val hi = 100.dollars / MWh
val low = 40.dollars / megawattHour
```

Implicit conversion support for using Double on the left side of operations

```scala
val price = 10 / dollar	    // 1 USD / 10 ea
val freq = 60 / second	    // 60 Hz
val load = 10 * 4.MW		// 40 MW
```

Create Quantity Ranges using `to` or `plusOrMinus` (`+-`) operators

```scala
val range1 = 1000.kW to 5000.kW	             // 1000.kW to 5000.kW
val range2 = 5000.kW plusOrMinus 1000.kW     // 4000.kW to 6000.kW
val range2 = 5000.kW +- 1000.kW              // 4000.kW to 6000.kW
```

### Numeric Support
Most Quantities that support implicit conversions also include an implicit Numeric object that can be imported
to your code where Numeric support is required.  These follow the following pattern:

```scala
import squants.mass.MassConversions.MassNumeric

val sum = List(Kilograms(100), Grams(34510)).sum
```

NOTE - Because a quantity can not be multiplied by a like quantity and return a like quantity, the `Numeric.times`
operation of numeric is implemented to through an UnsupportedOperationException for all types except `Dimensionless`.

The MoneyNumeric implementation is a bit different than the implementations for other quantity types
in a few important ways.

1. MoneyNumeric is a class, not an object like the others.
2. To create a MoneyNumeric value there must be an implicit MoneyContext in scope.
3. The MoneyContext must contain applicable exchange rates if you will be applying cross-currency Numeric ops.

The following code provides a basic example for creating a MoneyNumeric:

```scala
import MoneyConversions._
implicit val moneyContext = defaultMoneyContext
implicit val moneyNum = new MoneyNumeric()

val sum = List(USD(100), USD(10)).sum
```

## Type Hierarchy
The type hierarchy includes the following core types:  Quantity, Dimension, and UnitOfMeasure

### Quantity and Dimension

A Dimension represents a type of Quantity. For example: Mass, Length, Time, etc.

A Quantity represents a dimensional value or measurement.  A Quantity is a combination of a numeric value and a unit.
For example:  2 lb, 10 km, 3.4 hr.

Squants has built in support for 52 quantity dimensions.

### Unit of Measure
UnitOfMeasure is the scale or multiplier in which the Quantity is being measured.
Squants has built in support for over 230 different units of measure

For each Dimension a set of UOM objects implement a primary UOM trait typed to that Quantity.
The UOM objects define the unit symbols, conversion factors, and factory methods for creating Quantities in that unit.

### Quantity Implementations

The code for specific implementations include

* A class representing the Quantity including cross-dimensional operations
* A companion object representing the Dimension and set of available units
* A base trait for its Units
* A set of objects defining specific units, their symbols and conversion factors

This is an abbreviated example of how a Quantity type is constructed:

```scala
class Length(val value: Double, val unit: LengthUnit) extends Quantity[Length]  { ... }
object Length extends Dimension[Length]  { ... }
trait LengthUnit extends UnitOfMeasure[Length]  { ... }
object Meters extends LengthUnit { ... }
object Yards extends LengthUnit { ... }
```

The apply method of the UOM objects are implemented as factories for creating Quantity values.

```scala
val len1: Length = Meters(4.3)
val len2: Length = Yards(5)
```

Squants currently supports 230 units of measure

### Time Derivatives

Special traits are used to establish a time derivative relationship between quantities.

For example Velocity is the 1st Time Derivative of Length (Distance), Acceleration is the 2nd Time Derivative.

```scala
class Length( ... ) extends Quantity[Length] with TimeIntegral[Velocity]
...
class Velocity( ... ) extends Quantity[Velocity] with TimeDerivative[Length] with TimeIntegral[Acceleration]
...
class Acceleration( ... ) extends Quantity[Acceleration] with TimeDerivative[Velocity]
```

These traits provide operations with time operands which result in correct dimensional transformations.

```scala
val distance: Length = Kilometers(100)
val time: Time = Hours(2)
val velocity: Velocity = distance / time
val acc: Acceleration = velocity / Seconds(1)

val gravity = 32.feet / second.squared
```

```scala
// Power is the 1st Time Derivative of Energy, PowerRamp is the 2nd
val power = Kilowatts(100)
val time: Time = Hours(2)
val energy = power * time
val ramp = Kilowatt(50) / Hours(1)
```

## Use Cases

### Dimensional Analysis

The primary use case for Squants, as described above, is to produce code that is typesafe within domains
that perform dimensional analysis.

```scala
val energyPrice: Price[Energy] = 45.25.money / megawattHour
val energyUsage: Energy = 345.kilowatts * 5.4.hours
val energyCost: Money = energyPrice * energyUsage

val dodgeViper: Acceleration = 60.miles / hour / 3.9.seconds
val speedAfter5Seconds: Velocity = dodgeViper * 5.seconds
val timeTo100MPH: Time = 100.miles / hour / dodgeViper

val density: Density = 1200.kilograms / cubicMeter
val volFlowRate: VolumeFlowRate = 10.gallons / minute
val flowTime: Time = 30.minutes
val totalMassFlow: Mass = volFlowRate * flowTime * density
```

### Domain Modeling
Another excellent use case for Squants is stronger typing for fields in your domain model.
This is OK ...

```scala
case class Generator(
  id: String,
  maxLoadKW: Double,
  rampRateKWph: Double,
  operatingCostPerMWh: Double,
  currency: String,
  maintenanceTimeHours: Double)
...
val gen1 = Generator("Gen1", 5000, 7500, 75.4, "USD", 1.5)
val gen2 = Generator("Gen2", 100, 250, 2944.5, "JPY", 0.5)
assetManagementActor ! ManageGenerator(gen1)
```

... but this is much better

```scala
case class Generator(
  id: String,
  maxLoad: Power,
  rampRate: PowerRamp,
  operatingCost: Price[Energy],
  maintenanceTime: Time)
...
val gen1 = Generator("Gen1", 5 MW, 7.5.MW/hour, 75.4.USD/MWh, 1.5 hours)
val gen2 = Generator("Gen2", 100 kW, 250 kWph, 2944.5.JPY/MWh, 30 minutes)
assetManagementActor ! ManageGenerator(gen1)
```

### Anticorruption Layers

Create wrappers around external services that use basic types to represent quantities.
Your application code then uses the ACL to communicate with that system thus eliminating the need to deal
with type and scale conversions in multiple places throughout your application logic.

```scala
class ScadaServiceAnticorruption(val service: ScadaService) {
  // ScadaService returns meter load as Double representing Megawatts
  def getLoad: Power = Megawatts(service.getLoad(meterId))
  }
  // ScadaService.sendTempBias requires a Double representing Fahrenheit
  def sendTempBias(temp: Temperature) =
    service.sendTempBias(temp.to(Fahrenheit))
}
```

Implement the ACL as a trait and mix in to the application's services where needed.

```scala
trait WeatherServiceAntiCorruption {
  val service: WeatherService
  def getTemperature: Temperature = Celsius(service.getTemperature)
  def getIrradiance: Irradiance = WattsPerSquareMeter(service.getIrradiance)
}
```

Extend the pattern to provide multi-currency support

```scala
class MarketServiceAnticorruption(val service: MarketService)
     (implicit val moneyContext: = MoneyContext) {

  // MarketService.getPrice returns a Double representing $/MegawattHour
  def getPrice: Price[Energy] =
    (USD(service.getPrice) in moneyContext.defaultCurrency) / megawattHour

  // MarketService.sendBid requires a Double representing $/MegawattHour
  // and another Double representing the max amount of energy in MegawattHours
  def sendBid(bid: Price[Energy], limit: Energy) =
    service.sendBid((bid * megawattHour) to USD, limit to MegawattHours)
}
```

Build Anticorruption into Akka routers

```scala
// LoadReading message used within a Squants enabled application context
case class LoadReading(meterId: String, time: Long, load: Power)
class ScadaLoadListener(router: Router) extends Actor {
  def receive = {
   // ScadaLoadReading - from an external service - sends load as a string
   // eg, "10.3 MW", "345 kW"
   case msg @ ScadaLoadReading(meterId, time, loadString) ⇒
    // Parse the string and on success emit the Squants enabled event to routees
    Power(loadString) match {
      case Success(p) => router.route(LoadReading(meterId, time, p), sender())
      case Failure(e) => // react to QuantityStringParseException
    }
  }
}
```

... and REST API's with contracts that require basic types

```scala
trait LoadRoute extends HttpService {
  def repo: LoadRepository
  val loadRoute = {
    path("meter-reading") {
      // REST API contract requires load value and units in different fields
      // Units are string values that may be 'kW' or 'MW'
      post {
        parameters(meterId, time, loadDouble, unit) { (meterId, time, loadDouble, unit) =>
          complete {
            val load = unit match {
              case "kW" => Kilowatts(loadDouble)
              case "MW" => Megawatts(loadDouble)
            }
            repo.saveLoad(meterId, time, load)
          }
        }
      } ~
      // REST API contract requires load returned as a number representing megawatts
      get {
        parameters(meterId, time) { (meterId, time) =>
          complete {
            repo.getLoad(meterId, time) to Megawatts
          }
        }
      }
    }
  }
}
```

## Contributors

* Gary Keorkunian ([garyKeorkunian](https://github.com/garyKeorkunian))
* Jeremy Apthorp ([nornagon](https://github.com/nornagon))
* Steve Barham ([stevebarham](https://github.com/stevebarham))

## Caveats

Code is offered as-is, with no implied warranty of any kind.
Comments, criticisms, and/or praise are welcome, especially from scientists, engineers and the like.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFML.Graphics;

namespace Genetic_Cars
{
  static class ColorExtensions
  {
    /// <summary>
    /// Sets the alpha of a color leaving RGB unmodified.
    /// </summary>
    /// <param name="c"></param>
    /// <param name="a"></param>
    /// <returns></returns>
    public static Color SetAlpha(this Color c, byte a)
    {
      return new Color(c.R, c.G, c.B, a);
    }
  }
}


text:
SELECT CANADA_FOOD_SUBGROUP_ID, CANADA_FOOD_SUBGROUP_CODE, CANADA_FOOD_SUBGROUP_DESC_E, CANADA_FOOD_SUBGROUP_DESC_F, CANADA_FOOD_GROUP_ID, PUBLICATION_CODE
  FROM CANADA_FOOD_SUBGROUP
 WHERE CANADA_FOOD_SUBGROUP_ID = ?


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.03 at 08:07:19 AM CET
//

package iso.std.iso._20022.tech.xsd.pain_008_003_02;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for CreditorReferenceTypeSEPA complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="CreditorReferenceTypeSEPA">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="CdOrPrtry" type="{urn:iso:std:iso:20022:tech:xsd:pain.008.003.02}CreditorReferenceTypeCodeSEPA"/>
 *         <element name="Issr" type="{urn:iso:std:iso:20022:tech:xsd:pain.008.003.02}Max35Text" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CreditorReferenceTypeSEPA", propOrder = {
    "cdOrPrtry",
    "issr"
})
public class CreditorReferenceTypeSEPA {

    @XmlElement(name = "CdOrPrtry", required = true)
    protected CreditorReferenceTypeCodeSEPA cdOrPrtry;
    @XmlElement(name = "Issr")
    protected String issr;

    /**
     * Gets the value of the cdOrPrtry property.
     *
     * @return
     *     possible object is
     *     {@link CreditorReferenceTypeCodeSEPA }
     *
     */
    public CreditorReferenceTypeCodeSEPA getCdOrPrtry() {
        return cdOrPrtry;
    }

    /**
     * Sets the value of the cdOrPrtry property.
     *
     * @param value
     *     allowed object is
     *     {@link CreditorReferenceTypeCodeSEPA }
     *
     */
    public void setCdOrPrtry(CreditorReferenceTypeCodeSEPA value) {
        this.cdOrPrtry = value;
    }

    /**
     * Gets the value of the issr property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getIssr() {
        return issr;
    }

    /**
     * Sets the value of the issr property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setIssr(String value) {
        this.issr = value;
    }

}


text:
'use strict';

var isArray = require('util').isArray;
var Lock    = require('lock');
var async   = require('async');

var kvOps = {};

function atomics(db) {
    var atomicsDb = {
        db: db
    };

    // copy all functions from db
    for (var k in db) {
        if (typeof db[k] === 'function') {
            atomicsDb[k] = db[k].bind(db);
        }
    }

    // mix in the methods
    for (k in kvOps) {
        // some methods overlap, save the original ones under '_' + method
        if (atomicsDb[k]) {
            atomicsDb['_' + k] = atomicsDb[k];
        }

        atomicsDb[k] = kvOps[k];
    }

    atomicsDb._lock = new Lock();

    // used to speed up concurrent increments
    atomicsDb._counters = {};

    // used to speedup concurrent gets of the same key
    atomicsDb._fetchers = {};

    return atomicsDb;
}

atomics.tuple = _tuple;

// kvOps.append = function (keys, fragment, callback) {

// };

kvOps.counter = function (tuples, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options  = {};
    }

    var tasks = {},
        initial;

    if (options.hasOwnProperty('initial')) {
        initial = options.initial;
        delete options.initial;
    }

    _array(Object.keys(tuples)).forEach(function (key) {
        // create async tasks
        tasks[key] = function __tryCounter(callback) {
            var committer = false;

            // if there isn't another batch handling the counter, this will be the
            // committer for this key
            if (!this._counters[key]) {
                // init batch
                this._counters[key] = [];

                committer = true;
            }

            var batch = this._counters[key];

            batch.length;

            // add this entry to batch
            batch.push({
                delta:    parseInt(tuples[key], 10),
                callback: function (err, value) {
                    callback(err, value);
                }
            });

            // if this is the committer for the key, prepare to update it
            if (committer) {
                // lock and get key
                _lockAndGet(this, key, options, function __handleLockAndGet(oldValue, callback) {
                    // if no oldValue, use initial
                    var newValue = (oldValue === undefined) ? initial : parseInt(oldValue, 10) + tuples[key]; // TODO: make initial required in doc

                    // remove batch
                    delete this._counters[key];

                    var tmp = newValue;

                    // prepare to call back others waiting, including own callback
                    batch[0].err   = null;
                    batch[0].value = tmp;

                    for (var i = 1; i < batch.length; i++) {
                        tmp += batch[i].delta;

                        batch[i].err   = null;
                        batch[i].value = tmp;
                    }

                    // update the key
                    this._put(key, tmp, options, function __handlePut(err) {
                        if (err) {
                            return callback(err, true); // true to signal to keep any current batch, since it's a new batch
                        }

                        _callbackCounters(this, batch);

                        // all done
                        return callback();
                    });
                }.bind(this), function __handleCounterUpdate(err, keepBatch) {
                    if (err) {
                        for (var i = 0; i < batch.length; i++) {
                            batch[i].err   = err;
                            batch[i].value = undefined;
                        }

                        if (!keepBatch) {
                            delete this._counters[key];
                        }

                        return _callbackCounters(this, batch);
                    }
                }.bind(this));
            }
        }.bind(this);
    }.bind(this));

    // console.log('executing', tasks);

    async.parallel(tasks, function __handleGets(err, res) {
        if (err) {
            return callback(err);
        }

        var misses   = [];
        var finalRes = {};

        for (var k in res) {
            if (res[k] === undefined) {
                misses.push(k);
            } else {
                finalRes[k] = res[k];
            }
        }

        return callback(null, finalRes, misses);
    });

    return this;
};

kvOps.del = function (keys, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options  = {};
    }

    var tasks = {};

    _array(keys).forEach(function (key) {
        tasks[key] = _lockAndGet.bind(null, this, key, options, function __handle(value, callback) {
            this._del(key, options, callback);
        }.bind(this));
    }.bind(this));

    async.parallel(tasks, function (err) {
        if (err) {
            return callback(err);
        }

        return callback(null);
    });

    return this;
};

kvOps.get = function (keys, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options  = {};
    }

    var tasks = {};

    _array(keys).forEach(function (key) {
        // tasks[key] = _get.bind(null, this, key, options);
        tasks[key] = _collapseGet.bind(null, this, key, options);
    }.bind(this));

    async.parallel(tasks, function __handleGets(err, res) {
        if (err) {
            return callback(err);
        }

        var misses   = [];
        var finalRes = {};

        for (var k in res) {
            if (res[k] === undefined) {
                misses.push(k);
            } else {
                finalRes[k] = res[k];
            }
        }

        return callback(null, finalRes, misses);
    });

    return this;
};

kvOps.insert = function (tuples, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options  = {};
    }

    var tasks = {};

    _array(Object.keys(tuples)).forEach(function (key) {
        tasks[key] = function __tryInsert(callback) {
            // start by quickly checking if the key exists and give up before
            // trying to lock it
            this.get(key, options, function __handleGet(err, res) {
                if (err) {
                    return callback(err);
                }

                var value = res[key];

                // if key already exists, give up
                if (value !== undefined) {
                    return callback(null, true); // key already existed
                }

                // there is a strong chance that the key does not exist, let's
                // lock and get it
                _lockAndGet(this, key, options, function __handle(value, callback) {
                    // if value already exists, insert fails
                    if (value !== undefined) {
                        return callback(null, true); // key already existed
                    }

                    this._put(key, tuples[key], options, function __handlePut(err) {
                        if (err) {
                            return callback(err);
                        }

                        return callback(null, false); // key did not exist
                    });
                }.bind(this), callback);
            }.bind(this));
        }.bind(this);
    }.bind(this));

    async.parallel(tasks, function __handleInserts(err, res) {
        if (err) {
            return callback(err);
        }

        var existing = [];

        for (var k in res) {
            if (res[k]) {
                existing.push(k);
            }
        }

        return callback(null, existing);
    });

    return this;
};

// kvOps.prepend = function (keys, fragment, callback) {

// };

kvOps.put = function (tuples, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options  = {};
    }

    var tasks = {};

    _array(Object.keys(tuples)).forEach(function (key) {
        tasks[key] = this._put.bind(this, key, tuples[key], options);
    }.bind(this));

    async.parallel(tasks, function __handlePuts(err) {
        if (err) {
            return callback(err);
        }

        return callback();
    });

    return this;
};

kvOps.replace = function (tuples, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options  = {};
    }

    var tasks = {};

    _array(Object.keys(tuples)).forEach(function (key) {
        tasks[key] = _lockAndGet.bind(null, this, key, options, function __handle(value, callback) {
            // if value does not exist, replace fails
            if (value === undefined) {
                return callback(null, true); // key missing
            }

            this._put(key, tuples[key], options, function __handlePut(err) {
                if (err) {
                    return callback(err);
                }

                return callback(null, false); // key existed
            });
        }.bind(this));
    }.bind(this));

    async.parallel(tasks, function (err, res) {
        if (err) {
            return callback(err);
        }

        var existing = [];

        for (var k in res) {
            if (res[k]) {
                existing.push(k);
            }
        }

        return callback(null, existing);
    });

    return this;
};

// -----------------------------------------------------------------------------

function _lockAndGet(db, key, options, handler, callback) {
    db._lock(key, function __handleLock(release) {
        db.get(key, options, function __handleGet(err, res) {
            if (err) {
                return callback(err);
            }

            return handler(res[key], release(callback));
        });
    });
}

function _collapseGet(db, key, options, callback) {
    var fetcher = false;

    // if there isn't another batch fetching the key, this will be the
    // fetcher for this key
    if (!db._fetchers[key]) {
        // init batch
        db._fetchers[key] = [];

        fetcher = true;
    }

    var batch = db._fetchers[key];

    // add this callback to batch
    var batchPosition = batch.push(callback);
    batchPosition--; // fix 0 indexed position

    // if this is the fetcher for the key, prepare to get it
    if (fetcher) {
        // get the key
        db._get(key, options, function __handleGet(err, value) {
            if (err && !err.notFound) {
                return _callbackGets(db, key, err);
            }

            return _callbackGets(db, key, null, value);
        });
    }
}

function _array(x) {
    return isArray(x) ? x : [x];
}

function _tuple(k, v) {
    var res = {};

    // if it's a set of keys and respective values
    if (isArray(k)) {
        for (var i = k.length - 1; i >= 0; i--) {
            res[k[i]] = v[i];
        }

        return res;
    }

    // just a key and a value
    res[k] = v;

    return res;
}

function _callbackCounters(db, batch) {
    for (var i = 0; i < batch.length; i++) {
        setImmediate(batch[i].callback, batch[i].err, batch[i].value);
    }

    return;
}

function _callbackGets(db, key, err, value) {
    var batch = db._fetchers[key];

    for (var i = 0; i < batch.length; i++) {
        setImmediate(batch[i], err, value);
    }

    // remove batch
    delete db._fetchers[key];

    return;
}

module.exports = atomics;


text:
TEST(socket,socket)
{
    socket_failable_by__(EAFNOSUPPORT)
    {
        ASSERT_EQ(-1, socket(AF_INET, SOCK_STREAM, 0));
        ASSERT_EQ(EAFNOSUPPORT, errno);
    }
}
#endif

#ifdef HAVE_SOCKETPAIR
TEST(socket,socketpair)
{
    socketpair_failable_by__(EAFNOSUPPORT)
    {
        int fds[2] = {0,0};
        ASSERT_EQ(-1, socketpair(AF_INET, SOCK_STREAM, 0, fds));
        ASSERT_EQ(EAFNOSUPPORT, errno);
    }
}
#endif

#ifdef HAVE_BIND
TEST(socket,bind)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    bind_failable_by__(EACCES)
    {
        struct sockaddr_in addr;
        addr.sin_port = htons(12345);
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = htonl(INADDR_ANY);
        ASSERT_EQ(-1, bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)));
        ASSERT_EQ(EACCES, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_GETSOCKNAME
TEST(socket,getsockname)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    getsockname_failable_by__(ENOBUFS)
    {
        struct sockaddr_in addr;
        socklen_t addrlen = 0;
        ASSERT_EQ(-1, getsockname(sockfd, (struct sockaddr*)&addr, &addrlen));
        ASSERT_EQ(ENOBUFS, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_CONNECT
TEST(socket,connect)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    connect_failable_by__(EALREADY)
    {
        struct sockaddr_in addr;
        addr.sin_port = htons(12345);
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = inet_addr("127.0.0.1");
        ASSERT_EQ(-1, connect(sockfd, (struct sockaddr*)&addr, sizeof(addr)));
        ASSERT_EQ(EALREADY, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_GETPEERNAME
TEST(socket,getpeername)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    getpeername_failable_by__(ENOTSOCK)
    {
        struct sockaddr_in addr;
        socklen_t addrlen = 0;
        ASSERT_EQ(-1, getpeername(sockfd, (struct sockaddr*)&addr, &addrlen));
        ASSERT_EQ(ENOTSOCK, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_SEND
TEST(socket,send)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    send_failable_by__(ECONNRESET)
    {
        ASSERT_EQ(-1, send(sockfd, NULL, 0, 0));
        ASSERT_EQ(ECONNRESET, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_RECV
TEST(socket,recv)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    recv_failable_by__(ECONNREFUSED)
    {
        ASSERT_EQ(-1, recv(sockfd, NULL, 0, 0));
        ASSERT_EQ(ECONNREFUSED, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_SENDTO
TEST(socket,sendto)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    sendto_failable_by__(ECONNRESET)
    {
        struct sockaddr_in addr;
        addr.sin_port = htons(12345);
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = inet_addr("127.0.0.1");
        ASSERT_EQ(-1, sendto(sockfd, NULL, 0, 0,
                             (const struct sockaddr*)&addr, sizeof(addr)));
        ASSERT_EQ(ECONNRESET, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_RECVFROM
TEST(socket,recvfrom)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    recvfrom_failable_by__(ECONNREFUSED)
    {
        struct sockaddr_in addr;
        addr.sin_port = htons(12345);
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = inet_addr("127.0.0.1");
        socklen_t addrlen = 0;
        ASSERT_EQ(-1, recvfrom(sockfd, NULL, 0, 0,
                               (struct sockaddr*)&addr, &addrlen));
        ASSERT_EQ(ECONNREFUSED, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_SENDMSG
TEST(socket,sendmsg)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    sendmsg_failable_by__(ECONNRESET)
    {
        struct msghdr msg;
        ASSERT_EQ(-1, sendmsg(sockfd, &msg, 0));
        ASSERT_EQ(ECONNRESET, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_RECVMSG
TEST(socket,recvmsg)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    recvmsg_failable_by__(ECONNREFUSED)
    {
        struct msghdr msg;
        ASSERT_EQ(-1, recvmsg(sockfd, &msg, 0));
        ASSERT_EQ(ECONNREFUSED, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_GETSOCKOPT
TEST(socket,getsockopt)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    getsockopt_failable_by__(ENOPROTOOPT)
    {
        int optval = 0;
        socklen_t optlen = 0;
        ASSERT_EQ(-1, getsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
                                 &optval, &optlen));
        ASSERT_EQ(ENOPROTOOPT, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_SETSOCKOPT
TEST(socket,setsockopt)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    setsockopt_failable_by__(ENOPROTOOPT)
    {
        int optval = 0;
        ASSERT_EQ(-1, setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
                                 &optval, sizeof(optval)));
        ASSERT_EQ(ENOPROTOOPT, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_LISTEN
TEST(socket,listen)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    listen_failable_by__(EADDRINUSE)
    {
        ASSERT_EQ(-1, listen(sockfd, 1));
        ASSERT_EQ(EADDRINUSE, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_ACCEPT
TEST(socket,accept)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    accept_failable_by__(ECONNABORTED)
    {
        struct sockaddr_in addr;
        socklen_t addrlen = 0;
        ASSERT_EQ(-1, accept(sockfd, (struct sockaddr*)&addr, &addrlen));
        ASSERT_EQ(ECONNABORTED, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_ACCEPT4
TEST(socket,accept4)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    accept4_failable_by__(ECONNABORTED)
    {
        struct sockaddr_in addr;
        socklen_t addrlen = 0;
        ASSERT_EQ(-1, accept4(sockfd, (struct sockaddr*)&addr, &addrlen,
                              SOCK_CLOEXEC));
        ASSERT_EQ(ECONNABORTED, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_SHUTDOWN
TEST(socket,shutdown)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    shutdown_failable_by__(ENOTSOCK)
    {
        ASSERT_EQ(-1, shutdown(sockfd, SHUT_RDWR));
        ASSERT_EQ(ENOTSOCK, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_SOCKATMARK
TEST(socket,sockatmark)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    sockatmark_failable_by__(EBADF)
    {
        ASSERT_EQ(-1, sockatmark(sockfd));
        ASSERT_EQ(EBADF, errno);
    }
    close(sockfd);
}
#endif

#ifdef HAVE_ISFDTYPE
TEST(socket,isfdtype)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    isfdtype_failable__
    {
        ASSERT_EQ(-1, isfdtype(sockfd, S_IFREG));
        ASSERT_EQ(EBADF, errno);
    }
    close(sockfd);
}
#endif


text:
#ifndef _IGNITE_IMPL
#define _IGNITE_IMPL

#include <ignite/common/concurrent.h>
#include <ignite/common/java.h>

#include "ignite/impl/cache/cache_impl.h"
#include "ignite/impl/ignite_environment.h"
#include "ignite/impl/utils.h"

namespace ignite
{
    namespace impl
    {
        /**
         * Ignite implementation.
         */
        class IGNITE_FRIEND_EXPORT IgniteImpl
        {
            friend class Ignite;
        public:
            /**
             * Constructor used to create new instance.
             *
             * @param env Environment.
             * @param javaRef Reference to java object.
             */
            IgniteImpl(ignite::common::concurrent::SharedPointer<IgniteEnvironment> env, jobject javaRef);

            /**
             * Destructor.
             */
            ~IgniteImpl();

            /**
             * Get name of the Ignite.
             *
             * @param Name.
             */
            const char* GetName() const;

            /**
             * Get JNI context associated with this instance.
             *
             * @return JNI context for this instance.
             */
            common::java::JniContext* GetContext();

            /**
             * Get cache.
             *
             * @param name Cache name.
             * @param err Error.
             */
            template<typename K, typename V>
            cache::CacheImpl* GetCache(const char* name, IgniteError* err)
            {
                ignite::common::java::JniErrorInfo jniErr;

                jobject cacheJavaRef = env.Get()->Context()->ProcessorCache(javaRef, name, &jniErr);

                if (!cacheJavaRef)
                {
                    IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

                    return NULL;
                }

                char* name0 = utils::CopyChars(name);

                return new cache::CacheImpl(name0, env, cacheJavaRef);
            }

            /**
             * Get or create cache.
             *
             * @param name Cache name.
             * @param err Error.
             */
            template<typename K, typename V>
            cache::CacheImpl* GetOrCreateCache(const char* name, IgniteError* err)
            {
                ignite::common::java::JniErrorInfo jniErr;

                jobject cacheJavaRef = env.Get()->Context()->ProcessorGetOrCreateCache(javaRef, name, &jniErr);

                if (!cacheJavaRef)
                {
                    IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

                    return NULL;
                }

                char* name0 = utils::CopyChars(name);

                return new cache::CacheImpl(name0, env, cacheJavaRef);
            }

            /**
             * Create cache.
             *
             * @param name Cache name.
             * @param err Error.
             */
            template<typename K, typename V>
            cache::CacheImpl* CreateCache(const char* name, IgniteError* err)
            {
                ignite::common::java::JniErrorInfo jniErr;

                jobject cacheJavaRef = env.Get()->Context()->ProcessorCreateCache(javaRef, name, &jniErr);

                if (!cacheJavaRef)
                {
                    IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

                    return NULL;
                }

                char* name0 = utils::CopyChars(name);

                return new cache::CacheImpl(name0, env, cacheJavaRef);
            }

            /**
             * Get instance of the implementation from the proxy class.
             * Internal method. Should not be used by user.
             *
             * @param proxy Proxy instance containing IgniteImpl.
             * @return IgniteImpl instance associated with the proxy or null-pointer.
             */
            template<typename T>
            static IgniteImpl* GetFromProxy(T& proxy)
            {
                return proxy.impl.Get();
            }
        private:
            /** Environment. */
            ignite::common::concurrent::SharedPointer<IgniteEnvironment> env;

            /** Native Java counterpart. */
            jobject javaRef;

            IGNITE_NO_COPY_ASSIGNMENT(IgniteImpl)
        };
    }
}

#endif


text:
package org.hibernate;

/**
 * Represents an association fetching strategy. This is used
 * together with the <tt>Criteria</tt> API to specify runtime
 * fetching strategies.

 *

 * For HQL queries, use the <tt>FETCH</tt> keyword instead.
 *
 * @see Criteria#setFetchMode(java.lang.String, FetchMode)
 * @author Gavin King
 */
public enum FetchMode  {
	/**
	 * Default to the setting configured in the mapping file.
	 */
	DEFAULT,

	/**
	 * Fetch using an outer join. Equivalent to <tt>fetch="join"</tt>.
	 */
	JOIN,
	/**
	 * Fetch eagerly, using a separate select. Equivalent to
	 * <tt>fetch="select"</tt>.
	 */
	SELECT;

	/**
	 * Fetch lazily. Equivalent to <tt>outer-join="false"</tt>.
	 * @deprecated use <tt>FetchMode.SELECT</tt>
	 */
	public static final FetchMode LAZY = SELECT;
	/**
	 * Fetch eagerly, using an outer join. Equivalent to
	 * <tt>outer-join="true"</tt>.
	 * @deprecated use <tt>FetchMode.JOIN</tt>
	 */
	public static final FetchMode EAGER = JOIN;
}


text:
require 'spec_helper'

describe Surkle do

end


text:
{-# LANGUAGE FlexibleInstances #-}
module System.Environment.Extract where

import System.Environment (getEnvironment)

import qualified Data.HashMap.Strict as H
--import qualified Data.List.NonEmpty as NE
import Data.Semigroup (Semigroup, (<>))
import Text.Read (readEither)

import Control.Applicative (Applicative, (<*>), pure, Alternative, empty, (<|>), (<$>))
--import Control.Monad

type EnvKey = String
type EnvVal = String
type EnvMap = H.HashMap EnvKey EnvVal
type TypeReport = String
type ValueReport = String

emptyEnvVal :: EnvVal
emptyEnvVal = ""

getEnvValue :: EnvKey -> EnvMap -> Maybe EnvVal
getEnvValue = H.lookup

getEnvDefault :: EnvVal -> EnvKey -> EnvMap -> EnvVal
getEnvDefault = H.lookupDefault

data FailReport =
    MissingKey { frType :: TypeReport, frKey :: EnvKey } |
    MalformedValue { frType :: TypeReport, frKey :: EnvKey, frGot :: EnvVal, frMsg :: Maybe String}
    deriving (Eq, Show)

data SuccessReport =
    LeafValue { vrType :: TypeReport, vrValue :: ValueReport, vrKey :: EnvKey, vrGot :: EnvVal } |
    DefaultValue { vrType :: TypeReport, vrValue :: ValueReport, vrKey :: EnvKey }
    deriving (Eq, Show)

-- | the Result of running an extractor
-- contains reports etc.
-- has 3 varieties
--  - Fail: non-recoverable failure
--  - FailRec: recoverable failure
--  - Success: succesfully extracted value
data Result a =
    Fail [FailReport] [SuccessReport] |
    FailRec [FailReport] [SuccessReport] |
    Success a [SuccessReport]
    deriving (Eq, Show)

joinFails :: ([FailReport] -> [SuccessReport] -> Result a) -> [FailReport] -> [SuccessReport] -> [FailReport] -> [SuccessReport] -> Result a
joinFails con frs1 srs1 frs2 srs2 = con (frs1 <> frs2) (srs1 <> srs2)

joinSuccessAndFail :: ([FailReport] -> [SuccessReport] -> Result b) -> [FailReport] -> [SuccessReport] -> a -> [SuccessReport] -> Result b
joinSuccessAndFail con frs1 srs1 _ srs2 = con frs1 (srs1 <> srs2)

instance Functor Result where
    fmap f = result Fail FailRec (Success . f)

instance Applicative Result where
    pure v = Success v []
    (<*>) = result onFail onFailRec onSuccess
        where onFail frs srs = result (joinFails Fail frs srs) (joinFails Fail frs srs) (joinSuccessAndFail Fail frs srs)
              onFailRec frs srs = result (joinFails Fail frs srs) (joinFails FailRec frs srs) (joinSuccessAndFail FailRec frs srs)
              onSuccess fun srs1 = result (compMappend srs1 . Fail) (compMappend srs1 . FailRec) (compMappend srs1 . Success . fun)

instance Alternative Result where
    empty = FailRec [] []
    (<|>) = result onFail onFailRec ((const .) . Success)
        where onFail frs srs = result (joinFails Fail frs srs) (joinFails Fail frs srs) (joinSuccessAndFail Fail frs srs)
              onFailRec frs srs = result (joinFails Fail frs srs) (joinFails FailRec frs srs) Success

--i suspect this instance is not valid.
{-
instance Monad Result where
    return = pure
    r >>= f = result Fail FailRec onSuccess r
        where onSuccess v srs = result (compMappend srs . Fail) (compMappend srs . FailRec) (compMappend srs . Success) $ f v

instance MonadPlus Result where
    mzero = empty
    mplus = (<|>)
-}

-- | case analysis for the Result type
result :: ([FailReport] -> [SuccessReport] -> b) -> ([FailReport] -> [SuccessReport] -> b)-> (a -> [SuccessReport] -> b) -> Result a -> b
result f _ _ (Fail frs srs) = f frs srs
result _ f _ (FailRec frs srs) = f frs srs
result _ _ f (Success v srs) = f v srs

singleFail :: FailReport -> Result a
singleFail fr = Fail (pure fr) []

singleFailRec :: FailReport -> Result a
singleFailRec fr = FailRec (pure fr) []

missingKeyFail :: TypeReport -> EnvKey -> Result a
missingKeyFail tr k = singleFailRec $ MissingKey tr k

malformedValueFail :: TypeReport -> EnvKey -> EnvVal -> Result a
malformedValueFail tr k got = singleFail $ MalformedValue tr k got Nothing

malformedValueFailMsg :: TypeReport -> EnvKey -> EnvVal -> String -> Result a
malformedValueFailMsg tr k got msg = singleFail $ MalformedValue tr k got (Just msg)

valueSuccess :: a -> SuccessReport -> Result a
valueSuccess v sr = Success v [sr]

leafSuccess :: TypeReport -> ValueReport -> EnvKey -> EnvVal -> a-> Result a
leafSuccess tr vr k ev v = valueSuccess v $ LeafValue tr vr k ev

defaultSuccess :: TypeReport -> ValueReport -> EnvKey -> a -> Result a
defaultSuccess tr vr k v = valueSuccess v $ DefaultValue tr vr k

-- | the Extractor function is to take a key (prefix) and the environment
-- map, and produce a Result for its type.
-- (<*>) produces extractors that will pass the received key
-- prefix to the component extractors
newtype Extractor a = Extractor { runExtractor :: EnvKey -> EnvMap -> Result a }

instance Functor Extractor where
    fmap f e = Extractor $ \k env -> f <$> runExtractor e k env

instance Applicative Extractor where
    pure v = Extractor $ \_ _ -> pure v
    f <*> e = Extractor $ \k env -> runExtractor f k env <*> runExtractor e k env

{-
instance Monad Extractor where
    return = pure
    e >>= f = Extractor $ \k env -> runExtractor e k env >>= \v -> runExtractor (f v) k env
-}

leafExtraction :: (EnvVal -> Maybe a) -> TypeReport -> (a -> ValueReport) -> EnvKey -> EnvMap -> Result a
leafExtraction p tr vr k env = maybe (missingKeyFail tr k) (parse <*> p) $ getEnvValue k env
    where parse ev = maybe (malformedValueFail tr k ev) (success ev)
          success ev v = leafSuccess tr (vr v) k ev v

leafExtractionMsg :: (EnvVal -> Either String a) -> TypeReport -> (a -> ValueReport) -> EnvKey -> EnvMap -> Result a
leafExtractionMsg p tr vr k env = maybe (missingKeyFail tr k) (parse <*> p) $ getEnvValue k env
    where parse ev = either (malformedValueFailMsg tr k ev) (success ev)
          success ev v = leafSuccess tr (vr v) k ev v

leafExtractor :: (EnvVal -> Maybe a) -> TypeReport -> (a -> ValueReport) -> Extractor a
leafExtractor p tr vr = Extractor $ leafExtraction p tr vr

leafExtractorMsg :: (EnvVal -> Either String a) -> TypeReport -> (a -> ValueReport) -> Extractor a
leafExtractorMsg p tr vr = Extractor $ leafExtractionMsg p tr vr

-- | define an extractor easily
readShowLeafExtractor :: (Read a, Show a) => TypeReport -> Extractor a
readShowLeafExtractor tr = leafExtractorMsg readEither tr show

-- | an Extractable type has an Extractor defined for it
class Extractable e where
    extractor :: Extractor e

-- | a Defaulter can be used to produce a DefaultValue report
data Defaulter a = Defaulter { defaulterTypeReport :: TypeReport, defaulterValueReport :: a -> ValueReport }

mkDefaultReport :: Defaulter a -> EnvKey -> a -> SuccessReport
mkDefaultReport (Defaulter tr vr) k v = DefaultValue tr (vr v) k

mkDefaultSuccess :: Defaulter a -> EnvKey -> a -> Result a
mkDefaultSuccess (Defaulter tr vr)  k v = defaultSuccess tr (vr v) k v

-- | easily define a defaulter
showDefaulter :: Show a => TypeReport -> Defaulter a
showDefaulter tr = Defaulter tr show

-- | an ExtractableDefault type is an Extractable that can also produce
-- defaulting Extractors.
-- minimal definition: defaulter
class Extractable e => ExtractableDefault e where
    defaulter :: Defaulter e

    extractorWithDefault :: e -> Extractor e
    extractorWithDefault v = Extractor $ \k env -> runExtractor extractor k env <|> mkDefaultSuccess defaulter k v

instance Extractable [Char] where
    extractor = leafExtractor Just "[Char]" id

instance ExtractableDefault [Char] where
    defaulter = Defaulter "[Char]" id

instance Extractable Integer where
    extractor = readShowLeafExtractor "Integer"

instance ExtractableDefault Integer where
    defaulter = showDefaulter "Integer"

instance Extractable Bool where
    extractor = readShowLeafExtractor "Bool"

instance ExtractableDefault Bool where
    defaulter = showDefaulter "Bool"

-- | default key section separator
defaultSeparator :: EnvKey
defaultSeparator = "_"

-- | produce a new extractor that searches for a key with the prefix
-- extended by the separator and segment
extractorSep :: Extractor a -> EnvKey -> EnvKey -> Extractor a
extractorSep e sep append = Extractor $ \k env -> runExtractor e (k <> sep <> append) env

-- | produces an extractor that searches for an extended key
extractSep :: Extractable a => EnvKey -> EnvKey -> Extractor a
extractSep = extractorSep extractor

-- | produces a defaulting extractor that searches for an extended key
extractSepDefault :: ExtractableDefault a => a -> EnvKey -> EnvKey -> Extractor a
extractSepDefault = extractorSep . extractorWithDefault

-- | produces an extractor that searches for a key with the specified segment added to the prefix
extract :: Extractable a => EnvKey -> Extractor a
extract = extractSep defaultSeparator

-- | produces a defaulting extractor that searches for the key with the segment added
-- to the prefix
extractDefault :: ExtractableDefault a => a -> EnvKey -> Extractor a
extractDefault = flip extractSepDefault defaultSeparator

extractOn :: Extractor a -> EnvKey -> [(EnvKey, EnvVal)] -> Result a
extractOn e k env = runExtractor e k $ H.fromList env

extractResult :: Extractable a => EnvKey -> [(EnvKey, EnvVal)] -> Result a
extractResult = extractOn extractor

extractOnIO :: Extractor a -> EnvKey -> IO (Result a)
extractOnIO e k = extractOn e k <$> getEnvironment

extractResultIO :: Extractable a => EnvKey -> IO (Result a)
extractResultIO = extractOnIO extractor

compMappend :: Semigroup b => b -> (b -> c) -> b -> c
compMappend l f r = f (l <> r)

infixr 6 .<>
(.<>) :: Semigroup b => b -> (b -> c) -> b -> c
(.<>) = compMappend


text:
/*@ngInject*/
function fn($http) {
    return {
        getList: function () {
            return $http.get('/data/viewsList').then((data) => {
                var views = data.data;
                return views;
            });
        }
    }
}

module.exports = fn;


text:
package com.sequenceiq.freeipa.flow.freeipa.diagnostics.event;

import com.sequenceiq.flow.core.FlowEvent;

public enum DiagnosticsCollectionHandlerSelectors implements FlowEvent {
    SALT_VALIDATION_DIAGNOSTICS_EVENT,
    SALT_PILLAR_UPDATE_DIAGNOSTICS_EVENT,
    SALT_STATE_UPDATE_DIAGNOSTICS_EVENT,
    PREFLIGHT_CHECK_DIAGNOSTICS_EVENT,
    INIT_DIAGNOSTICS_EVENT,
    UPGRADE_DIAGNOSTICS_EVENT,
    VM_PREFLIGHT_CHECK_DIAGNOSTICS_EVENT,
    ENSURE_MACHINE_USER_EVENT,
    COLLECT_DIAGNOSTICS_EVENT,
    UPLOAD_DIAGNOSTICS_EVENT,
    CLEANUP_DIAGNOSTICS_EVENT;

    @Override
    public String event() {
        return name();
    }
}


text:
package com.tw.tradeaway.entities;

import lombok.Data;

import javax.persistence.*;

@Data
@Entity
@Table(name = "Order_Details")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @OneToOne
    @JoinColumn(name = "Product_ID", referencedColumnName = "id")
    private Product product;
    @Column(name = "Buyer_ID", nullable = false)
    private int buyerID;
    @Column(name = "Seller_ID",nullable = false)
    private int sellerID;
    @Column(name = "Quantity", nullable = false)
    private int quantity;
    @Column(name = "Delivery_Address", nullable = false)
    private String deliveryAddress;

    @Column(name = "Status", nullable = false)
    private String status;

    public Order(Product product,int buyerID, int sellerID, int quantity, String deliveryAddress, String status) {
        this.product=product;
        this.buyerID = buyerID;
        this.sellerID = sellerID;
        this.quantity = quantity;
        this.deliveryAddress = deliveryAddress;
        this.status = status;
    }

    public Order() {
    }

    public int getId() {
        return id;
    }

    public Product getProduct() {
        return product;
    }

    public int getBuyerID() {
        return buyerID;
    }

    public int getSellerID() {
        return sellerID;
    }

    public int getQuantity() {
        return quantity;
    }

    public String getDeliveryAddress() {
        return deliveryAddress;
    }

    public String getStatus() {
        return status;
    }

}


text:
(function() {
/* global define, validator */
define('validator-js', [], function() {
  "use strict";

  return {
    'default': window.validator || window.module.exports
  };
});
})();


text:
/**
 * Generates a new, generic route guard definition in the given or default project.
 */
export interface Schema {
    /**
     * When true (the default), creates the new files at the top level of the current project.
     */
    flat?: boolean;
    /**
     * Specifies which interfaces to implement.
     */
    implements?: string[];
    /**
     * When true, applies lint fixes after generating the guard.
     */
    lintFix?: boolean;
    /**
     * The name of the new route guard.
     */
    name: string;
    /**
     * The path at which to create the interface that defines the guard, relative to the current
     * workspace.
     */
    path?: string;
    /**
     * The name of the project.
     */
    project: string;
    /**
     * When true, does not create "spec.ts" test files for the new guard.
     */
    skipTests?: boolean;
    /**
     * When true (the default), generates a  "spec.ts" test file for the new guard.
     * @deprecated Use "skipTests" instead.
     */
    spec?: boolean;
}


text:
@interface StudiengangTableView ()
{
    NSDictionary *_studiengang;
}

- (NSString *)gradeRange:(float)grade;

@end

@implementation StudiengangTableView

//Bereitet die Tabelle vor.
- (id)initWithFrame:(CGRect)frame dictionary:(NSDictionary *)studiengang
{
    self = [super initWithFrame:frame style:UITableViewStyleGrouped];
    if (self)
    {
        _studiengang = studiengang;
        self.delegate = self;
        self.dataSource = self;
        self.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        self.backgroundView = nil;
        self.backgroundColor = kCUSTOM_BACKGROUND_PATTERN_COLOR;
        UINib *nib = [UINib nibWithNibName:@"StatistikCell_" bundle:nil];
        [self registerNib:nib forCellReuseIdentifier:@"StatCell"];
    }
    return self;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    switch (section)
    {
        case 0:
            return NSLocalizedString(@"Creditpunkte", @"Creditpunkte");
            break;
        case 1:
            return NSLocalizedString(@"Noten", @"Noten");
        case 2:
            return NSLocalizedString(@"Zeit", @"Zeit");
        default:
            break;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section)
    {
        case 0:
            return 3;
        case 1:
            return 3;
        case 2:
            return 2;
        default:
            break;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StatistikCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StatCell"];

    switch (indexPath.section)
    {
        case 0: //Creditpunkte
            if (indexPath.row == 0)
            {
                cell.textLabel.text = NSLocalizedString(@"Erreicht", @"Erreicht");
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ CP", [_studiengang objectForKey:kAchievedCP]];
                int erreicht = [[_studiengang objectForKey:kAchievedCP] intValue];
                if (erreicht > 0)
                {
                    int aktuellesSemester = [[_studiengang objectForKey:kCurrentSemesterIndex] intValue];
                    int semester = [[_studiengang objectForKey:kLastSemesterIndexWithAchievedEintraege] intValue];
                    if (semester > aktuellesSemester)
                    {
                        cell.detailDetailTextLabel.text = [NSString stringWithFormat:@"%@ %i. %@", NSLocalizedString(@"bis einschließlich des", @"bis einschließlich des"), semester, NSLocalizedString(@"Semesters", @"Semesters")];
                    }
                    else
                    {
                        cell.detailDetailTextLabel.text = NSLocalizedString(@"inkl. des aktuellen Semesters", @"inkl. des aktuellen Semesters");
                    }
                }
                else
                {
                    cell.detailDetailTextLabel.text = @"";
                }
            }
            else if (indexPath.row == 1)
            {
                cell.textLabel.text = NSLocalizedString(@"Geplant", @"Geplant");
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ CP", [_studiengang objectForKey:kOpenCP]];
                int geplant = [[_studiengang objectForKey:kOpenCP] intValue];
                if (geplant > 0)
                {
                    int aktuellesSemester = [[_studiengang objectForKey:kCurrentSemesterIndex] intValue];
                    int semester = [[_studiengang objectForKey:kLastSemesterIndexForAnyEintraege] intValue];
                    if (semester > aktuellesSemester)
                    {
                        cell.detailDetailTextLabel.text = [NSString stringWithFormat:@"%@ %i. %@", NSLocalizedString(@"bis einschließlich des", @"bis einschließlich des"), semester, NSLocalizedString(@"Semesters", @"Semesters")];
                    }
                    else
                    {
                        cell.detailDetailTextLabel.text = NSLocalizedString(@"inkl. des aktuellen Semesters", @"inkl. des aktuellen Semesters");
                    }

                }
                else
                {
                    cell.detailDetailTextLabel.text = @"";
                }

            }
            else
            {
                int ausstehend = [[_studiengang objectForKey:kCPNeededToCompletion] intValue];
                ausstehend  = ausstehend >= 0 ? ausstehend : 0;
                cell.textLabel.text = NSLocalizedString(@"Ausstehend", @"Ausstehend");
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%i %@ %i CP", ausstehend, NSLocalizedString(@"von", @"von"), [[_studiengang objectForKey:kStudiengangCP] intValue]];
                if (ausstehend > 0)
                {
                    int nochzuplanen = ausstehend - [[_studiengang objectForKey:kOpenCP] intValue];
                    if (nochzuplanen > 0)
                    {
                        cell.detailDetailTextLabel.text = [NSString stringWithFormat:@"%@ %i CP %@", NSLocalizedString(@"noch", @"noch"), nochzuplanen, NSLocalizedString(@"zu planen", @"zu planen")];
                    }
                    else
                    {
                        cell.detailDetailTextLabel.text = NSLocalizedString(@"ausreichend CP geplant", @"ausreichend CP geplant");
                    }
                }
                else
                {
                    cell.detailDetailTextLabel.text = NSLocalizedString(@"ausreichend CP erworben", @"ausreichend CP erworben");
                }
            }
            break;
        case 1: //Noten
            if (indexPath.row == 0)
            {
                cell.textLabel.text = NSLocalizedString(@"Durchschnitt", @"Durchschnitt");
                id averageMark = [_studiengang objectForKey:kAvarageMark];
                if ([averageMark floatValue] > 0.0)
                {
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [[NSString stringWithFormat:@"%.2f", [[_studiengang objectForKey:kAvarageMark] floatValue]] stringByReplacingOccurrencesOfString:@"." withString:@","]];
                    cell.detailDetailTextLabel.text = [self gradeRange:[averageMark floatValue]];
                }
                else
                {
                    cell.detailTextLabel.text = @"--";
                    cell.detailDetailTextLabel.text = @"";
                }
            }
            else if (indexPath.row == 1)
            {
                cell.textLabel.text = NSLocalizedString(@"Beste Note", @"Beste Note");
                id bestMark = [_studiengang objectForKey:kBestMark];
                if (bestMark)
                {
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [[NSString stringWithFormat:@"%.1f", [[_studiengang objectForKey:kBestMark] floatValue]] stringByReplacingOccurrencesOfString:@"." withString:@","]];
                    cell.detailDetailTextLabel.text = [self gradeRange:[bestMark floatValue]];
                }
                else
                {
                    cell.detailTextLabel.text = @"--";
                    cell.detailDetailTextLabel.text = @"";
                }
            }
            else
            {
                cell.textLabel.text = NSLocalizedString(@"Schlechteste Note", @"Schlechteste Note");
                id worstMark = [_studiengang objectForKey:kWorstMark];
                if (worstMark)
                {
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [[NSString stringWithFormat:@"%.1f", [[_studiengang objectForKey:kWorstMark] floatValue]] stringByReplacingOccurrencesOfString:@"." withString:@","]];
                    cell.detailDetailTextLabel.text = [self gradeRange:[worstMark floatValue]];
                }
                else
                {
                    cell.detailTextLabel.text = @"--";
                    cell.detailDetailTextLabel.text = @"";
                }
            }
            break;
        case 2: //Zeit
            if (indexPath.row == 0)
            {
                cell.textLabel.text = NSLocalizedString(@"Punkte/Semester", @"Punkte/Semester");
                float schnitt = [[_studiengang objectForKey:kAvarageCPPerSemester] floatValue];
                if (schnitt > 0.0)
                {
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ CP", [[[_studiengang objectForKey:kAvarageCPPerSemester] stringValue] stringByReplacingOccurrencesOfString:@"." withString:@","]];
                    if ([[_studiengang objectForKey:kCurrentSemesterIndex] intValue] == 1)
                    {
                        cell.detailDetailTextLabel.text = NSLocalizedString(@"erstes Semester", @"erstes Semester");
                    }
                    else
                    {
                        cell.detailDetailTextLabel.text = NSLocalizedString(@"erstes bis einschließlich aktuelles Semester", @"erstes bis einschließlich aktuelles Semester");
                    }
                }
                else
                {
                    cell.detailTextLabel.text = @"--";
                    cell.detailDetailTextLabel.text = @"";
                }
            }
            else
            {
                cell.textLabel.text = NSLocalizedString(@"Studiendauer", @"Studiendauer");

                float averageCP = [[_studiengang objectForKey:kAvarageCPPerSemester] floatValue];
                if (averageCP > 0.0)
                {
                    float studiendauer = [[_studiengang objectForKey:kStudiengangCP] floatValue] / averageCP;
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%i Semester", (int)ceil(studiendauer)];
                    cell.detailDetailTextLabel.text = NSLocalizedString(@"nach bisherigem Schnitt", @"nach bisherigem Schnitt");
                }
                else
                {
                    cell.detailTextLabel.text = @"--";
                    cell.detailDetailTextLabel.text = @"";
                }
            }
            break;
        default:
            break;
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    cell.opaque = YES;
    return cell;
}

//Gibt aus einer Note den Notenbereich in dem sich diese Note befindet als String zurück.
- (NSString *)gradeRange:(float)grade
{
    NSString *gradeRange;
    if (grade)
    {
        if (grade >= 1.0 && grade <= 1.24)
        {
            gradeRange = [NSString stringWithFormat:@"1,0 < %@ < 1,25", NSLocalizedString(@"Ausgezeichnet", @"Ausgezeichnet")];
        }
        else if (grade >= 1.25 && grade <= 1.54)
        {
            gradeRange = [NSString stringWithFormat:@"1,25 < %@ < 1,54", NSLocalizedString(@"Sehr gut", @"Sehr gut")];
        }
        else if (grade >= 1.55 && grade < 2.54)
        {
            gradeRange = [NSString stringWithFormat:@"1,55 < %@ < 2,54", NSLocalizedString(@"Gut", @"Gut")];
        }
        else if (grade >= 2.54 && grade < 3.54)
        {
            gradeRange = [NSString stringWithFormat:@"2,54 < %@ < 3,54", NSLocalizedString(@"Befriedigend", @"Befriedigend")];
        }
        else if (grade >= 3.54 && grade <= 4.04)
        {
            gradeRange = [NSString stringWithFormat:@"3,54 < %@ < 4,04", NSLocalizedString(@"Ausreichend", @"Ausreichend")];
        }
        else
        {
            gradeRange = [NSString stringWithFormat:@"4,05 < %@", NSLocalizedString(@"Nicht bestanden", @"Nicht bestanden")];
        }
    }
    return gradeRange;
}

#pragma mark - UITableViewDelegate

//Fügt in den TableHeader noch die Grafiken hinzu.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CGRect frame = CGRectMake(20.0, 0.0, 200.0, 40.0);

    UIView *headerView = [[UIView alloc] initWithFrame:frame];
    UIImageView *headerImageView;
    frame.size.width -= 30.0;
    frame.size.height -= 10.0;
    frame.origin.x += 25.0;
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:frame];
    headerLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:20.0];
    headerLabel.backgroundColor = [UIColor clearColor];
    switch (section)
    {
        case 0: //Creditpunkte
            headerImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"108-badge"]];
            headerLabel.text = NSLocalizedString(@"Creditpunkte", @"Creditpunkte");
            break;
        case 1: //Noten
            headerImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"85-trophy"]];
            headerLabel.text = NSLocalizedString(@"Noten", @"Noten");
            break;
        case 2: //Zeit
            headerImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"78-stopwatch"]];
            headerLabel.text = NSLocalizedString(@"Zeit", @"Zeit");
            break;
        default:
            break;
    }
    [headerView addSubview:headerLabel];
    [headerView addSubview:headerImageView];
    frame = headerImageView.frame;
    frame.origin.x += 15.0;
    headerImageView.frame = frame;
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 52.0;
}

@end


text:
'use strict';

var OpenElementStack = require('./open_element_stack'),
    Tokenizer = require('../tokenization/tokenizer'),
    HTML = require('../common/html');

//Aliases
var $ = HTML.TAG_NAMES;

function setEndLocation(element, endTagToken) {
    if (element.__location)
        element.__location.end = endTagToken.location.end;
}

//NOTE: patch open elements stack, so we can assign end location for the elements
function patchOpenElementsStack(stack, parser) {
    stack.pop = function () {
        setEndLocation(this.current, parser.currentToken);
        OpenElementStack.prototype.pop.call(this);
    };

    stack.popAllUpToHtmlElement = function () {
        for (var i = this.stackTop; i > 0; i--)
            setEndLocation(this.items[i], parser.currentToken);

        OpenElementStack.prototype.popAllUpToHtmlElement.call(this);
    };

    stack.remove = function (element) {
        setEndLocation(element, parser.currentToken);
        OpenElementStack.prototype.remove.call(this, element);
    };
}

exports.assign = function (parser) {
    //NOTE: obtain Parser proto this way to avoid module circular references
    var parserProto = Object.getPrototypeOf(parser);

    //NOTE: patch _reset method
    parser._reset = function (html, document, fragmentContext) {
        parserProto._reset.call(this, html, document, fragmentContext);

        this.attachableElementLocation = null;
        this.lastFosterParentingLocation = null;
        this.currentToken = null;

        patchOpenElementsStack(this.openElements, parser);
    };

    parser._processTokenInForeignContent = function (token) {
        this.currentToken = token;
        parserProto._processTokenInForeignContent.call(this, token);
    };

    parser._processToken = function (token) {
        this.currentToken = token;
        parserProto._processToken.call(this, token);

        //NOTE: <body> and <html> are never popped from the stack, so we need to updated
        //their end location explicitly.
        if (token.type === Tokenizer.END_TAG_TOKEN &&
            (token.tagName === $.HTML ||
             (token.tagName === $.BODY && this.openElements.hasInScope($.BODY)))) {
            for (var i = this.openElements.stackTop; i >= 0; i--) {
                var element = this.openElements.items[i];

                if (this.treeAdapter.getTagName(element) === token.tagName) {
                    setEndLocation(element, token);
                    break;
                }
            }
        }
    };

    //Doctype
    parser._setDocumentType = function (token) {
        parserProto._setDocumentType.call(this, token);

        var documentChildren = this.treeAdapter.getChildNodes(this.document),
            cnLength = documentChildren.length;

        for (var i = 0; i < cnLength; i++) {
            var node = documentChildren[i];

            if (this.treeAdapter.isDocumentTypeNode(node)) {
                node.__location = token.location;
                break;
            }
        }
    };

    //Elements
    parser._attachElementToTree = function (element) {
        //NOTE: _attachElementToTree is called from _appendElement, _insertElement and _insertTemplate methods.
        //So we will use token location stored in this methods for the element.
        element.__location = this.attachableElementLocation || null;
        this.attachableElementLocation = null;
        parserProto._attachElementToTree.call(this, element);
    };

    parser._appendElement = function (token, namespaceURI) {
        this.attachableElementLocation = token.location;
        parserProto._appendElement.call(this, token, namespaceURI);
    };

    parser._insertElement = function (token, namespaceURI) {
        this.attachableElementLocation = token.location;
        parserProto._insertElement.call(this, token, namespaceURI);
    };

    parser._insertTemplate = function (token) {
        this.attachableElementLocation = token.location;
        parserProto._insertTemplate.call(this, token);

        var tmplContent = this.treeAdapter.getChildNodes(this.openElements.current)[0];

        tmplContent.__location = null;
    };

    parser._insertFakeRootElement = function () {
        parserProto._insertFakeRootElement.call(this);
        this.openElements.current.__location = null;
    };

    //Comments
    parser._appendCommentNode = function (token, parent) {
        parserProto._appendCommentNode.call(this, token, parent);

        var children = this.treeAdapter.getChildNodes(parent),
            commentNode = children[children.length - 1];

        commentNode.__location = token.location;
    };

    //Text
    parser._findFosterParentingLocation = function () {
        //NOTE: store last foster parenting location, so we will be able to find inserted text
        //in case of foster parenting
        this.lastFosterParentingLocation = parserProto._findFosterParentingLocation.call(this);
        return this.lastFosterParentingLocation;
    };

    parser._insertCharacters = function (token) {
        parserProto._insertCharacters.call(this, token);

        var hasFosterParent = this._shouldFosterParentOnInsertion(),
            parentingLocation = this.lastFosterParentingLocation,
            parent = (hasFosterParent && parentingLocation.parent) ||
                     this.openElements.currentTmplContent ||
                     this.openElements.current,
            siblings = this.treeAdapter.getChildNodes(parent),
            textNodeIdx = hasFosterParent && parentingLocation.beforeElement ?
                          siblings.indexOf(parentingLocation.beforeElement) - 1 :
                          siblings.length - 1,
            textNode = siblings[textNodeIdx];

        //NOTE: if we have location assigned by another token, then just update end position
        if (textNode.__location)
            textNode.__location.end = token.location.end;

        else
            textNode.__location = token.location;
    };
};


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>IQKeyboardReturnKeyHandler Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1334)">

				qudianDoc

				qudian

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Properties">

		<option value="//api/name/delegate">delegate</option>

		<option value="//api/name/lastTextFieldReturnKeyType">lastTextFieldReturnKeyType</option>

	</optgroup>

	<optgroup label="Instance Methods">

		<option value="//api/name/addResponderFromView:">- addResponderFromView:</option>

		<option value="//api/name/addTextFieldView:">- addTextFieldView:</option>

		<option value="//api/name/initWithCoder:">- initWithCoder:</option>

		<option value="//api/name/initWithViewController:">- initWithViewController:</option>

		<option value="//api/name/removeResponderFromView:">- removeResponderFromView:</option>

		<option value="//api/name/removeTextFieldView:">- removeTextFieldView:</option>

	</optgroup>

</select>

IQKeyboardReturnKeyHandler Class Reference

	Inherits from
	NSObject

	Declared in
	IQKeyboardReturnKeyHandler.h
IQKeyboardReturnKeyHandler.m

Overview

Manages the return key to work like next/done in a view hierarchy.

Initializations

– initWithViewController:

Add all the textFields available in UIViewController’s view.

- (nonnull instancetype)initWithViewController:(nullable UIViewController *)controller

Discussion

Add all the textFields available in UIViewController’s view.

Declared In

IQKeyboardReturnKeyHandler.h

– initWithCoder:

Unavailable. Please use initWithViewController: or init method

- (nonnull instancetype)initWithCoder:(nullable NSCoder *)aDecoder

Discussion

Unavailable. Please use initWithViewController: or init method

Declared In

IQKeyboardReturnKeyHandler.h

Settings

  delegate

Delegate of textField/textView.

@property (nullable, nonatomic, weak) id<UITextFieldDelegate,UITextViewDelegate> delegate

Discussion

Delegate of textField/textView.

Declared In

IQKeyboardReturnKeyHandler.h

  lastTextFieldReturnKeyType

Set the last textfield return key type. Default is UIReturnKeyDefault.

@property (nonatomic, assign) UIReturnKeyType lastTextFieldReturnKeyType

Discussion

Set the last textfield return key type. Default is UIReturnKeyDefault.

Declared In

IQKeyboardReturnKeyHandler.h

Registering/Unregistering textFieldView

– addTextFieldView:

Should pass UITextField/UITextView instance. Assign textFieldView delegate to self, change it’s returnKeyType.

- (void)addTextFieldView:(nonnull UIView *)textFieldView

Parameters

						textFieldView

UITextField/UITextView object to register.

Discussion

Should pass UITextField/UITextView instance. Assign textFieldView delegate to self, change it’s returnKeyType.

Declared In

IQKeyboardReturnKeyHandler.h

– removeTextFieldView:

Should pass UITextField/UITextView instance. Restore it’s textFieldView delegate and it’s returnKeyType.

- (void)removeTextFieldView:(nonnull UIView *)textFieldView

Parameters

						textFieldView

UITextField/UITextView object to unregister.

Discussion

Should pass UITextField/UITextView instance. Restore it’s textFieldView delegate and it’s returnKeyType.

Declared In

IQKeyboardReturnKeyHandler.h

– addResponderFromView:

Add all the UITextField/UITextView responderView’s.

- (void)addResponderFromView:(nonnull UIView *)view

Parameters

						UIView

object to register all it’s responder subviews.

Discussion

Add all the UITextField/UITextView responderView’s.

Declared In

IQKeyboardReturnKeyHandler.h

– removeResponderFromView:

Remove all the UITextField/UITextView responderView’s.

- (void)removeResponderFromView:(nonnull UIView *)view

Parameters

						UIView

object to unregister all it’s responder subviews.

Discussion

Remove all the UITextField/UITextView responderView’s.

Declared In

IQKeyboardReturnKeyHandler.h

Copyright © 2016 qudian. All rights reserved. Updated: 2016-11-29

Generated by appledoc 2.2.1 (build 1334).


text:
package ir.ast

import lift.arithmetic.{PosVar, Var}

/**
 * Abstract class for the (full) reduce pattern.
 *
 * The full reduction is modeled as a special case of the parital reduction,
 * therefore, this class inherits from the AbstractPartRed class.
 *
 * An object of the reduce pattern has to be instantiated with a given
 * lambda `f`, therefore, it is not possible to have a like `Red()`.
 *
 * @param f A lambda to be applied in the partial reduction
 */
abstract class AbstractReduce(override val f: Lambda,
                              loopVar: Var)
  extends AbstractPartRed(f, loopVar)

/**
 * Concrete class for the reduce pattern.
 * No code can be generated for this pattern.
 *
 * The reduce pattern has the following high-level semantics:
 *   `Reduce(f)( id, [x,,1,,, ..., x,,n,,] ) =
 *      id f (x,,1,, f (... ( ... f x,,n,,) ...))`
 * where `f` is written in infix notation.
 *
 * The reduce pattern has the following type:
 *   `Reduce(f) : a -> [a],,i,, -> [a],,1,,`
 * where `f : (a x a) -> a`.
 *
 * We know the following algorithmic rewrite rules for the reduce pattern
 * (so far):
 *  - `Reduce(f) => Reduce(f) o PartRed(f)`
 *
 * @param f A lambda to be applied as the binary reduction operator in the
 *          reduction
 */
case class Reduce(override val f: Lambda) extends AbstractReduce(f, PosVar("")) {
  override def copy(f: Lambda): Pattern = Reduce(f)
}

object Reduce {
  def apply(f: Lambda2, init: Expr): Lambda1 = fun((x) => Reduce(f)(init, x))
}