text:
package org.basex.query.expr;

import static org.basex.query.func.Function.*;

import org.basex.query.*;
import org.basex.query.CompileContext.*;
import org.basex.query.expr.CmpG.*;
import org.basex.query.iter.*;
import org.basex.query.util.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.seq.*;
import org.basex.query.value.type.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.hash.*;

/**
 * If expression.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Christian Gruen
 */
public final class If extends Arr {
  /** Condition. */
  public Expr cond;

  /**
   * Constructor with empty 'else' branch.
   * @param info input info
   * @param cond condition
   * @param branch1 'then' branch
   */
  public If(final InputInfo info, final Expr cond, final Expr branch1) {
    this(info, cond, branch1, Empty.VALUE);
  }

  /**
   * Constructor.
   * @param info input info
   * @param cond condition
   * @param branch1 'then' branch
   * @param branch2 'else' branch
   */
  public If(final InputInfo info, final Expr cond, final Expr branch1, final Expr branch2) {
    super(info, SeqType.ITEM_ZM, branch1, branch2);
    this.cond = cond;
  }

  @Override
  public void checkUp() throws QueryException {
    checkNoUp(cond);
    checkAllUp(exprs);
  }

  @Override
  public Expr compile(final CompileContext cc) throws QueryException {
    cond = cond.compile(cc);

    final int el = exprs.length;
    for(int e = 0; e < el; e++) {
      exprs[e] = cc.compileOrError(exprs[e], false);
    }
    return optimize(cc);
  }

  @Override
  public Expr optimize(final CompileContext cc) throws QueryException {
    if(EMPTY.is(cond)) {
      // if(empty(A)) then B else C  ->  if(exists(A)) then C else B
      cond = cc.function(EXISTS, info, cond.arg(0));
      swap();
      cc.info(QueryText.OPTSWAP_X, this);
    } else if(NOT.is(cond)) {
      // if(not(A)) then B else C  ->  if(A) then C else B
      cond = cond.arg(0);
      swap();
      cc.info(QueryText.OPTSWAP_X, this);
    }
    // if(exists(nodes))  ->  if(nodes)
    cond = cond.simplifyFor(Simplify.EBV, cc);

    return cc.replaceWith(this, opt(cc));
  }

  /**
   * Optimizes the expression.
   * @param cc compilation context
   * @return optimized or original expression
   * @throws QueryException query exception
   */
  private Expr opt(final CompileContext cc) throws QueryException {
    // choose static branch at compile time
    if(cond instanceof Value) return expr(cc.qc);

    // if(...empty sequence...) then A else B  ->  B
    final Expr br1 = exprs[0], br2 = exprs[1];
    final SeqType ct = cond.seqType();
    final boolean ndt = cond.has(Flag.NDT);
    if(ct.zero() && !ndt) return br2;

    // rewrite to elvis operator:
    //   if(exists(VALUE)) then VALUE else DEFAULT  ->  VALUE ?: DEFAULT
    //   if(NODES) then NODES else DEFAULT  ->  NODES ?: DEFAULT
    final Expr cmp = EXISTS.is(cond) ? cond.arg(0) :
      ct.type instanceof NodeType ? cond : null;
    if(!ndt && cmp != null && cmp.equals(br1)) return
        cc.function(_UTIL_OR, info, br1, br2);

    // if(A) then B else B  ->  prof:void(A), B
    if(br1.equals(br2)) return cc.merge(cond, br1, info);

    // determine type
    final SeqType st1 = br1.seqType(), st2 = br2.seqType();
    exprType.assign(st1.union(st2)).data(exprs);

    // logical rewritings
    if(st1.eq(SeqType.BOOLEAN_O) && st2.eq(SeqType.BOOLEAN_O)) {
      if(br1 == Bln.TRUE) return br2 == Bln.FALSE ?
        // if(A) then true() else false()  ->  boolean(A)
        cc.function(BOOLEAN, info, cond) :
        // if(A) then true() else C  ->  A or C
        new Or(info, cond, br2).optimize(cc);
      if(br2 == Bln.TRUE) return br1 == Bln.FALSE ?
        // if(A) then false() else true()  ->  not(A)
        cc.function(NOT, info, cond) :
        // if(A) then B else true()  ->  not(A) or B
        new Or(info, cc.function(NOT, info, cond), br1).optimize(cc);
      // if(A) then false() else C  ->  not(A) and C
      if(br1 == Bln.FALSE) return
        new And(info, cc.function(NOT, info, cond), br2).optimize(cc);
      // if(A) then B else false()  ->  A and B
      if(br2 == Bln.FALSE) return
        new And(info, cond, br1).optimize(cc);

      if(contradict(br1, br2, false)) return new CmpG(
          info, cc.function(BOOLEAN, info, cond), br1, OpG.EQ, null, cc.sc()).optimize(cc);
      if(contradict(br2, br1, false)) return new CmpG(
          info, cc.function(BOOLEAN, info, cond), br2, OpG.NE, null, cc.sc()).optimize(cc);
    }
    return this;
  }

  /**
   * Swaps the arguments.
   */
  public void swap() {
    final Expr tmp = exprs[0];
    exprs[0] = exprs[1];
    exprs[1] = tmp;
  }

  @Override
  public Iter iter(final QueryContext qc) throws QueryException {
    return expr(qc).iter(qc);
  }

  @Override
  public Value value(final QueryContext qc) throws QueryException {
    return expr(qc).value(qc);
  }

  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    return expr(qc).item(qc, info);
  }

  /**
   * Tests the condition and returns the expression to evaluate.
   * @param qc query context
   * @return branch offset
   * @throws QueryException query exception
   */
  private Expr expr(final QueryContext qc) throws QueryException {
    return exprs[cond.ebv(qc, info).bool(info) ? 0 : 1];
  }

  @Override
  public boolean has(final Flag... flags) {
    return cond.has(flags) || super.has(flags);
  }

  @Override
  public boolean inlineable(final InlineContext ic) {
    return cond.inlineable(ic) && super.inlineable(ic);
  }

  @Override
  public VarUsage count(final Var var) {
    return cond.count(var).plus(VarUsage.maximum(var, exprs));
  }

  @Override
  public Expr inline(final InlineContext ic) throws QueryException {
    boolean changed = ic.inline(exprs, true);
    final Expr inlined = cond.inline(ic);
    if(inlined != null) {
      changed = true;
      cond = inlined;
    }
    return changed ? optimize(ic.cc) : null;
  }

  @Override
  public If copy(final CompileContext cc, final IntObjMap<Var> vm) {
    return copyType(new If(info, cond.copy(cc, vm), exprs[0].copy(cc, vm), exprs[1].copy(cc, vm)));
  }

  @Override
  public boolean vacuous() {
    return exprs[0].vacuous() && exprs[1].vacuous();
  }

  @Override
  public boolean ddo() {
    return exprs[0].ddo() && exprs[1].ddo();
  }

  @Override
  public void markTailCalls(final CompileContext cc) {
    for(final Expr expr : exprs) expr.markTailCalls(cc);
  }

  @Override
  public Expr simplifyFor(final Simplify mode, final CompileContext cc) throws QueryException {
    return simplifyAll(mode, cc) ? optimize(cc) : super.simplifyFor(mode, cc);
  }

  @Override
  public boolean accept(final ASTVisitor visitor) {
    return cond.accept(visitor) && super.accept(visitor);
  }

  @Override
  public int exprSize() {
    int size = cond.exprSize();
    for(final Expr expr : exprs) size += expr.exprSize();
    return size;
  }

  @Override
  public Expr typeCheck(final TypeCheck tc, final CompileContext cc) throws QueryException {
    boolean changed = false;
    final int el = exprs.length;
    for(int e = 0; e < el; e++) {
      Expr expr = exprs[e];
      try {
        expr = tc.check(expr, cc);
      } catch(final QueryException qe) {
        expr = cc.error(qe, expr);
      }
      if(expr != null) {
        changed = true;
        exprs[e] = expr;
      }
    }
    return changed ? optimize(cc) : this;
  }

  @Override
  public boolean equals(final Object obj) {
    return this == obj || obj instanceof If && cond.equals(((If) obj).cond) && super.equals(obj);
  }

  @Override
  public void toXml(final QueryPlan plan) {
    plan.add(plan.create(this), cond, exprs);
  }

  @Override
  public void toString(final QueryString qs) {
    qs.token("(").token(QueryText.IF).paren(cond).token(QueryText.THEN).token(exprs[0]);
    qs.token(QueryText.ELSE).token(exprs[1]).token(')');
  }
}


text:
package de.waldheinz.fs;

import java.io.IOException;
import java.util.Iterator;

/**
 * Base class for all {@link FileSystem} directories.
 *
 * @author Ewout Prangsma < epr at jnode.org>
 * @author Matthias Treydte
 */
public interface FsDirectory extends Iterable<FsDirectoryEntry>, FsObject {

    /**
     * Gets an iterator to iterate over the entries of this directory.
     *
     * @return the directory iterator
     */
    @Override
    Iterator<FsDirectoryEntry> iterator();

    /**
     * Gets the entry with the given name.
     *
     * @param name the name of the entry to get
     * @return the entry, if it existed
     * @throws IOException on error retrieving the entry
     */
    FsDirectoryEntry getEntry(String name) throws IOException;

    /**
     * Add a new file with a given name to this directory.
     *
     * @param name the name of the file to add
     * @return the entry pointing to the new file
     * @throws IOException on error creating the file
     */
    FsDirectoryEntry addFile(String name) throws IOException;

    /**
     * Add a new (sub-)directory with a given name to this directory.
     *
     * @param name the name of the sub-directory to add
     * @return the entry pointing to the new directory
     * @throws IOException on error creating the directory
     */
    FsDirectoryEntry addDirectory(String name) throws IOException;

    /**
     * Remove the entry with the given name from this directory.
     *
     * @param name name of the entry to remove
     * @throws IOException on error deleting the entry
     */
    void remove(String name) throws IOException;

    /**
     * Save all dirty (unsaved) data to the device.
     *
     * @throws IOException on write error
     */
    void flush() throws IOException;

}

redpajama_set_name: RedPajamaGithub


text:
//
// DefaultDirectoryResolver.cs
//
// Copyright (c) 2017 Couchbase, Inc 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.
//
#if __ANDROID__
using Android.Content;
using Couchbase.Lite.DI;

namespace Couchbase.Lite.Support
{
    internal sealed class DefaultDirectoryResolver : IDefaultDirectoryResolver
    {
        private readonly Context _context;

        public DefaultDirectoryResolver(Context context)
        {
            _context = context;
        }

        public string DefaultDirectory()
        {
            return _context.FilesDir.AbsolutePath;
        }
    }
}
#endif


text:
import Component from '@ember/component';
import { set } from '@ember/object';
import layout from './template';

export default Component.extend({
  layout,
  searchFields: ['displayName', 'id:prefix', 'displayState'],

  actions: {
    clearSearch() {
      set(this, 'searchText', '');
    },
  },
});


text:
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import yahoofinance.Stock;
import yahoofinance.YahooFinance;
import yahoofinance.histquotes.HistoricalQuote;
import yahoofinance.histquotes.Interval;

public class Symbol extends Stock {

	private final int DAYS_HISTORY = 2000;

	// Keep historical data that we have already pulled to speed up getHistory method
	private List<HistoricalQuote> history = new ArrayList<>(0);

	public Symbol(String symbol) throws IOException {
		super(symbol);
		Stock stock = YahooFinance.get(symbol);
		setQuote(stock.getQuote());
		setStats(stock.getStats());
		setDividend(stock.getDividend());

		// Set history
		Calendar from = Calendar.getInstance();
		from.add(Calendar.DAY_OF_MONTH, -DAYS_HISTORY);

		// Update list of historical data with new historical data
		history = getHistory(from, Interval.DAILY);
	}

	/**
	 * Returns list of historical quotes using days from most to least recent
	 * @author Michael Bick
	 * @param daysAgo days ago the first quote is from
	 * @param days amount of days of historical quotes
	 * @return list of historical quotes from time period
	 * @throws IOException
	 */
	public List<HistoricalQuote> getHistory(int daysAgo, int days) throws IOException {
		// Create an integer to hold the farthest back day requested
		int fromDay = daysAgo + days;

		// Filter the list down to what we need
		// Only subtract 1 from first parameter because it is inclusive
		return history.subList(daysAgo, fromDay);
	}

	/**
	 * Returns one day of historical information
	 * @author Michael Bick
	 * @param daysAgo amount of days ago to get information from
	 * @return historical quote from a given amount of days ago
	 * @throws IOException
	 */
	public HistoricalQuote getDay(int daysAgo) throws IOException {
		return getHistory(daysAgo, 1).get(0);
	}

	/**
	 * Returns a historical adjusted closing price of a stock
	 * @author Michael Bick
	 * @param daysAgo amount of days ago to get the closing price from
	 * @return historical adjusted closing price
	 * @throws IOException
	 */
	public BigDecimal getAdjClose(int daysAgo) throws IOException {
		return getDay(daysAgo).getAdjClose();
	}

	/**
	 * Returns a historical volume of shares traded
	 * @author Michael Bick
	 * @param daysAgo amount of days ago to get the volume from
	 * @return volume of shares traded
	 * @throws IOException
	 */
	public long getVolume(int daysAgo) throws IOException {
		return getDay(daysAgo).getVolume();
	}

	/**
	 *  Returns a moving average from a stock's history
	 * @author Michael Bick
	 * @param daysAgo amount of days ago the moving average is from
	 * @param days amount of days to use in the moving average
	 * @return moving average
	 * @throws IOException
	 */
	public BigDecimal getMA(int daysAgo, int days) throws IOException {
		// Gets historical quotes
		List<HistoricalQuote> quotes = getHistory(daysAgo, days);

		// Calculate the moving average
		BigDecimal ma = new BigDecimal(0);
		for (HistoricalQuote quote : quotes) {
			ma = ma.add(quote.getAdjClose());
			// System.out.println(quote.getAdjClose());
			// System.out.println(ma);
		}
		ma = ma.divide(new BigDecimal(quotes.size()), 2, RoundingMode.HALF_UP); // Rounds the "regular" way to 2 decimal places

		return ma;
	}

	public BigDecimal getPrice() {
		return getQuote().getPrice();
	}
	/*
	public BigDecimal getDayHigh() {
		return getQuote().getDayHigh();
	}

	public BigDecimal getDayLow() {
		return getQuote().getDayLow();
	}
	public BigDecimal getFtWkHigh(){
		return getQuote().getYearHigh();
	}
	public BigDecimal getFtWkLow(){
		return getQuote().getYearLow();
	}
	public BigDecimal getEPS() {
		return getStats().getEps();
	}
	public long getNumberOfShares() {
		return getStats().getSharesOutstanding();
	}
	public long getVolume() {
		return getQuote().getVolume();
	}
	*/
}


text:
<?php

declare(strict_types=1);

namespace Eelly\SDK\Data\Exception;

use Eelly\Exception\LogicException;

class EaTrackException extends LogicException
{
    public const FIELD_EMPTY = '字段名不能为空';
}


text:
///////////////////////////////////////////////////////////////////////////////
//
//  A parser for a comma separated list of numbers,
//  with positional error reporting
//  See the "Position Iterator" chapter in the User's Guide.
//
//  [ JCAB 9/28/2002 ]
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/classic_functor_parser.hpp>
#include <iostream>
#include <fstream>
#include <vector>

///////////////////////////////////////////////////////////////////////////////
using namespace std;
using namespace BOOST_SPIRIT_CLASSIC_NS;

///////////////////////////////////////////////////////////////////////////////
//
//  Our error reporting parsers
//
///////////////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& out, file_position const& lc)
{
    return out <<
            "\nFile:\t" << lc.file <<
            "\nLine:\t" << lc.line <<
            "\nCol:\t" << lc.column << endl;
}

struct error_report_parser {
    char const* eol_msg;
    char const* msg;

    error_report_parser(char const* eol_msg_, char const* msg_):
        eol_msg(eol_msg_),
        msg    (msg_)
    {}

    typedef nil_t result_t;

    template <typename ScannerT>
    int
    operator()(ScannerT const& scan, result_t& /*result*/) const
    {
        if (scan.at_end()) {
            if (eol_msg) {
                file_position fpos = scan.first.get_position();
                cerr << fpos << eol_msg << endl;
            }
        } else {
            if (msg) {
                file_position fpos = scan.first.get_position();
                cerr << fpos << msg << endl;
            }
        }

        return -1; // Fail.
    }

};
typedef functor_parser<error_report_parser> error_report_p;

error_report_p
error_badnumber_or_eol =
    error_report_parser(
        "Expecting a number, but found the end of the file\n",
        "Expecting a number, but found something else\n"
    );

error_report_p
error_badnumber =
    error_report_parser(
        0,
        "Expecting a number, but found something else\n"
    );

error_report_p
error_comma =
    error_report_parser(
        0,
        "Expecting a comma, but found something else\n"
    );

///////////////////////////////////////////////////////////////////////////////
//
//  Our comma separated list parser
//
///////////////////////////////////////////////////////////////////////////////
bool
parse_numbers(char const* filename, char const* str, vector<double>& v)
{
    typedef position_iterator<char const*> iterator_t;
    iterator_t begin(str, str + strlen(str), filename);
    iterator_t end;
    begin.set_tabchars(8);
    return parse(begin, end,

        //  Begin grammar
        (
            (real_p[push_back_a(v)] | error_badnumber)
         >> *(
                (',' | error_comma)
             >> (real_p[push_back_a(v)] | error_badnumber_or_eol)
            )
        )
        ,
        //  End grammar

        space_p).full;
}

////////////////////////////////////////////////////////////////////////////
//
//  Main program
//
////////////////////////////////////////////////////////////////////////////
int
main(int argc, char **argv)
{
    cout << "/////////////////////////////////////////////////////////\n\n";
    cout << "\tAn error-reporting parser for Spirit...\n\n";
    cout << "Parses a comma separated list of numbers from a file.\n";
    cout << "The numbers will be inserted in a vector of numbers\n\n";
    cout << "/////////////////////////////////////////////////////////\n\n";

    char str[65536];
    char const* filename;

    if (argc > 1) {
        filename = argv[1];
        ifstream file(filename);
        file.get(str, sizeof(str), '\0');
    } else {
        filename = "<cin>";
        cin.get(str, sizeof(str), '\0');
    }

    vector<double> v;
    if (parse_numbers(filename, str, v))
    {
        cout << "-------------------------\n";
        cout << "Parsing succeeded\n";
        cout << str << " Parses OK: " << endl;

        for (vector<double>::size_type i = 0; i < v.size(); ++i)
            cout << i << ": " << v[i] << endl;

        cout << "-------------------------\n";
    }
    else
    {
        cout << "-------------------------\n";
        cout << "Parsing failed\n";
        cout << "-------------------------\n";
    }

    cout << "Bye... :-) \n\n";
    return 0;
}


text:
using Xunit;
using System;
using System.Linq;

namespace Test
{
    public class SumTests
    {
        //
        // Sum
        //
        [Fact]
        public static void RunSumTests()
        {
            int count1 = 0, count2 = 1024 * 8, count3 = 1024 * 16, count4 = 1024 * 1024;

            Action<int>[] testActions = new Action<int>[]
            {
                (count) => RunSumTest1<int>(count),
                (count) => RunSumTest1<int?>(count),
                (count) => RunSumTest1<long>(count),
                (count) => RunSumTest1<long?>(count),
                (count) => RunSumTest1<float>(count),
                (count) => RunSumTest1<float?>(count),
                (count) => RunSumTest1<double>(count),
                (count) => RunSumTest1<double?>(count),
                (count) => RunSumTest1<decimal>(count),
                (count) => RunSumTest1<decimal?>(count)
            };

            for (int i = 0; i < testActions.Length; i++)
            {
                bool isLong = i == 2 || i == 3;
                bool isFloat = i == 4 || i == 5;

                testActions[i](count1);
                testActions[i](count2);
                if (!isFloat)
                    testActions[i](count3);
                if (isLong)
                    testActions[i](count4);
            }
        }

        [Fact]
        public static void FloatLimitationTest()
        {
            float[] elements = new[] { 16777220F, 1F, 1F, 1F, 1F, 1F, 1F, };
            Assert.Equal(16777226F, elements.AsParallel().Sum());
            Assert.Equal((float?)16777226F, elements.AsParallel().Sum(x => (float?)x));
        }

        private static void RunSumTest1<T>(int count)
        {
            if (typeof(T) == typeof(int))
            {
                int expectSum = 0;
                int[] ints = new int[count];
                for (int i = 0; i < ints.Length; i++)
                {
                    ints[i] = i;
                    expectSum += i;
                }

                int realSum = ints.AsParallel().Sum();
                if (!expectSum.Equals(realSum))
                    Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}):  FAILED.  > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
            }
            else if (typeof(T) == typeof(long))
            {
                long expectSum = 0;
                long[] longs = new long[count];
                for (int i = 0; i < longs.Length; i++)
                {
                    longs[i] = i;
                    expectSum += i;
                }

                long realSum = longs.AsParallel().Sum();
                if (!expectSum.Equals(realSum))
                    Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}):  FAILED.  > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
            }
            else if (typeof(T) == typeof(float))
            {
                float expectSum = 0;
                float[] floats = new float[count];
                for (int i = 0; i < floats.Length; i++)
                {
                    float val = (float)i / 10;
                    floats[i] = val;
                    expectSum += val;
                }

                float realSum = floats.AsParallel().Sum();
                if (!AreEpsEqual(expectSum, realSum))
                    Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}):  FAILED.  > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
            }
            else if (typeof(T) == typeof(double))
            {
                double expectSum = 0;
                double[] doubles = new double[count];
                for (int i = 0; i < doubles.Length; i++)
                {
                    double val = (double)i / 100;
                    doubles[i] = val;
                    expectSum += val;
                }

                double realSum = doubles.AsParallel().Sum();
                if (!AreEpsEqual(expectSum, realSum))
                    Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}):  FAILED.  > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
            }
            else if (typeof(T) == typeof(decimal))
            {
                decimal expectSum = 0;
                decimal[] decimals = new decimal[count];
                for (int i = 0; i < decimals.Length; i++)
                {
                    decimal val = (decimal)i / 100;
                    decimals[i] = val;
                    expectSum += val;
                }

                decimal realSum = decimals.AsParallel().Sum();
                //round the numbers for the comparison
                if (!AreEpsEqual(expectSum, realSum))
                    Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}):  FAILED.  > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
            }
            else if (typeof(T) == typeof(int?))
            {
                int? expectSum = 0;
                int?[] ints = new int?[count];
                for (int i = 0; i < ints.Length; i++)
                {
                    ints[i] = i;
                    expectSum += i;
                }

                int? realSum = ints.AsParallel().Sum();

                if (!expectSum.Equals(realSum))
                    Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}):  FAILED.  > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
            }
            else if (typeof(T) == typeof(long?))
            {
                long? expectSum = 0;
                long?[] longs = new long?[count];
                for (int i = 0; i < longs.Length; i++)
                {
                    longs[i] = i;
                    expectSum += i;
                }

                long? realSum = longs.AsParallel().Sum();

                if (!expectSum.Equals(realSum))
                    Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}):  FAILED.  > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
            }
            else if (typeof(T) == typeof(float?))
            {
                float? expectSum = 0;
                float?[] floats = new float?[count];
                for (int i = 0; i < floats.Length; i++)
                {
                    float? val = (float)i / 10;
                    floats[i] = val;
                    expectSum += val;
                }

                bool passed = true;
                float? realSum = floats.AsParallel().Sum();

                if (!expectSum.HasValue || !realSum.HasValue)
                    passed = expectSum.HasValue.Equals(realSum.HasValue);
                else
                    passed = AreEpsEqual(expectSum.Value, realSum.Value);

                if (!passed)
                    Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}):  FAILED.  > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
            }
            else if (typeof(T) == typeof(double?))
            {
                double? expectSum = 0;
                double?[] doubles = new double?[count];
                for (int i = 0; i < doubles.Length; i++)
                {
                    double? val = (double)i / 100;
                    doubles[i] = val;
                    expectSum += val;
                }

                double? realSum = doubles.AsParallel().Sum();

                bool passed = true;
                if (!expectSum.HasValue || !realSum.HasValue)
                    passed = expectSum.HasValue.Equals(realSum.HasValue);
                else
                    passed = AreEpsEqual(expectSum.Value, realSum.Value);

                if (!passed)
                    Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}):  FAILED.  > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
            }
            else if (typeof(T) == typeof(decimal?))
            {
                decimal? expectSum = 0;
                decimal?[] decimals = new decimal?[count];
                for (int i = 0; i < decimals.Length; i++)
                {
                    decimal? val = (decimal)i / 100;
                    decimals[i] = val;
                    expectSum += val;
                }

                decimal? realSum = decimals.AsParallel().Sum();

                bool passed = true;
                if (!expectSum.HasValue || !realSum.HasValue)
                    passed = expectSum.HasValue.Equals(realSum.HasValue);
                else
                    passed = AreEpsEqual(expectSum.Value, realSum.Value);

                if (!passed)
                    Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}):  FAILED.  > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
            }
        }

        //
        // Tests summing an ordered list.
        //
        private static void RunSumTestOrderBy1(int count)
        {
            int expectSum = 0;
            int[] ints = new int[count];
            for (int i = 0; i < ints.Length; i++)
            {
                ints[i] = i;
                expectSum += i;
            }

            int realSum = ints.AsParallel().OrderBy(x => x).Sum();

            if (realSum != expectSum)
                Assert.True(false, string.Format("RunSumTestOrderBy1(count={2}): FAILED.  > Expect: {0}, real: {1}", expectSum, realSum, count));
        }

        #region Helper Methods

        /// <summary>
        /// Returns whether two float values are approximately equal.
        /// The values compare as equal if either the relative or absolute
        /// error is less than 1e-4f.
        /// </summary>
        internal static bool AreEpsEqual(float a, float b)
        {
            const float eps = 1e-4f;

            float absA = a >= 0 ? a : -a;
            float absB = b >= 0 ? b : -b;
            float maximumAB = absA >= absB ? absA : absB;
            const float oneF = 1.0f;
            float maxABOneF = oneF >= maximumAB ? oneF : maximumAB;

            float absASubB = (a - b) >= 0 ? (a - b) : -(a - b);
            bool isEqual = (absASubB / maxABOneF) < eps;
            return isEqual;
        }

        /// <summary>
        /// Returns whether two double values are approximately equal.
        /// The values compare as equal if either the relative or absolute
        /// error is less than 1e-9.
        /// </summary>
        internal static bool AreEpsEqual(double a, double b)
        {
            const double eps = 1e-9;

            double absA = a >= 0 ? a : -a;
            double absB = b >= 0 ? b : -b;
            double maximumAB = absA >= absB ? absA : absB;
            const double oneD = 1.0;
            double maxABOne = oneD >= maximumAB ? oneD : maximumAB;

            double absASubB = (a - b) >= 0 ? (a - b) : -(a - b);
            bool isEqual = (absASubB / maxABOne) < eps;
            return isEqual;
        }

        /// <summary>
        /// Returns whether two decimal values are approximately equal.
        /// The values compare as equal if either the relative or absolute
        /// error is less than 1e-9m.
        /// </summary>
        internal static bool AreEpsEqual(decimal a, decimal b)
        {
            const decimal eps = 1e-9m;

            decimal absA = a >= 0 ? a : -a;
            decimal absB = b >= 0 ? b : -b;
            decimal maximumAB = absA >= absB ? absA : absB;
            const decimal oneD = 1.0m;
            decimal maxABOne = oneD >= maximumAB ? oneD : maximumAB;

            decimal absASubB = (a - b) >= 0 ? (a - b) : -(a - b);
            bool isEqual = (absASubB / maxABOne) < eps;

            return isEqual;
        }
        #endregion
    }
}


text:
package blackmagic

import (
	"testing"

	"github.com/remogatto/prettytest"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

// Setup

type DayTestSuite struct {
	prettytest.Suite
}

func TestRunner(t *testing.T) {
	prettytest.RunWithFormatter(t, new(prettytest.TDDFormatter), new(DayTestSuite))
}

// EndSetup

type mockCollection struct{}

func (c *mockCollection) All(map[string]interface{}, *[]interface{}) error { return nil }
func (c *mockCollection) First(map[string]interface{}, *interface{}) error { return nil }
func (c *mockCollection) FindId(bson.ObjectId, *interface{}) error         { return nil }
func (c *mockCollection) UpdateId(day bson.ObjectId, update map[string]interface{}) error {
	return nil
}
func (c *mockCollection) UpsertId(id interface{}, update interface{}) (info *mgo.ChangeInfo, err error) {
	return nil, nil
}

type mockDatabase struct{}

func (db *mockDatabase) Connect() error { return nil }
func (db *mockDatabase) Collection(collectionName string) (Collection, error) {
	if collectionName == "days" {
		return &mockCollection{}, nil
	}
	return nil, nil
}

func (s *DayTestSuite) TestShouldAddNewForecast() {
	day := &Day{}
	forecast := &Forecast{Id: bson.NewObjectId()}

	err := day.AddForecast(forecast, &mockDatabase{})
	s.Equal(err, nil)
}


text:
using ChinookWebAPIOData.Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.OData;

namespace ChinookWebAPIOData.Controllers
{
    public class MediaTypesController : ODataController
    {
        ChinookModel db = new ChinookModel();
        private bool MediaTypeExists(int key) => db.MediaTypes.Any(p => p.MediaTypeId == key);
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        [EnableQuery]
        public IQueryable<MediaType> Get() => db.MediaTypes;
        [EnableQuery]
        public SingleResult<MediaType> Get([FromODataUri] int key)
        {
            IQueryable<MediaType> result = db.MediaTypes.Where(p => p.MediaTypeId == key);
            return SingleResult.Create(result);
        }

        public async Task<IHttpActionResult> Post(MediaType MediaType)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            db.MediaTypes.Add(MediaType);
            await db.SaveChangesAsync();
            return Created(MediaType);
        }

        public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<MediaType> MediaType)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var entity = await db.MediaTypes.FindAsync(key);
            if (entity == null)
            {
                return NotFound();
            }
            MediaType.Patch(entity);
            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MediaTypeExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return Updated(entity);
        }
        public async Task<IHttpActionResult> Put([FromODataUri] int key, MediaType update)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            if (key != update.MediaTypeId)
            {
                return BadRequest();
            }
            db.Entry(update).State = EntityState.Modified;
            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MediaTypeExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return Updated(update);
        }

        public async Task<IHttpActionResult> Delete([FromODataUri] int key)
        {
            var MediaType = await db.MediaTypes.FindAsync(key);
            if (MediaType == null)
            {
                return NotFound();
            }
            db.MediaTypes.Remove(MediaType);
            await db.SaveChangesAsync();
            return StatusCode(HttpStatusCode.NoContent);
        }

        [EnableQuery]
        public IQueryable<Track> GetTracks([FromODataUri] int key) => db.MediaTypes.Where(m => m.MediaTypeId == key).SelectMany(m => m.Tracks);

        public async Task<IHttpActionResult> DeleteRef([FromODataUri] int key,
        [FromODataUri] string relatedKey, string navigationProperty)
        {
            var mediaType = await db.MediaTypes.SingleOrDefaultAsync(p => p.MediaTypeId == key);
            if (mediaType == null)
            {
                return NotFound();
            }

            switch (navigationProperty)
            {
                case "Tracks":
                    var trackId = Convert.ToInt32(relatedKey);
                    var track = await db.Tracks.SingleOrDefaultAsync(p => p.TrackId == trackId);

                    if (track == null)
                    {
                        return NotFound();
                    }
                    track.MediaType = null;
                    break;
                default:
                    return StatusCode(HttpStatusCode.NotImplemented);

            }
            await db.SaveChangesAsync();

            return StatusCode(HttpStatusCode.NoContent);
        }
    }
}