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/typelevel/squants)
|
[Wiki](https://github.com/typelevel/squants/wiki)
|
[![Join the chat at https://gitter.im/typelevel/squants](https://badges.gitter.im/typelevel/squants.svg)](https://gitter.im/typelevel/squants?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
[![Scaladocs](https://www.javadoc.io/badge/org.typelevel/squants_2.12.svg?label=scaladoc)](https://static.javadoc.io/org.typelevel/squants_2.12/1.2.0/squants/index.html)
|
[![Build Status](https://travis-ci.org/typelevel/squants.png?branch=master)](https://travis-ci.org/typelevel/squants)

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

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

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

Build services provided by [Travis CI](https://travis-ci.com/)

NOTE - This README reflects the feature set in the branch it can be found.
For more information on feature availability of a specific version see the Release History or the README for a that version

## Installation
Repository hosting for Squants is provided by [Sonatype](https://oss.sonatype.org/).
To use Squants in your SBT project add the following dependency to your build.

    "org.typelevel"  %% "squants"  % "1.3.0"
or

    "org.typelevel"  %% "squants"  % "1.4.0-SNAPSHOT"

To use Squants in your Maven project add the following dependency

```xml
<dependency>
    <groupId>org.typelevel</groupId>
    <artifactId>squants_2.11</artifactId>
    <version>1.3.0</version>
</dependency>
```

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

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

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

## Third-party integrations

This is an incomplete list of third-party libraries that support squants:

* [PureConfig](https://github.com/melrief/pureconfig/)
* [Ciris](https://cir.is/)

If your library isn't listed here, please open a PR to add it!

## Type Safe 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:

```tut
val loadKw = 1.2
val energyMwh = 24.2
val sumKw = loadKw + energyMwh
```

This example 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:

```tut:reset
import squants.energy.{Kilowatts, Megawatts, Power}
val load1: Power = Kilowatts(12)
val load2: Power = Megawatts(0.023)
val sum = load1 + load2
sum == Kilowatts(35)
sum == Megawatts(0.035) // comparisions automatically convert scale
```

The above sample works 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:

```tut
import squants.energy.{Energy, Power, Kilowatts, KilowattHours}
val load: Power = Kilowatts(1.2)
val energy: Energy = KilowattHours(23.0)
```

Invalid operations, like adding power and energy, no longer compile:
```tut:fail
val sum = load + energy
```
By using stronger types, we catch the error earlier in the development cycle, preventing 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.

Code samples in this section assume these imports:
```tut:silent:reset
import squants.energy.{Kilowatts, Power}
import squants.time.{Hours, Days}
```

The following code demonstrates creating ratio between two quantities of the same dimension,
resulting in a dimensionless value:

```tut
val ratio = Days(1) / Hours(3)
```

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

```tut
val load = Kilowatts(1.2)
val time = Hours(2)
val energyUsed = load * time
```

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

```tut
val aveLoad: Power = energyUsed / time
```

### Unit Conversions

Code samples in this section assume these imports:
```tut:silent:reset
import scala.language.postfixOps
import squants.energy.{Gigawatts, Kilowatts, Power, Megawatts}
import squants.mass.MassConversions._
import squants.mass.{Kilograms, Pounds}
import squants.thermal.TemperatureConversions._
import squants.thermal.Fahrenheit
```

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

```tut
val loadA: Power = Kilowatts(1200)
val loadB: Power = Megawatts(1200)
```

Since Squants properly equates values of a like dimension, regardless of the unit,
there is usually 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.

```tut
val loadA = Kilowatts(1200)
val loadB = loadA in Megawatts
val loadC = loadA in Gigawatts
```

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

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

```tut
val load: Power = Kilowatts(1200)
val kw: Double = load to Kilowatts
val mw: Double = load to Megawatts
val gw: Double = load to Gigawatts
```

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

```tut
val kw: Double = load toKilowatts
val mw: Double = load toMegawatts
val gw: Double = load toGigawatts
```

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 be 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:

```tut
val kw: String = load toString Kilowatts
val mw: String = load toString Megawatts
val gw: String = load toString Gigawatts
```

Creating `Tuple2[Double, String]` that includes a numeric value and unit symbol:

```tut
val load: Power = Kilowatts(1200)
val kw = load toTuple
val mw = load toTuple Megawatts
val gw = load toTuple Gigawatts
```

This can be useful for passing properly scaled quantities to other processes
that do not use Squants, or require use of more basic types (Double, String)

Simple console based conversions (using DSL described below)

```tut
1.kilograms to Pounds
kilogram / pound

2.1.pounds to Kilograms
2.1.pounds / kilogram

100.C to Fahrenheit
```

### Mapping over Quantity values
Apply a `Double => Double` operation to the underlying value of a quantity, while preserving its type and unit.

```tut:reset
import squants.energy.Kilowatts

val load = Kilowatts(2.0)
val newLoad = load.map(v => v * 2 + 10)
```

The `q.map(f)` method effectively expands to `q.unit(f(q.to(q.unit))`

NOTE - For Money objects, use the `mapAmount` method as this will retain the BigDecimal precision used there.

### Approximations
Create an implicit Quantity value to be used as a tolerance in approximations.
Then use the `approx` method (or `=~`, `~=`, `≈` operators) like you would use the `equals` method (`==` operator).

```tut:reset
import squants.energy.{Kilowatts, Watts}

val load = Kilowatts(2.0)
val reading = Kilowatts(1.9999)
```

Calls to `approx` (and its symbolic aliases) use an implicit tolerance:

```tut
implicit val tolerance = Watts(.1)
load =~ reading
load ≈ reading
load approx reading
```

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 case classes that takes a variable parameter list of like quantities
representing a set of point coordinates in Cartesian space.
The SVector object is a factory for creating DoubleVectors and QuantityVectors.
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)

```tut:reset
import squants.{QuantityVector, SVector}
import squants.space.{Kilometers, Length}
import squants.space.LengthConversions._

val vector: QuantityVector[Length] = SVector(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[Length] = SVector(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
```

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

```tut:silent
import squants.DoubleVector

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

#### Dimensional conversions within Vector operations.

Currently dimensional conversions are supported by using the slightly verbose, but flexible map method.

```tut:reset
import squants.{DoubleVector, QuantityVector}
import squants.motion.Velocity
import squants.space.{Area, Kilometers, Length, Meters}
import squants.time.Seconds

val vectorLength = QuantityVector(Kilometers(1.2), Kilometers(4.3), Kilometers(2.3))
val vectorArea = vectorLength.map[Area](_ * Kilometers(2))      // QuantityVector(2.4 km², 8.6 km², 4.6 km²)
val vectorVelocity = vectorLength.map[Velocity](_ / Seconds(1)) // QuantityVector(1200.0 m/s, 4300.0 m/s, 2300.0 m/s)

val vectorDouble = DoubleVector(1.2, 4.3, 2.3)
val vectorLength = vectorDouble.map[Length](Kilometers(_))      // QuantityVector(1.2 km, 4.3 km, 2.3 km)
```

Convert QuantityVectors to specific units using the `to` or `in` method - much like Quantities.

```tut
val vectorLength = QuantityVector(Kilometers(1.2), Kilometers(4.3), Kilometers(2.3))
val vectorMetersNum = vectorLength.to(Meters)   // DoubleVector(1200.0, 4300.0, 2300.0)
val vectorMeters = vectorLength.in(Meters)      // QuantityVector(1200.0 m, 4300.0 m, 2300.0 m)
```

## Market Package
Market Types are similar but not quite the same as other quantities in the library.
The primary type, Money, is a Dimensional 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 Currency units.
Like other quantities, the Unit of Measures are used to create Money values.

```tut:reset
import squants.market.{BTC, JPY, USD, XAU}

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

### 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*

Assuming these imports:
```tut:reset:silent
import squants.{Dozen, Each}
import squants.energy.MegawattHours
import squants.market.USD
import squants.space.UsGallons
```

You can compute the following:
```tut
val threeForADollar = USD(1) / Each(3)
val energyPrice = USD(102.20) / MegawattHours(1)
val milkPrice = USD(4) / UsGallons(1)

val costForABunch = threeForADollar * Dozen(10)
val energyCost = energyPrice * MegawattHours(4)
val milkQuota = USD(20) / milkPrice
```

Conversions to Strings
```tut
val money = USD(123.456)
val s = money.toString  // returns full precision amount with currency code
val s = money.toFormattedString // returns currency symbol and amount rounded based on currency rules
```

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

```tut:reset
import squants.market.{CurrencyExchangeRate, JPY, Money, USD}

// create an exchange rate
val rate1 = CurrencyExchangeRate(USD(1), JPY(100))
// OR
val rate2 = USD / JPY(100)
// OR
val rate3 = JPY(100) -> USD(1)
// OR
val rate4 = 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:

```tut
val dollarAmount: Money = rate1.convert(someYen)
val yenAmount: Money = rate1.convert(someBucks)
```

Or just use the `*` operator in either direction (money * rate, or rate * money):
```tut`
val dollarAmount2: Money = rate1 * someYen
val yenAmount2: Money = someBucks * rate1
```

### 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.

Assuming these imports:
```tut:silent
import squants.energy.MegawattHours
import squants.market.{CAD, JPY, MXN, USD}
import squants.market.defaultMoneyContext
```

You can compute:
```tut
val exchangeRates = List(USD / CAD(1.05), USD / MXN(12.50), USD / JPY(100))
implicit val moneyContext = defaultMoneyContext withExchangeRates exchangeRates

val energyPrice = USD(102.20) / MegawattHours(1)
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
A `QuantityRange` is used to represent a range of Quantity values between an upper and lower bound:

```tut:reset:silent
import squants.QuantityRange
import squants.energy.{Kilowatts, Megawatts, Power}
```
```tut:book
val load1: Power = Kilowatts(1000)
val load2: Power = Kilowatts(5000)
val range: QuantityRange[Power] = QuantityRange(load1, load2)
```

### Inclusivity and Exclusivitiy

The `QuantityRange` constructor requires that `upper` is strictly greater than `lower`:

```tut:book
import squants.space.LengthConversions._

// this will work b/c upper > lower
QuantityRange(1.km, 5.km)
```

This will fail because `lower` = `upper`:

```tut:fail
QuantityRange(1.km, 1.km)
```

`QuantityRange` contains two functions that check if an element is part of the range, `contains` and `includes`.
These differ in how they treat the range's upper bound: `contains()` _excludes_ it but `includes()` _includes_ it.

```tut
val distances = QuantityRange(1.km, 5.km)
distances.contains(5.km) // this is false b/c contains() doesn't include the upper range
distances.includes(5.km) // this is true b/c includes() does include the upper range
```

### QuantityRange transformation

The multiplication and division operators create a `Seq` of ranges from the original.

For example:

Create a Seq of 10 sequential ranges starting with the original and each the same size as the original:
```tut:book
val rs1 = range * 10
```
Create a Seq of 10 sequential ranges each 1/10th of the original size:

```tut:book
val rs2 = range / 10
```

Create a Seq of 10 sequential ranges each with a size of 400 kilowatts:
```tut:book
val rs3 = range / Kilowatts(400)
```

### QuantityRange operations

`QuantityRange` supports foreach, map, and foldLeft/foldRight. These vary slightly from the versions
in the Scala standard library in that they take a divisior as the first parameter. The examples below
illustrate their use.

Subdivide range into 1-Megawatt "slices", and foreach over each of slices:
```tut:book
range.foreach(Megawatts(1)) { r => println(s"lower = ${r.lower}, upper = ${r.upper}") }
```

Subdivide range into 10 slices and map over each slice:
```tut:book
range.map(10) { r => r.upper }
```

Subdivide range into 10 slices and fold over them, using 0 Megawatts as a starting value:
```tut:book
range.foldLeft(10, Megawatts(0)) { (z, r) => z + r.upper }
```

NOTE - Because these implementations of foreach, map and fold* take a parameter (the divisor), these methods
are not directly compatible with Scala's for comprehensions.
To use in a for comprehension, apply the * or / operators as described above to create a Seq from the Range.

```scala
for {
    interval <- (0.seconds to 1.seconds) * 60  // 60 time ranges, 0s to 1s, 1s to 2s, ...., 59s to 60s
    ...
} yield ...
```

## 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.

Code samples in this section assume these imports
```tut:silent:reset
import squants.energy.{Kilowatts, MegawattHours, Power}
import squants.market.{Price, USD}
import squants.time.Hours
```

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

```tut
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):

```tut:silent
import scala.language.postfixOps
import squants.energy.EnergyConversions._
import squants.energy.PowerConversions._
import squants.information.InformationConversions._
import squants.market.MoneyConversions._
import squants.space.LengthConversions._
import squants.time.TimeConversions._
```
```tut
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:

```tut
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:

```tut
val load = Power("40 MW")
```

Create Quantities using Tuples:

```tut
val load = Power((40.5, "MW"))
```

Use single unit values to simplify expressions:

```tut
// 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 Doubles, Longs and BigDecimals on the left side of multiply and divide operations:

```tut
val load = 10.22 * 4.MW
val driveArrayCapacity = 12 * 600.gb
val freq = 60 / second
val freq2 = BigDecimal(36000000) / hour
```

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

```tut:silent
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:

```tut:reset
import squants.mass.{Grams, Kilograms}
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 throw 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:

```tut:reset:silent
import squants.market.defaultMoneyContext
import squants.market.MoneyConversions._
import squants.market.USD
implicit val moneyContext = defaultMoneyContext
```

```tut
implicit val moneyNum = new MoneyNumeric()

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

## Unit groups

Squants provides an experimental API for grouping related `UnitOfMeasure` values together.
This are called `UnitGroup`s. Squants provides `UnitGroup` implementations for the SI, the US Customary system, and various other systems. End-users can create their own ad-hoc `UnitGroup`s for `UnitOfMeasure`s in a related dimension.

The `UnitGroup` trait defines two public fields: `units`, a `Set[UnitOfMeasure]`, and `sortedUnits`, which contains `units` sorted in ascending order.

### SI UnitGroups

Almost every `Dimension` in Squants has SI Units (with the exception of `Information`
and `Money`). To avoid boilerplate, Squants generates `UnitGroup`s for SI using implicits.

There are two `UnitGroup`s provided for SI: "strict" and "expanded." Strict only includes SI
UnitOfMeasure defined in the SI; "expanded" includes [non-SI units that are commonly used in](http://www.bipm.org/en/publications/si-brochure/table6.html)
SI, such as litre, hectare, hour, minute, etc). See the linked document for a detailed list.

To summon the strict SI `UnitGroup` for `Length`, you would use this code:

```tut:reset:book
import squants.space.Length
import squants.experimental.unitgroups.ImplicitDimensions.space._
import squants.experimental.unitgroups.UnitGroup
import squants.experimental.unitgroups.si.strict.implicits._
val siLengths: UnitGroup[Length] = implicitly[UnitGroup[Length]]
```

To print out units and their conversion factors to the primary SI unit, you could use this code:

```tut:book
import squants.{Quantity, UnitOfMeasure}

def mkConversionFactor[A <: Quantity[A]](uom: UnitOfMeasure[A]): Double = {
  val one = uom(1)
  one.to(one.dimension.siUnit)
}

def mkTuple[A <: Quantity[A]](uom: UnitOfMeasure[A]): (String, Double) = {
  (uom.symbol, mkConversionFactor(uom))
}

siLengths.sortedUnits.toList.map(mkTuple).foreach(println)
```

Note that `UnitGroup`'s `sortedUnits` field is a `SortedSet`, so before mapping over it,
you will probably want to convert it to a List, otherwise the output may be resorted.

### Non-SI UnitGroups

Other `UnitGroup` definitions don't use implicits. For example, `squants.experimental.unitgroups.uscustomary.space.UsCustomaryLiquidVolumes` or `squants.experimental.unitgroups.misc.TroyMasses` can be imported and used directly.

### Creating an ad-hoc UnitGroup

To create an ad-hoc `UnitGroup` just implement the trait. For example, to make a US cooking measure `UnitGroup`:

```tut:book
import squants.{Quantity, Dimension}
import squants.space._
import squants.experimental.unitgroups.UnitGroup

val usCookingUnitGroup = new UnitGroup[Volume] {
  // units don't have to be specified in-order.
  val units: Set[UnitOfMeasure[Volume]] = Set(UsPints, UsGallons, Teaspoons, Tablespoons, UsQuarts, FluidOunces)
}

// squants automatically sorts units
usCookingUnitGroup.sortedUnits.foreach(println)
```

The `UnitGroup` values provided with Squants are only samples and aren't intended to be exhaustive.
We encourage users to make their own `UnitGroup` defintitions and submit them as PRs if they're generally
applicable.

## Formatters

Squants provides an experimental API for formatting Quantities in the "best unit." For example,
convert Inches(12) to Feet(1). This is useful for producing human-friendly output.

To use a formatter, you must implement the `squants.formatters.Formatter` trait:

```tut:silent
trait Formatter[A <: Quantity[A]] {
  def inBestUnit(quantity: Quantity[A]): A
}
```

### Default Formatter implementation

There is a default formatter implementation in `squants.experimental.formatter.DefaultFormatter`. This builds on the `UnitGroup`
API discussed above to choose the best `UnitOfMeasure` for a `Quantity`. The `DefaultFormatter` algorithm will probably
work for most use-cases, but users can create their own `Formatters` if they have custom needs.

To use `DefaultFormatter` import it, and a unit group:

```tut:silent
import squants.experimental.formatter.DefaultFormatter
import squants.experimental.unitgroups.misc.AstronomicalLengthUnitGroup
```

Then create the formatter by passing in a unit group:
```tut:book
val astroFormatter = new DefaultFormatter(AstronomicalLengthUnitGroup)
```

Now, we create some values using human-unfriendly numbers:

```tut:book
import squants.space.LengthConversions._
val earthToJupiter = 588000000.km
val earthToVoyager1 = 2.06e10.km
val earthToAlphaCentauri = 4.1315e+13.km
```

And format them into appropriate units (AUs and Parsecs, in this case):
```tut:book
astroFormatter.inBestUnit(earthToJupiter)
astroFormatter.inBestUnit(earthToVoyager1)
astroFormatter.inBestUnit(earthToAlphaCentauri)
```

### Implicit formatters

There is a nicer syntax for formatters available via implicits.
This lets you write expressions such as `12.inches.inBestUnit`. This syntax is added per-`Dimension`.

To use this syntax, first import `squants.experimental.formatter.syntax._`.
Then, for each `Dimension` you wish to use, place a Formatter for the Dimension in implicit scope. In this example,
we're adding support for `Length`.

```tut:reset:silent
import squants.experimental.formatter.DefaultFormatter
import squants.experimental.formatter.syntax._
import squants.mass.MassConversions._
import squants.space.Length
import squants.space.LengthConversions._
import squants.experimental.unitgroups.misc.AstronomicalLengthUnitGroup
```

```tut:book
implicit val astroFormatter = new DefaultFormatter(AstronomicalLengthUnitGroup)

val earthToJupiter = 588000000.km
val earthToVoyager1 = 2.06e10.km
val earthToAlphaCentauri = 4.1315e+13.km

earthToJupiter.inBestUnit
earthToVoyager1.inBestUnit
earthToAlphaCentauri.inBestUnit
```

This example won't compile because there is no `Formatter[Mass]` in implicit scope:

```tut:fail
5000.grams.inBestUnit
```

### SI Formatters and implicit syntax

When using SI units, and the default formatter algorithm, you don't have to declare a `Formatter` and place it in
implicit scope. The compiler can do that for you. This creates a very human-friendly API by using the appropriate
imports.

First, import the SI unit groups and their implicits:
```tut:reset:silent
import squants.experimental.unitgroups.ImplicitDimensions.space._
import squants.experimental.unitgroups.si.strict.implicits._
```

Next, import the formatter syntax described above:

```tut:silent
import squants.experimental.formatter.syntax._
```

Finally, add imports for implicitly deriving formatters:
```tut
import squants.experimental.formatter.implicits._
```

Now we can create quantities and format them by calling `.inBestUnit` directly:

```tut:silent
import squants.space.LengthConversions._
```

```tut:book
5.cm.inBestUnit
500.cm.inBestUnit
3000.meters.inBestUnit
```

## 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 54 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 257 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 257 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.

Using these imports:
```tut:reset:silent
import squants.energy.Kilowatts
import squants.motion.{Acceleration, Velocity}
import squants.space.{Kilometers, Length}
import squants.space.LengthConversions._
import squants.time.{Hours, Seconds, Time}
import squants.time.TimeConversions._
```

You can code the following:
```tut
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
```

Power is the 1st Time Derivative of Energy, PowerRamp is the 2nd.
```tut
val power = Kilowatts(100)
val time: Time = Hours(2)
val energy = power * time
val ramp = Kilowatts(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.

This code samples in this section use these imports:
```tut:reset:silent
import squants.energy.Energy
import squants.energy.EnergyConversions._
import squants.energy.PowerConversions._
import squants.market.{Money, Price}
import squants.market.MoneyConversions._
import squants.market.defaultMoneyContext
import squants.mass.{Density, Mass}
import squants.mass.MassConversions._
import squants.motion.{Acceleration, Velocity, VolumeFlow}
import squants.motion.AccelerationConversions._
import squants.space.LengthConversions._
import squants.space.VolumeConversions._
import squants.time.Time
import squants.time.TimeConversions._
```

```tut
implicit val moneyContext = defaultMoneyContext
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: VolumeFlow = 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.

Code samples in this section use these imports:
```tut:silent:reset
import scala.language.postfixOps

import squants.energy.{Energy, Power, PowerRamp}
import squants.energy.EnergyConversions._
import squants.energy.PowerConversions._
import squants.energy.PowerRampConversions._
import squants.market.Price
import squants.market.MoneyConversions._
import squants.time.Time
import squants.time.TimeConversions._
```

This is OK ...

```tut:silent
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)
```

... but this is much better

```tut:silent
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)
```

### 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
import squants.radio.{Irradiance, WattsPerSquareMeter}
import squants.thermal.{Celsius, Temperature}

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))
* Derek Morr ([derekmorr](https://github.com/derekmorr))
* Michael Korbakov ([rmihael](https://github.com/rmihael))
* Florian Nussberger ([fnussber](https://github.com/fnussber))
* Ajay Chandran ([ajaychandran](https://github.com/ajaychandran))
* Gia Bảo ([giabao](https://github.com/giabao))
* Josh Lemer ([joshlemer](https://github.com/joshlemer))
* Dave DeCarpio ([DaveDeCaprio](https://github.com/DaveDeCaprio))
* Carlos Quiroz ([cquiroz](https://github.com/cquiroz))
* Szabolcs Berecz ([khernyo](https://github.com/khernyo))
* Matt Hicks ([darkfrog26](https://github.com/darkfrog26))
* golem131 ([golem131](https://github.com/golem131))
* Ian O'Hara ([ianohara](https://github.com/ianohara))
* Shadaj Laddad ([shadaj](https://github.com/shadaj))
* Ian McIntosh ([cranst0n](https://github.com/cranst0n))
* Doug Hurst ([robotsnowfall](https://github.com/robotsnowfall))
* Philip Axelrod ([Paxelord](https://github.com/paxelord))

## Code of Conduct

Squants is a [Typelevel](http://typelevel.org/) Incubator Project and, as such, supports the [Typelevel Code of Conduct](http://typelevel.org/conduct).

## 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.

# Release procedure

Making a release requires permission to publish to sonatype, and a properly setup [signing key](http://www.scala-sbt.org/sbt-pgp/usage.html):

To make a release do the following:

* Ensure the version is not set to `SNAPSHOT`

* Build the README using tut

```
  sbt tut
```

* Publish a cross-version signed package (no cross-version available for Scala Native)
```
  sbt +squantsJVM/publishSigned
  sbt +squantsJS/publishSigned
  sbt squantsNative/publishSigned
```

* Then make a release (Note: after this step the release cannot be replaced)
```
  sbt sonatypeRelease
```


text:
package ar_ubin.beacon_detector;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

public class BeaconScanner extends BeaconBluetoothService implements ServiceConnection
{
    private final String TAG = BeaconScanner.class.getSimpleName();

    private BeaconService mService;
    private boolean mIsBound;
    private BeaconNotifier mBeaconCallback;

    public BeaconScanner( Context context, BeaconNotifier beaconCallback ) {
        final Intent intent = new Intent( context, BeaconBluetoothService.class );
        mIsBound = context.getApplicationContext().bindService( intent, this, Service.BIND_AUTO_CREATE );
        this.mBeaconCallback = beaconCallback;
    }

    public void startScanning() {
        super.startOneScan();
    }

    public void destroyService() {
        if( mIsBound ) {
            this.mService.unregisterCallback();
            this.mService.stopService();
        }
    }

    @Override
    public void onServiceConnected( ComponentName name, IBinder iBinderService ) {
        this.mService = ( (BeaconBluetoothService.LocalBinder) iBinderService ).getService();
        this.mService.registerCallback( mBeaconCallback );
        this.mService.startService();
        if( BeaconConfig.DEBUG ) {
            Log.d( TAG, "Service connected" );
        }
    }

    @Override
    public void onServiceDisconnected( ComponentName name ) {
        if( this.mService != null ) {
            this.mService.unregisterCallback();
            this.mService.stopService();
        }
        if( BeaconConfig.DEBUG ) {
            Log.d( TAG, "Service disconnected" );
        }
    }

    public void setDebugLogging( boolean flag ) {
        BeaconConfig.DEBUG = flag;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package li.strolch.model.timedstate;

import li.strolch.model.StrolchValueType;
import li.strolch.model.timevalue.impl.BooleanValue;
import li.strolch.model.visitor.StrolchElementVisitor;

/**
 * @author Robert von Burg <eitch@eitchnet.ch>
 */
public class BooleanTimedState extends AbstractStrolchTimedState<BooleanValue> {

	public BooleanTimedState() {
		super();
	}

	public BooleanTimedState(String id, String name) {
		super(id, name);
	}

	@Override
	public void setStateFromStringAt(Long time, String value) {
		assertNotReadonly();
		getTimeEvolution().setValueAt(time, new BooleanValue(value));
	}

	@Override
	public String getType() {
		return StrolchValueType.BOOLEAN.getType();
	}

	@Override
	public StrolchValueType getValueType() {
		return StrolchValueType.BOOLEAN;
	}

	@Override
	public <U> U accept(StrolchElementVisitor<U> visitor) {
		return visitor.visitBooleanState(this);
	}

	@Override
	public BooleanTimedState getClone() {
		BooleanTimedState clone = new BooleanTimedState();
		fillClone(clone);
		return clone;
	}
}


text:
/**
 * @author Intel, Salikh Zakirov
 */
#ifndef _SLOT_H_
#define _SLOT_H_

/**
 * @file
 * Define the Slot structure to read the object fields of reference type.
 *
 * This data layout is statically shared between all VM components.
 */

#include "open/gc.h"        // for the declaration of gc_heap_base_address()
#include "open/vm_util.h"   // VM_Global_State
#include "environment.h"    // Global_Env

// (this file is based on gc_v4/src/compressed_references.h)
//
// The Slot data structure represents a pointer to a heap location that contains
// a reference field.  It is packaged this way because the heap location may
// contain either a raw pointer or a compressed pointer, depending on command line
// options.
//
// Code originally of the form:
//     ManagedObject **p_slot = foo ;
//     ... *p_slot ...
// can be expressed as:
//     Slot p_slot(foo);
//     ... p_slot.dereference() ...

class Slot {
private:
    union {
        void **raw;
        U_32 *compressed;
        void *value;
    } content;

    static void* heap_base;
    static void* heap_ceiling;

public:
    Slot(void *v) {
        set_address(v);
    }

    static void init(void* base, void* ceiling)
    {
        heap_base = base;
        heap_ceiling = ceiling;
    }

    // Sets the raw value of the slot.
    void *set_address(void *v) {
        content.value = v;
        return v;
    }

    // Returns the raw pointer value.
    void *get_address() { return content.value; }

    // Dereferences the slot and converts it to a raw object pointer.
    void *dereference() {
        REFS_RUNTIME_SWITCH_IF
#ifdef REFS_RUNTIME_OR_COMPRESSED
            assert(content.compressed != NULL);
            return (void*)((UDATA)*content.compressed + (UDATA)heap_base);
#endif // REFS_RUNTIME_OR_COMPRESSED
        REFS_RUNTIME_SWITCH_ELSE
#ifdef REFS_RUNTIME_OR_UNCOMPRESSED
            assert(content.raw != NULL);
            return *content.raw;
#endif // REFS_RUNTIME_OR_UNCOMPRESSED
        REFS_RUNTIME_SWITCH_ENDIF
    }

    // Writes a new object reference into the slot.
    void write(void *obj) {
        REFS_RUNTIME_SWITCH_IF
#ifdef REFS_RUNTIME_OR_COMPRESSED
            if (obj != NULL) {
                *content.compressed = (U_32) ((UDATA)obj - (UDATA)heap_base);
            } else {
                *content.compressed = 0;
            }
#endif // REFS_RUNTIME_OR_COMPRESSED
        REFS_RUNTIME_SWITCH_ELSE
#ifdef REFS_RUNTIME_OR_UNCOMPRESSED
            *content.raw = obj;
#endif // REFS_RUNTIME_OR_UNCOMPRESSED
        REFS_RUNTIME_SWITCH_ENDIF
    }

    // Returns true if the slot points to a null reference.
    bool is_null() {
        REFS_RUNTIME_SWITCH_IF
#ifdef REFS_RUNTIME_OR_COMPRESSED
            assert(content.compressed != NULL);
            return (*content.compressed == 0);
#endif // REFS_RUNTIME_OR_COMPRESSED
        REFS_RUNTIME_SWITCH_ELSE
#ifdef REFS_RUNTIME_OR_UNCOMPRESSED
            assert(content.raw != NULL);
            return (*content.raw == NULL);
#endif // REFS_RUNTIME_OR_UNCOMPRESSED
        REFS_RUNTIME_SWITCH_ENDIF
    }

    // Returns the raw value of a managed null, which may be different
    // depending on whether compressed references are used.
    static void *managed_null() {
        return VM_Global_State::loader_env->managed_null;
    }

};

#endif // _SLOT_H_


text:
var gulp = require('gulp'),
    del = require('del');

gulp.task('clean', function(cb) {
  del(['./static/*', '!./static/.git', '!./static/.gitignore'], cb)
});

gulp.task('clean-partials', function(cb) {
  del([
    './static/components',
    './static/templates'
  ], cb)
});


text:
@echo off

set /p input_page=input program name :

if "%c%"=="notepad" notepad
if "%c%"=="calc" calc

if "%c%"== "google" explorer "http://www.google.com"

pause > nul


text:
import Queue
import threading
import sys, time
import urllib2
import json
import framework
from moniItems import mon
from daemon import Daemon

class MyDaemon(Daemon):
    def run(self):
        print 'start'
        framework.startTh()
        print 'stop2'

if __name__ == "__main__":
    daemon = MyDaemon()
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)


text:
<cordova-dialog id="exec-dialog" caption="ハンドルされない exec 呼び出し" data-loc-id="f7283850">
    <cordova-group>

次の exec 呼び出しのハンドラーはありません。

service.action(arguments)

以下に戻り値を入力してこの関数への呼び出しをシミュレーションし、この値が成功または失敗のいずれを表すかを選択してください。この関数への今後のすべての呼び出しでこの値が返されるのが望ましい場合、'保持' のオプションを選択してください。

    </cordova-group>
    <cordova-group>
        <textarea id="exec-response" rows="10"></textarea>

値は有効な JSON でなければならない (error)

    </cordova-group>
    <cordova-panel-row>
        <cordova-checkbox id="exec-persist" data-loc-id="bce2c943">保持</cordova-checkbox>
        <cordova-group>
            <cordova-button id="exec-success" data-loc-id="17ccfb90">成功</cordova-button>
            <cordova-button id="exec-failure" data-loc-id="5c16961d">失敗</cordova-button>
        </cordova-group>
    </cordova-panel-row>
</cordova-dialog>


text:
<?php

namespace VU\BlogBundle\Controller;

use FOS\RestBundle\Controller\Annotations\View;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\Security\Core\Util\SecureRandom;

class UserRestController extends Controller
{
    public function getUserAction($id){
        $user = $this->getDoctrine()->getRepository('VUBlogBundle:User')->findOneById($id);
        if(!is_object($user)){
          throw $this->createNotFoundException();
        }
        return $user;
    }

    public function getUsersAction(){
        $users = $this->getDoctrine()->getRepository('VUBlogBundle:User')->findAll();
        if(!$users){
          throw $this->createNotFoundException();
        }
        return $users;
    }

    public function postUsersAction(Request $request){
        $user = new \VU\BlogBundle\Entity\User();
        $user->setEmail($request->get( 'email' ))
            ->setName($request->get( 'name' ))
            ->setLastName($request->get( 'last_name' ))
            ->setRegDate(new \DateTime('now'))
            ->setIsActive(false)
            ->setAccessLevel(false);

        //generate random password
        $generator = new SecureRandom();
        $user->setPassword(password_hash($generator->nextBytes(8), PASSWORD_BCRYPT));

        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();

        if(!is_object($user)){
          throw $this->createNotFoundException();
        }
        return $user;
    }

    public function deleteUsersAction($id){
        $user = $this->getDoctrine()->getRepository('VUBlogBundle:User')->findOneById($id);
        if(!is_object($user)){
          throw $this->createNotFoundException();
        }

        $em = $this->getDoctrine()->getManager();
        $em->remove($user);
        $em->flush();

        return;
    }

    public function putUserAction($id, Request $request){
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('VUBlogBundle:User')->findOneById($id);

        if(!is_object($user)){
          throw $this->createNotFoundException();
        }

        $user->setName($request->get( 'name' ))
            ->setLastName($request->get( 'last_name' ));

        $em->flush();

        return $user;
    }

}


text:
package eu.davidea.samples.flexibleadapter.items;

import android.animation.Animator;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import eu.davidea.flexibleadapter.FlexibleAdapter;
import eu.davidea.flexibleadapter.Payload;
import eu.davidea.flexibleadapter.helpers.AnimatorHelper;
import eu.davidea.flexibleadapter.items.AbstractFlexibleItem;
import eu.davidea.samples.flexibleadapter.R;
import eu.davidea.samples.flexibleadapter.items.ProgressItem.ProgressViewHolder;
import eu.davidea.viewholders.FlexibleViewHolder;

/**
 * @author Davide Steduto
 * @since 22/04/2016
 */
public class ProgressItem extends AbstractFlexibleItem<ProgressViewHolder> {

	private StatusEnum status = StatusEnum.MORE_TO_LOAD;

	@Override
	public boolean equals(Object o) {
		return this == o;//The default implementation
	}

	public StatusEnum getStatus() {
		return status;
	}

	public void setStatus(StatusEnum status) {
		this.status = status;
	}

	@Override
	public int getLayoutRes() {
		return R.layout.progress_item;
	}

	@Override
	public ProgressViewHolder createViewHolder(FlexibleAdapter adapter, LayoutInflater inflater, ViewGroup parent) {
		return new ProgressViewHolder(inflater.inflate(getLayoutRes(), parent, false), adapter);
	}

	@Override
	public void bindViewHolder(FlexibleAdapter adapter, ProgressViewHolder holder,
							   int position, List payloads) {

		Context context = holder.itemView.getContext();
		holder.progressBar.setVisibility(View.GONE);
		holder.progressMessage.setVisibility(View.VISIBLE);

		if (!adapter.isEndlessScrollEnabled()) {
			setStatus(StatusEnum.DISABLE_ENDLESS);
		} else if (payloads.contains(Payload.NO_MORE_LOAD)) {
			setStatus(StatusEnum.NO_MORE_LOAD);
		}

		switch (this.status) {
		case NO_MORE_LOAD:
			holder.progressMessage.setText(
					context.getString(R.string.no_more_load_retry));
			// Reset to default status for next binding
			setStatus(StatusEnum.MORE_TO_LOAD);
			break;
		case DISABLE_ENDLESS:
			holder.progressMessage.setText(context.getString(R.string.endless_disabled));
			break;
		case ON_CANCEL:
			holder.progressMessage.setText(context.getString(R.string.endless_cancel));
			// Reset to default status for next binding
			setStatus(StatusEnum.MORE_TO_LOAD);
			break;
		case ON_ERROR:
			holder.progressMessage.setText(context.getString(R.string.endless_error));
			// Reset to default status for next binding
			setStatus(StatusEnum.MORE_TO_LOAD);
			break;
		default:
			holder.progressBar.setVisibility(View.VISIBLE);
			holder.progressMessage.setVisibility(View.GONE);
			break;
		}
	}

	static class ProgressViewHolder extends FlexibleViewHolder {

		@BindView(R.id.progress_bar)
		ProgressBar progressBar;
		@BindView(R.id.progress_message)
		TextView progressMessage;

		ProgressViewHolder(View view, FlexibleAdapter adapter) {
			super(view, adapter);
			ButterKnife.bind(this, view);
		}
		@Override
		public void scrollAnimators(@NonNull List<Animator> animators, int position, boolean isForward) {
			AnimatorHelper.scaleAnimator(animators, itemView, 0f);
		}
	}

	public enum StatusEnum {
		MORE_TO_LOAD, //Default = should have an empty Payload
		DISABLE_ENDLESS, //Endless is disabled because user has set limits
		NO_MORE_LOAD, //Non-empty Payload = Payload.NO_MORE_LOAD
		ON_CANCEL,
		ON_ERROR
	}

}


text:
sudo yum install gstreamer-plugins-good.i686-0.10.23 -y
sudo yum install gstreamer-plugins-good-debuginfo.i686-0.10.23 -y
sudo yum install gstreamer-plugins-good-devel.i686-0.10.23 -y


text:
export default {
  path: '/music/libraries/:artistsLibrary/:artistName',
  name: 'artist',
  getComponent() {
    return Promise.all([
      import('./containers/ArtistContainer'),
      import('./modules/artist'),
    ])
  }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager;

namespace Azure.ResourceManager.Network.Models
{
    public partial class ApplicationGatewaySslPredefinedPolicy : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            writer.WritePropertyName("id");
            writer.WriteStringValue(Id);
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsCollectionDefined(CipherSuites))
            {
                writer.WritePropertyName("cipherSuites");
                writer.WriteStartArray();
                foreach (var item in CipherSuites)
                {
                    writer.WriteStringValue(item.ToString());
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(MinProtocolVersion))
            {
                writer.WritePropertyName("minProtocolVersion");
                writer.WriteStringValue(MinProtocolVersion.Value.ToString());
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static ApplicationGatewaySslPredefinedPolicy DeserializeApplicationGatewaySslPredefinedPolicy(JsonElement element)
        {
            Optional<string> name = default;
            ResourceIdentifier id = default;
            Optional<IList<ApplicationGatewaySslCipherSuite>> cipherSuites = default;
            Optional<ApplicationGatewaySslProtocol> minProtocolVersion = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("cipherSuites"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<ApplicationGatewaySslCipherSuite> array = new List<ApplicationGatewaySslCipherSuite>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(new ApplicationGatewaySslCipherSuite(item.GetString()));
                            }
                            cipherSuites = array;
                            continue;
                        }
                        if (property0.NameEquals("minProtocolVersion"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            minProtocolVersion = new ApplicationGatewaySslProtocol(property0.Value.GetString());
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new ApplicationGatewaySslPredefinedPolicy(id, name.Value, Optional.ToList(cipherSuites), Optional.ToNullable(minProtocolVersion));
        }
    }
}


text:
package imaging

import (
	"image"
	"math"
)

type indexWeight struct {
	index  int
	weight float64
}

func precomputeWeights(dstSize, srcSize int, filter ResampleFilter) [][]indexWeight {
	du := float64(srcSize) / float64(dstSize)
	scale := du
	if scale < 1.0 {
		scale = 1.0
	}
	ru := math.Ceil(scale * filter.Support)

	out := make([][]indexWeight, dstSize)
	tmp := make([]indexWeight, 0, dstSize*int(ru+2)*2)

	for v := 0; v < dstSize; v++ {
		fu := (float64(v)+0.5)*du - 0.5

		begin := int(math.Ceil(fu - ru))
		if begin < 0 {
			begin = 0
		}
		end := int(math.Floor(fu + ru))
		if end > srcSize-1 {
			end = srcSize - 1
		}

		var sum float64
		for u := begin; u <= end; u++ {
			w := filter.Kernel((float64(u) - fu) / scale)
			if w != 0 {
				sum += w
				tmp = append(tmp, indexWeight{index: u, weight: w})
			}
		}
		if sum != 0 {
			for i := range tmp {
				tmp[i].weight /= sum
			}
		}

		out[v] = tmp
		tmp = tmp[len(tmp):]
	}

	return out
}

// Resize resizes the image to the specified width and height using the specified resampling
// filter and returns the transformed image. If one of width or height is 0, the image aspect
// ratio is preserved.
//
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
//
// Usage example:
//
//	dstImage := imaging.Resize(srcImage, 800, 600, imaging.Lanczos)
//
func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
	dstW, dstH := width, height
	if dstW < 0 || dstH < 0 {
		return &image.NRGBA{}
	}
	if dstW == 0 && dstH == 0 {
		return &image.NRGBA{}
	}

	srcW := img.Bounds().Dx()
	srcH := img.Bounds().Dy()
	if srcW <= 0 || srcH <= 0 {
		return &image.NRGBA{}
	}

	// If new width or height is 0 then preserve aspect ratio, minimum 1px.
	if dstW == 0 {
		tmpW := float64(dstH) * float64(srcW) / float64(srcH)
		dstW = int(math.Max(1.0, math.Floor(tmpW+0.5)))
	}
	if dstH == 0 {
		tmpH := float64(dstW) * float64(srcH) / float64(srcW)
		dstH = int(math.Max(1.0, math.Floor(tmpH+0.5)))
	}

	if filter.Support <= 0 {
		// Nearest-neighbor special case.
		return resizeNearest(img, dstW, dstH)
	}

	if srcW != dstW && srcH != dstH {
		return resizeVertical(resizeHorizontal(img, dstW, filter), dstH, filter)
	}
	if srcW != dstW {
		return resizeHorizontal(img, dstW, filter)
	}
	if srcH != dstH {
		return resizeVertical(img, dstH, filter)
	}
	return Clone(img)
}

func resizeHorizontal(img image.Image, width int, filter ResampleFilter) *image.NRGBA {
	src := newScanner(img)
	dst := image.NewNRGBA(image.Rect(0, 0, width, src.h))
	weights := precomputeWeights(width, src.w, filter)
	parallel(0, src.h, func(ys <-chan int) {
		scanLine := make([]uint8, src.w*4)
		for y := range ys {
			src.scan(0, y, src.w, y+1, scanLine)
			j0 := y * dst.Stride
			for x := 0; x < width; x++ {
				var r, g, b, a float64
				for _, w := range weights[x] {
					i := w.index * 4
					aw := float64(scanLine[i+3]) * w.weight
					r += float64(scanLine[i+0]) * aw
					g += float64(scanLine[i+1]) * aw
					b += float64(scanLine[i+2]) * aw
					a += aw
				}
				if a != 0 {
					aInv := 1 / a
					j := j0 + x*4
					dst.Pix[j+0] = clamp(r * aInv)
					dst.Pix[j+1] = clamp(g * aInv)
					dst.Pix[j+2] = clamp(b * aInv)
					dst.Pix[j+3] = clamp(a)
				}
			}
		}
	})
	return dst
}

func resizeVertical(img image.Image, height int, filter ResampleFilter) *image.NRGBA {
	src := newScanner(img)
	dst := image.NewNRGBA(image.Rect(0, 0, src.w, height))
	weights := precomputeWeights(height, src.h, filter)
	parallel(0, src.w, func(xs <-chan int) {
		scanLine := make([]uint8, src.h*4)
		for x := range xs {
			src.scan(x, 0, x+1, src.h, scanLine)
			for y := 0; y < height; y++ {
				var r, g, b, a float64
				for _, w := range weights[y] {
					i := w.index * 4
					aw := float64(scanLine[i+3]) * w.weight
					r += float64(scanLine[i+0]) * aw
					g += float64(scanLine[i+1]) * aw
					b += float64(scanLine[i+2]) * aw
					a += aw
				}
				if a != 0 {
					aInv := 1 / a
					j := y*dst.Stride + x*4
					dst.Pix[j+0] = clamp(r * aInv)
					dst.Pix[j+1] = clamp(g * aInv)
					dst.Pix[j+2] = clamp(b * aInv)
					dst.Pix[j+3] = clamp(a)
				}
			}
		}
	})
	return dst
}

// resizeNearest is a fast nearest-neighbor resize, no filtering.
func resizeNearest(img image.Image, width, height int) *image.NRGBA {
	dst := image.NewNRGBA(image.Rect(0, 0, width, height))
	dx := float64(img.Bounds().Dx()) / float64(width)
	dy := float64(img.Bounds().Dy()) / float64(height)

	if dx > 1 && dy > 1 {
		src := newScanner(img)
		parallel(0, height, func(ys <-chan int) {
			for y := range ys {
				srcY := int((float64(y) + 0.5) * dy)
				dstOff := y * dst.Stride
				for x := 0; x < width; x++ {
					srcX := int((float64(x) + 0.5) * dx)
					src.scan(srcX, srcY, srcX+1, srcY+1, dst.Pix[dstOff:dstOff+4])
					dstOff += 4
				}
			}
		})
	} else {
		src := toNRGBA(img)
		parallel(0, height, func(ys <-chan int) {
			for y := range ys {
				srcY := int((float64(y) + 0.5) * dy)
				srcOff0 := srcY * src.Stride
				dstOff := y * dst.Stride
				for x := 0; x < width; x++ {
					srcX := int((float64(x) + 0.5) * dx)
					srcOff := srcOff0 + srcX*4
					copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
					dstOff += 4
				}
			}
		})
	}

	return dst
}

// Fit scales down the image using the specified resample filter to fit the specified
// maximum width and height and returns the transformed image.
//
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
//
// Usage example:
//
//	dstImage := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)
//
func Fit(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
	maxW, maxH := width, height

	if maxW <= 0 || maxH <= 0 {
		return &image.NRGBA{}
	}

	srcBounds := img.Bounds()
	srcW := srcBounds.Dx()
	srcH := srcBounds.Dy()

	if srcW <= 0 || srcH <= 0 {
		return &image.NRGBA{}
	}

	if srcW <= maxW && srcH <= maxH {
		return Clone(img)
	}

	srcAspectRatio := float64(srcW) / float64(srcH)
	maxAspectRatio := float64(maxW) / float64(maxH)

	var newW, newH int
	if srcAspectRatio > maxAspectRatio {
		newW = maxW
		newH = int(float64(newW) / srcAspectRatio)
	} else {
		newH = maxH
		newW = int(float64(newH) * srcAspectRatio)
	}

	return Resize(img, newW, newH, filter)
}

// Fill scales the image to the smallest possible size that will cover the specified dimensions,
// crops the resized image to the specified dimensions using the given anchor point and returns
// the transformed image.
//
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
//
// Usage example:
//
//	dstImage := imaging.Fill(srcImage, 800, 600, imaging.Center, imaging.Lanczos)
//
func Fill(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA {
	minW, minH := width, height

	if minW <= 0 || minH <= 0 {
		return &image.NRGBA{}
	}

	srcBounds := img.Bounds()
	srcW := srcBounds.Dx()
	srcH := srcBounds.Dy()

	if srcW <= 0 || srcH <= 0 {
		return &image.NRGBA{}
	}

	if srcW == minW && srcH == minH {
		return Clone(img)
	}

	srcAspectRatio := float64(srcW) / float64(srcH)
	minAspectRatio := float64(minW) / float64(minH)

	var tmp *image.NRGBA
	if srcAspectRatio < minAspectRatio {
		tmp = Resize(img, minW, 0, filter)
	} else {
		tmp = Resize(img, 0, minH, filter)
	}

	return CropAnchor(tmp, minW, minH, anchor)
}

// Thumbnail scales the image up or down using the specified resample filter, crops it
// to the specified width and hight and returns the transformed image.
//
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
//
// Usage example:
//
//	dstImage := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)
//
func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
	return Fill(img, width, height, Center, filter)
}

// ResampleFilter is a resampling filter struct. It can be used to define custom filters.
//
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
//
//	General filter recommendations:
//
//	- Lanczos
//		High-quality resampling filter for photographic images yielding sharp results.
//		It's slower than cubic filters (see below).
//
//	- CatmullRom
//		A sharp cubic filter. It's a good filter for both upscaling and downscaling if sharp results are needed.
//
//	- MitchellNetravali
//		A high quality cubic filter that produces smoother results with less ringing artifacts than CatmullRom.
//
//	- BSpline
//		A good filter if a very smooth output is needed.
//
//	- Linear
//		Bilinear interpolation filter, produces reasonably good, smooth output.
//		It's faster than cubic filters.
//
//	- Box
//		Simple and fast averaging filter appropriate for downscaling.
//		When upscaling it's similar to NearestNeighbor.
//
//	- NearestNeighbor
//		Fastest resampling filter, no antialiasing.
//
type ResampleFilter struct {
	Support float64
	Kernel  func(float64) float64
}

// NearestNeighbor is a nearest-neighbor filter (no anti-aliasing).
var NearestNeighbor ResampleFilter

// Box filter (averaging pixels).
var Box ResampleFilter

// Linear filter.
var Linear ResampleFilter

// Hermite cubic spline filter (BC-spline; B=0; C=0).
var Hermite ResampleFilter

// MitchellNetravali is Mitchell-Netravali cubic filter (BC-spline; B=1/3; C=1/3).
var MitchellNetravali ResampleFilter

// CatmullRom is a Catmull-Rom - sharp cubic filter (BC-spline; B=0; C=0.5).
var CatmullRom ResampleFilter

// BSpline is a smooth cubic filter (BC-spline; B=1; C=0).
var BSpline ResampleFilter

// Gaussian is a Gaussian blurring Filter.
var Gaussian ResampleFilter

// Bartlett is a Bartlett-windowed sinc filter (3 lobes).
var Bartlett ResampleFilter

// Lanczos filter (3 lobes).
var Lanczos ResampleFilter

// Hann is a Hann-windowed sinc filter (3 lobes).
var Hann ResampleFilter

// Hamming is a Hamming-windowed sinc filter (3 lobes).
var Hamming ResampleFilter

// Blackman is a Blackman-windowed sinc filter (3 lobes).
var Blackman ResampleFilter

// Welch is a Welch-windowed sinc filter (parabolic window, 3 lobes).
var Welch ResampleFilter

// Cosine is a Cosine-windowed sinc filter (3 lobes).
var Cosine ResampleFilter

func bcspline(x, b, c float64) float64 {
	var y float64
	x = math.Abs(x)
	if x < 1.0 {
		y = ((12-9*b-6*c)*x*x*x + (-18+12*b+6*c)*x*x + (6 - 2*b)) / 6
	} else if x < 2.0 {
		y = ((-b-6*c)*x*x*x + (6*b+30*c)*x*x + (-12*b-48*c)*x + (8*b + 24*c)) / 6
	}
	return y
}

func sinc(x float64) float64 {
	if x == 0 {
		return 1
	}
	return math.Sin(math.Pi*x) / (math.Pi * x)
}

func init() {
	NearestNeighbor = ResampleFilter{
		Support: 0.0, // special case - not applying the filter
	}

	Box = ResampleFilter{
		Support: 0.5,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x <= 0.5 {
				return 1.0
			}
			return 0
		},
	}

	Linear = ResampleFilter{
		Support: 1.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 1.0 {
				return 1.0 - x
			}
			return 0
		},
	}

	Hermite = ResampleFilter{
		Support: 1.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 1.0 {
				return bcspline(x, 0.0, 0.0)
			}
			return 0
		},
	}

	MitchellNetravali = ResampleFilter{
		Support: 2.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 2.0 {
				return bcspline(x, 1.0/3.0, 1.0/3.0)
			}
			return 0
		},
	}

	CatmullRom = ResampleFilter{
		Support: 2.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 2.0 {
				return bcspline(x, 0.0, 0.5)
			}
			return 0
		},
	}

	BSpline = ResampleFilter{
		Support: 2.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 2.0 {
				return bcspline(x, 1.0, 0.0)
			}
			return 0
		},
	}

	Gaussian = ResampleFilter{
		Support: 2.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 2.0 {
				return math.Exp(-2 * x * x)
			}
			return 0
		},
	}

	Bartlett = ResampleFilter{
		Support: 3.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 3.0 {
				return sinc(x) * (3.0 - x) / 3.0
			}
			return 0
		},
	}

	Lanczos = ResampleFilter{
		Support: 3.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 3.0 {
				return sinc(x) * sinc(x/3.0)
			}
			return 0
		},
	}

	Hann = ResampleFilter{
		Support: 3.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 3.0 {
				return sinc(x) * (0.5 + 0.5*math.Cos(math.Pi*x/3.0))
			}
			return 0
		},
	}

	Hamming = ResampleFilter{
		Support: 3.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 3.0 {
				return sinc(x) * (0.54 + 0.46*math.Cos(math.Pi*x/3.0))
			}
			return 0
		},
	}

	Blackman = ResampleFilter{
		Support: 3.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 3.0 {
				return sinc(x) * (0.42 - 0.5*math.Cos(math.Pi*x/3.0+math.Pi) + 0.08*math.Cos(2.0*math.Pi*x/3.0))
			}
			return 0
		},
	}

	Welch = ResampleFilter{
		Support: 3.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 3.0 {
				return sinc(x) * (1.0 - (x * x / 9.0))
			}
			return 0
		},
	}

	Cosine = ResampleFilter{
		Support: 3.0,
		Kernel: func(x float64) float64 {
			x = math.Abs(x)
			if x < 3.0 {
				return sinc(x) * math.Cos((math.Pi/2.0)*(x/3.0))
			}
			return 0
		},
	}
}


text:
package com.snowplowanalytics.snowplow.enrich
package hadoop
package jobs

// Java
import java.io.File
import java.io.BufferedWriter
import java.io.FileWriter

// Apache Commons IO
import org.apache.commons.io.FileUtils
import org.apache.commons.io.filefilter.TrueFileFilter

// Apache Commons Codec
import org.apache.commons.codec.binary.Base64

// Scala
import scala.collection.mutable.ListBuffer
import scala.io.Source
import scala.collection.JavaConverters._

// Scalaz
import scalaz._
import Scalaz._

// Scala
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._

// Scalding
import com.twitter.scalding._

// Specs2
import org.specs2.matcher.{Matcher, Expectable}
import org.specs2.matcher.Matchers._
/**
 * Holds helpers for running integration
 * tests on SnowPlow EtlJobs.
 */
object JobSpecHelpers {

  /**
   * A Specs2 matcher to check if a Scalding
   * output sink is empty or not.
   */
  val beEmpty: Matcher[ListBuffer[_]] =
    ((_: ListBuffer[_]).isEmpty, "is not empty")

  /**
   * A Specs2 matcher to check if a directory
   * on disk is empty or not.
   */
  val beEmptyFile: Matcher[File] =
    ((f: File) =>
      !f.exists || (f.isFile && f.length == 0),
      "is populated file"
    )

  /**
   * How Scalding represents input lines
   */
  type ScaldingLines = List[(String, String)]

  /**
   * Base64-urlsafe encoded version of this standard
   * Iglu configuration.
   */
  private val IgluConfig = {
    val encoder = new Base64(true) // true means "url safe"
    new String(encoder.encode(SpecHelpers.IgluConfig.getBytes)
    )
  }

  /**
   * A case class to make it easy to write out input
   * lines for Scalding jobs without manually appending
   * line numbers.
   *
   * @param l The repeated String parameters
   */
  case class Lines(l: String*) {

    val lines = l.toList
    val numberedLines = number(lines)

    /**
     * Writes the lines to the given file
     *
     * @param file The file to write the
     *        lines to
     */
    def writeTo(file: File) = {
      val writer = new BufferedWriter(new FileWriter(file))
      for (line <- lines) {
        writer.write(line)
        writer.newLine()
      }
      writer.close()
    }

    /**
     * Numbers the lines in the Scalding format.
     * Converts "My line" to ("0" -> "My line")
     *
     * @param lines The List of lines to number
     * @return the List of ("line number" -> "line")
     *         tuples.
     */
    private def number(lines: List[String]): ScaldingLines =
      for ((l, n) <- lines zip (0 until lines.size)) yield (n.toString -> l)
  }

  /**
   * Implicit conversion from a Lines object to
   * a ScaldingLines, aka List[(String, String)],
   * ready for Scalding to use.
   *
   * @param lines The Lines object
   * @return the ScaldingLines ready for Scalding
   */
  implicit def Lines2ScaldingLines(lines : Lines): ScaldingLines = lines.numberedLines

  /**
   * A standard JobSpec definition used by all of our
   * integration tests.
   */
  val ShredJobSpec =
    JobTest("com.snowplowanalytics.snowplow.enrich.hadoop.ShredJob").
      arg("input_folder", "inputFolder").
      arg("output_folder", "outputFolder").
      arg("bad_rows_folder", "badFolder").
      arg("exceptions_folder", "exceptionsFolder").
      arg("iglu_config", IgluConfig)

  case class Sinks(
    val output:     File,
    val badRows:    File,
    val exceptions: File) {

    def deleteAll() {
      for (f <- List(exceptions, badRows, output)) {
        f.delete()
      }
    }
  }

  /**
   * Run the ShredJob using the Scalding Tool.
   *
   * @param lines The input lines to shred
   * @return a Tuple3 containing open File
   *         objects for the output, bad rows
   *         and exceptions temporary directories.
   */
  def runJobInTool(lines: Lines): Sinks = {

    def mkTmpDir(tag: String, createParents: Boolean = false, containing: Option[Lines] = None): File = {
      val f = File.createTempFile(s"snowplow-shred-job-${tag}-", "")
      if (createParents) f.mkdirs() else f.mkdir()
      containing.map(_.writeTo(f))
      f
    }

    val input      = mkTmpDir("input", createParents = true, containing = lines.some)
    val output     = mkTmpDir("output")
    val badRows    = mkTmpDir("bad-rows")
    val exceptions = mkTmpDir("exceptions")

    val args = Array[String]("com.snowplowanalytics.snowplow.enrich.hadoop.ShredJob", "--local",
      "--input_folder",      input.getAbsolutePath,
      "--output_folder",     output.getAbsolutePath,
      "--bad_rows_folder",   badRows.getAbsolutePath,
      "--exceptions_folder", exceptions.getAbsolutePath,
      "--iglu_config",       IgluConfig)

    // Execute
    Tool.main(args)
    input.delete()

    Sinks(output, badRows, exceptions)
  }

  /**
   * Removes the timestamp from bad rows so that what remains is deterministic
   *
   * @param badRow
   * @return The bad row without the timestamp
   */
  def removeTstamp(badRow: String): String = {
    val badRowJson = parse(badRow)
    val badRowWithoutTimestamp = ("line", (badRowJson \ "line")) ~ ("errors", (badRowJson \ "errors"))
    compact(badRowWithoutTimestamp)
  }

  /**
   * Reads a file at the given path into a List of Strings
   *
   * @param root A root filepath
   * @param relativePath The relative path to the file from
   *        the root
   * @return the file contents
   */
  def readFile(root: File, relativePath: String): List[String] =
    Source
      .fromFile(new File(root, relativePath))
      .getLines
      .toList

  /**
   * Recursively lists files in a given path, excluding the
   * supplied paths.
   *
   * @param root A root filepath
   * @param exclusions A list of paths to exclude from the listing
   * @return the list of files contained in the root, minus the
   *         exclusions
   */
  def listFilesWithExclusions(root: File, exclusions: List[String]): List[String] = {
    val excl = for {
      e <- exclusions
    } yield (new File(root, e)).getCanonicalPath

    FileUtils.listFiles(root, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)
      .asScala
      .toList
      .map(_.getCanonicalPath)
      .filter(p => !excl.contains(p))
  }

}


text:
<!DOCTYPE html>
<html>
    <head>
    	<meta charset="utf-8">
    	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    	<title>Test Page</title>
    	<?= stylesheet_link_tag() ?>
        <?= javascript_include_tag() ?>
        <script>
			$(document).ready(function(){
				$('select.dropdown').dropdown();
			});
		</script>
    </head>
    <body>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
Spring Framework: Class  AbstractCachingViewResolver
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

com.interface21.web.servlet.view

Class  AbstractCachingViewResolver

java.lang.Object
  |
  +--com.interface21.context.support.ApplicationObjectSupport
        |
        +--com.interface21.web.servlet.view.AbstractCachingViewResolver

All Implemented Interfaces:
ApplicationContextAware, ViewResolver

Direct Known Subclasses:
InternalResourceViewResolver, ResourceBundleViewResolver, XmlViewResolver

public abstract class AbstractCachingViewResolver
extends ApplicationObjectSupport
implements ViewResolver

Convenient superclass for view resolvers. Caches views once resolved.
 This means that view resolution won't be a performance problem,
 no matter how costly initial view retrieval is.
 View retrieval is deferred to subclasses.

Author:
Rod Johnson

Fields inherited from class com.interface21.context.support.ApplicationObjectSupport

logger

Constructor Summary

AbstractCachingViewResolver()

Method Summary

 boolean
isCache()

          If caching is enabled.

protected abstract  View
loadView(java.lang.String viewName,
         java.util.Locale locale)

          Subclasses must implement this method.

 View
resolveViewName(java.lang.String viewName,
                java.util.Locale locale)

          Resolve the given view by name.

 void
setCache(boolean cache)

          Enable caching.

Methods inherited from class com.interface21.context.support.ApplicationObjectSupport

getApplicationContext, initApplicationContext, setApplicationContext

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface com.interface21.context.ApplicationContextAware

setApplicationContext

Constructor Detail

AbstractCachingViewResolver

public AbstractCachingViewResolver()

Method Detail

setCache

public void setCache(boolean cache)

Enable caching. Disable this only for debugging and development.
 Default is for caching to be enabled.

Warning: disabling caching severely impacts performance.
 Tests indicate that turning caching off reduces performance by at
 least 20%. Increased object churn probably eventually makes the
 problem even worse.

isCache

public boolean isCache()

If caching is enabled.

resolveViewName

public final View resolveViewName(java.lang.String viewName,
                                  java.util.Locale locale)
                           throws javax.servlet.ServletException

Description copied from interface: ViewResolver

Resolve the given view by name.

Specified by:
resolveViewName in interface ViewResolver

Following copied from interface: com.interface21.web.servlet.ViewResolver

Parameters:
viewName - name of the view to resolve
locale - Locale in which to resolve the view. ViewResolvers
 that support internationalization should respect this.
Throws:
javax.servlet.ServletException - if the view cannot be resolved.

loadView

protected abstract View loadView(java.lang.String viewName,
                                 java.util.Locale locale)
                          throws javax.servlet.ServletException

Subclasses must implement this method. There need be no concern for efficiency,
 as this class will cache views. Not all subclasses may support internationalization:
 A subclass that doesn't can ignore the locale parameter.

Parameters:
viewName - name of the view to retrieve
locale - Locale to retrieve the view for
Returns:
the View if it can be resolved, or null
Throws:
javax.servlet.ServletException - if there is an error trying to resolve the view

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Rod Johnson and Spring contributors 2001-2003.


text:
package network

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"net/http"
)

const (
	// DefaultBaseURI is the default URI used for the service Network
	DefaultBaseURI = "https://management.azure.com"
)

// ManagementClient is the base client for Network.
type ManagementClient struct {
	autorest.Client
	BaseURI        string
	SubscriptionID string
}

// New creates an instance of the ManagementClient client.
func New(subscriptionID string) ManagementClient {
	return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewWithBaseURI creates an instance of the ManagementClient client.
func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {
	return ManagementClient{
		Client:         autorest.NewClientWithUserAgent(UserAgent()),
		BaseURI:        baseURI,
		SubscriptionID: subscriptionID,
	}
}

// CheckDNSNameAvailability checks whether a domain name in the cloudapp.net zone is available for use.
//
// location is the location of the domain name. domainNameLabel is the domain name to be verified. It must conform to
// the following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$.
func (client ManagementClient) CheckDNSNameAvailability(location string, domainNameLabel string) (result DNSNameAvailabilityResult, err error) {
	req, err := client.CheckDNSNameAvailabilityPreparer(location, domainNameLabel)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", nil, "Failure preparing request")
		return
	}

	resp, err := client.CheckDNSNameAvailabilitySender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", resp, "Failure sending request")
		return
	}

	result, err = client.CheckDNSNameAvailabilityResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", resp, "Failure responding to request")
	}

	return
}

// CheckDNSNameAvailabilityPreparer prepares the CheckDNSNameAvailability request.
func (client ManagementClient) CheckDNSNameAvailabilityPreparer(location string, domainNameLabel string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"location":       autorest.Encode("path", location),
		"subscriptionId": autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2016-09-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(domainNameLabel) > 0 {
		queryParameters["domainNameLabel"] = autorest.Encode("query", domainNameLabel)
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/CheckDnsNameAvailability", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare(&http.Request{})
}

// CheckDNSNameAvailabilitySender sends the CheckDNSNameAvailability request. The method will close the
// http.Response Body if it receives an error.
func (client ManagementClient) CheckDNSNameAvailabilitySender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client,
		req,
		azure.DoRetryWithRegistration(client.Client))
}

// CheckDNSNameAvailabilityResponder handles the response to the CheckDNSNameAvailability request. The method always
// closes the http.Response Body.
func (client ManagementClient) CheckDNSNameAvailabilityResponder(resp *http.Response) (result DNSNameAvailabilityResult, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}


text:
import AccordionItem from './AccordionItem';
import {getFirstLevelDomDescendantsByCssClassSelector} from './../../_helpers/DomTraversing';

class Accordion {

  items = [];

  constructor(domNode, {itemSelector, itemOpenedClass, itemHeaderClassSelector}) {
    const accordionItems = getFirstLevelDomDescendantsByCssClassSelector(domNode, itemSelector);

    accordionItems.forEach(accordionItemNode =>
      this.items.push(new AccordionItem(accordionItemNode, {
        itemOpenedClass,
        itemHeaderClassSelector,
        onItemClickCallback: this.onAccordionItemSelected.bind(this),
        isInitiallyCollapsed: !accordionItemNode.classList.contains(itemOpenedClass)
      }))
    );
  }

  onAccordionItemSelected(anAccordionItem) {
    Array.from(this.items).forEach(accordionItem => {
      if (accordionItem === anAccordionItem) {
        accordionItem.toggle();
      } else {
        accordionItem.close();
      }
    });
  }
}

export default Accordion;


text:
Clojure gives us access to Java's shell capabilities through
`clojure.java.shell`. For instance, if you want to list the contents of your
project's directory, you can issue an `ls` command:

```
> (clojure.java.shell/sh "ls")
; {:exit 0,
;  :out "LICENSE\nREADME.md\ndoc\nproject.clj\nresources\nsrc\ntarget\ntest\n",
;  :err ""}
```

The default will always be to execute the command in the directory of the
containing project. It is likely that you'd like to specify a different
directory though. There is a function for that:

```clojure
(clojure.java.shell/with-sh-dir "some/dir" (clojure.java.shell/sh "ls"))
```

Or more concisely, you can specify the directory as part of the `sh`
function:

```clojure
(clojure.java.shell/sh "ls" :dir "some/dir")
```


text:
from invoke import Collection

from invocations import docs
from invocations.checks import blacken
from invocations.packaging import release
from invocations.pytest import test, coverage

ns = Collection(release, test, coverage, docs, blacken)
ns.configure(
    {
        "packaging": {
            "sign": True,
            "wheel": True,
            "changelog_file": "docs/changelog.rst",
        },
        "run": {
            "env": {
                # Our ANSI color tests test against hardcoded codes appropriate
                # for this terminal, for now.
                "TERM": "xterm-256color"
            },
        },
    }
)


text:
package cn.jsprun.foreg.vo.topicadmin;
public class ToTopAndEliteVO extends BaseVOWithSpareCheckBox {
	private String level;
	private Integer stickPurview;
	public String getLevel() {
		return level;
	}
	public void setLevel(String level) {
		this.level = level;
	}
	public Integer getStickPurview() {
		return stickPurview;
	}
	public void setStickPurview(Integer stickPurview) {
		this.stickPurview = stickPurview;
	}
}


text:
package org.apache.hadoop.hive.ql.udf.generic;

public class LongNumDistinctValueEstimator extends NumDistinctValueEstimator {

  public LongNumDistinctValueEstimator(int numBitVectors) {
    super(numBitVectors);
  }

  public LongNumDistinctValueEstimator(String s, int numVectors) {
    super(s, numVectors);
  }

   @Override
   public void addToEstimator(long v) {
    /* Update summary bitVector :
     * Generate hash value of the long value and mod it by 2^bitVectorSize-1.
     * In this implementation bitVectorSize is 31.
     */
     super.addToEstimator(v);
  }

  @Override
  public void addToEstimatorPCSA(long v) {
    super.addToEstimatorPCSA(v);
  }
}


text:
package backend

import (
	"context"
	"os"
	"path/filepath"
	"testing"

	"github.com/gopasspw/gopass/pkg/ctxutil"
	"github.com/gopasspw/gopass/pkg/debug"
	"github.com/stretchr/testify/assert"
)

func TestDetectStorage(t *testing.T) { //nolint:paralleltest
	ctx := context.Background()

	td := t.TempDir()

	// all tests involving age should set GOPASS_HOMEDIR
	t.Setenv("GOPASS_HOMEDIR", td)
	ctx = ctxutil.WithPasswordCallback(ctx, func(_ string, _ bool) ([]byte, error) {
		debug.Log("static test password callback")

		return []byte("gopass"), nil
	})

	fsDir := filepath.Join(td, "fs")
	assert.NoError(t, os.MkdirAll(fsDir, 0o700))

	t.Run("detect fs", func(t *testing.T) {
		r, err := DetectStorage(ctx, fsDir)
		assert.NoError(t, err)
		assert.NotNil(t, r)
		assert.Equal(t, "fs", r.Name())
	})
}


text:
* Testing: Karma, Jasmine
* Custom directive
* Snippets
* Helpers