text:
using System.Diagnostics;
using System.Data.SqlClient;
using System.Reflection;

namespace System.Data.Common
{
    internal static partial class DbConnectionStringBuilderUtil
    {
        internal static bool ConvertToBoolean(object value)
        {
            Debug.Assert(null != value, "ConvertToBoolean(null)");
            string svalue = (value as string);
            if (null != svalue)
            {
                if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes"))
                    return true;
                else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no"))
                    return false;
                else
                {
                    string tmp = svalue.Trim();  // Remove leading & trailing whitespace.
                    if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes"))
                        return true;
                    else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no"))
                        return false;
                }
                return bool.Parse(svalue);
            }
            try
            {
                return Convert.ToBoolean(value);
            }
            catch (InvalidCastException e)
            {
                throw ADP.ConvertFailed(value.GetType(), typeof(bool), e);
            }
        }

        internal static bool ConvertToIntegratedSecurity(object value)
        {
            Debug.Assert(null != value, "ConvertToIntegratedSecurity(null)");
            string svalue = (value as string);
            if (null != svalue)
            {
                if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes"))
                    return true;
                else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no"))
                    return false;
                else
                {
                    string tmp = svalue.Trim();  // Remove leading & trailing whitespace.
                    if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes"))
                        return true;
                    else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no"))
                        return false;
                }
                return bool.Parse(svalue);
            }
            try
            {
                return Convert.ToBoolean(value);
            }
            catch (InvalidCastException e)
            {
                throw ADP.ConvertFailed(value.GetType(), typeof(bool), e);
            }
        }

        internal static int ConvertToInt32(object value)
        {
            try
            {
                return Convert.ToInt32(value);
            }
            catch (InvalidCastException e)
            {
                throw ADP.ConvertFailed(value.GetType(), typeof(int), e);
            }
        }

        internal static string ConvertToString(object value)
        {
            try
            {
                return Convert.ToString(value);
            }
            catch (InvalidCastException e)
            {
                throw ADP.ConvertFailed(value.GetType(), typeof(string), e);
            }
        }

        private const string ApplicationIntentReadWriteString = "ReadWrite";
        private const string ApplicationIntentReadOnlyString = "ReadOnly";

        internal static bool TryConvertToApplicationIntent(string value, out ApplicationIntent result)
        {
            Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed");
            Debug.Assert(null != value, "TryConvertToApplicationIntent(null,...)");

            if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadOnlyString))
            {
                result = ApplicationIntent.ReadOnly;
                return true;
            }
            else if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadWriteString))
            {
                result = ApplicationIntent.ReadWrite;
                return true;
            }
            else
            {
                result = DbConnectionStringDefaults.ApplicationIntent;
                return false;
            }
        }

        internal static bool IsValidApplicationIntentValue(ApplicationIntent value)
        {
            Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed");
            return value == ApplicationIntent.ReadOnly || value == ApplicationIntent.ReadWrite;
        }

        internal static string ApplicationIntentToString(ApplicationIntent value)
        {
            Debug.Assert(IsValidApplicationIntentValue(value));
            if (value == ApplicationIntent.ReadOnly)
            {
                return ApplicationIntentReadOnlyString;
            }
            else
            {
                return ApplicationIntentReadWriteString;
            }
        }

        /// <summary>
        /// This method attempts to convert the given value tp ApplicationIntent enum. The algorithm is:
        /// * if the value is from type string, it will be matched against ApplicationIntent enum names only, using ordinal, case-insensitive comparer
        /// * if the value is from type ApplicationIntent, it will be used as is
        /// * if the value is from integral type (SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64), it will be converted to enum
        /// * if the value is another enum or any other type, it will be blocked with an appropriate ArgumentException
        ///
        /// in any case above, if the converted value is out of valid range, the method raises ArgumentOutOfRangeException.
        /// </summary>
        /// <returns>application intent value in the valid range</returns>
        internal static ApplicationIntent ConvertToApplicationIntent(string keyword, object value)
        {
            Debug.Assert(null != value, "ConvertToApplicationIntent(null)");
            string sValue = (value as string);
            ApplicationIntent result;
            if (null != sValue)
            {
                // We could use Enum.TryParse<ApplicationIntent> here, but it accepts value combinations like
                // "ReadOnly, ReadWrite" which are unwelcome here
                // Also, Enum.TryParse is 100x slower than plain StringComparer.OrdinalIgnoreCase.Equals method.

                if (TryConvertToApplicationIntent(sValue, out result))
                {
                    return result;
                }

                // try again after remove leading & trailing whitespace.
                sValue = sValue.Trim();
                if (TryConvertToApplicationIntent(sValue, out result))
                {
                    return result;
                }

                // string values must be valid
                throw ADP.InvalidConnectionOptionValue(keyword);
            }
            else
            {
                // the value is not string, try other options
                ApplicationIntent eValue;

                if (value is ApplicationIntent)
                {
                    // quick path for the most common case
                    eValue = (ApplicationIntent)value;
                }
                else if (value.GetType().GetTypeInfo().IsEnum)
                {
                    // explicitly block scenarios in which user tries to use wrong enum types, like:
                    // builder["ApplicationIntent"] = EnvironmentVariableTarget.Process;
                    // workaround: explicitly cast non-ApplicationIntent enums to int
                    throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), null);
                }
                else
                {
                    try
                    {
                        // Enum.ToObject allows only integral and enum values (enums are blocked above), raising ArgumentException for the rest
                        eValue = (ApplicationIntent)Enum.ToObject(typeof(ApplicationIntent), value);
                    }
                    catch (ArgumentException e)
                    {
                        // to be consistent with the messages we send in case of wrong type usage, replace
                        // the error with our exception, and keep the original one as inner one for troubleshooting
                        throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), e);
                    }
                }

                // ensure value is in valid range
                if (IsValidApplicationIntentValue(eValue))
                {
                    return eValue;
                }
                else
                {
                    throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)eValue);
                }
            }
        }
    }

    internal static partial class DbConnectionStringDefaults
    {
        // all
        // internal const string NamedConnection = "";

        // SqlClient
        internal const ApplicationIntent ApplicationIntent = System.Data.SqlClient.ApplicationIntent.ReadWrite;
        internal const string ApplicationName = "Core .Net SqlClient Data Provider";
        internal const string AttachDBFilename = "";
        internal const int ConnectTimeout = 15;
        internal const string CurrentLanguage = "";
        internal const string DataSource = "";
        internal const bool Encrypt = false;
        internal const bool Enlist = true;
        internal const string FailoverPartner = "";
        internal const string InitialCatalog = "";
        internal const bool IntegratedSecurity = false;
        internal const int LoadBalanceTimeout = 0; // default of 0 means don't use
        internal const bool MultipleActiveResultSets = false;
        internal const bool MultiSubnetFailover = false;
        internal const int MaxPoolSize = 100;
        internal const int MinPoolSize = 0;
        internal const int PacketSize = 8000;
        internal const string Password = "";
        internal const bool PersistSecurityInfo = false;
        internal const bool Pooling = true;
        internal const bool TrustServerCertificate = false;
        internal const string TypeSystemVersion = "Latest";
        internal const string UserID = "";
        internal const bool UserInstance = false;
        internal const bool Replication = false;
        internal const string WorkstationID = "";
        internal const string TransactionBinding = "Implicit Unbind";
        internal const int ConnectRetryCount = 1;
        internal const int ConnectRetryInterval = 10;
    }

    internal static partial class DbConnectionStringKeywords
    {
        // all
        // internal const string NamedConnection = "Named Connection";

        // SqlClient
        internal const string ApplicationIntent = "ApplicationIntent";
        internal const string ApplicationName = "Application Name";
        internal const string AsynchronousProcessing = "Asynchronous Processing";
        internal const string AttachDBFilename = "AttachDbFilename";
        internal const string ConnectTimeout = "Connect Timeout";
        internal const string ConnectionReset = "Connection Reset";
        internal const string ContextConnection = "Context Connection";
        internal const string CurrentLanguage = "Current Language";
        internal const string Encrypt = "Encrypt";
        internal const string FailoverPartner = "Failover Partner";
        internal const string InitialCatalog = "Initial Catalog";
        internal const string MultipleActiveResultSets = "MultipleActiveResultSets";
        internal const string MultiSubnetFailover = "MultiSubnetFailover";
        internal const string NetworkLibrary = "Network Library";
        internal const string PacketSize = "Packet Size";
        internal const string Replication = "Replication";
        internal const string TransactionBinding = "Transaction Binding";
        internal const string TrustServerCertificate = "TrustServerCertificate";
        internal const string TypeSystemVersion = "Type System Version";
        internal const string UserInstance = "User Instance";
        internal const string WorkstationID = "Workstation ID";
        internal const string ConnectRetryCount = "ConnectRetryCount";
        internal const string ConnectRetryInterval = "ConnectRetryInterval";

        // common keywords (OleDb, OracleClient, SqlClient)
        internal const string DataSource = "Data Source";
        internal const string IntegratedSecurity = "Integrated Security";
        internal const string Password = "Password";
        internal const string Driver = "Driver";
        internal const string PersistSecurityInfo = "Persist Security Info";
        internal const string UserID = "User ID";

        // managed pooling (OracleClient, SqlClient)
        internal const string Enlist = "Enlist";
        internal const string LoadBalanceTimeout = "Load Balance Timeout";
        internal const string MaxPoolSize = "Max Pool Size";
        internal const string Pooling = "Pooling";
        internal const string MinPoolSize = "Min Pool Size";
#if netcoreapp
        internal const string PoolBlockingPeriod = "PoolBlockingPeriod";
#endif
    }

    internal static class DbConnectionStringSynonyms
    {
        //internal const string AsynchronousProcessing = Async;
        internal const string Async = "async";

        //internal const string ApplicationName        = APP;
        internal const string APP = "app";

        //internal const string AttachDBFilename       = EXTENDEDPROPERTIES+","+INITIALFILENAME;
        internal const string EXTENDEDPROPERTIES = "extended properties";
        internal const string INITIALFILENAME = "initial file name";

        //internal const string ConnectTimeout         = CONNECTIONTIMEOUT+","+TIMEOUT;
        internal const string CONNECTIONTIMEOUT = "connection timeout";
        internal const string TIMEOUT = "timeout";

        //internal const string CurrentLanguage        = LANGUAGE;
        internal const string LANGUAGE = "language";

        //internal const string OraDataSource          = SERVER;
        //internal const string SqlDataSource          = ADDR+","+ADDRESS+","+SERVER+","+NETWORKADDRESS;
        internal const string ADDR = "addr";
        internal const string ADDRESS = "address";
        internal const string SERVER = "server";
        internal const string NETWORKADDRESS = "network address";

        //internal const string InitialCatalog         = DATABASE;
        internal const string DATABASE = "database";

        //internal const string IntegratedSecurity     = TRUSTEDCONNECTION;
        internal const string TRUSTEDCONNECTION = "trusted_connection"; // underscore introduced in Everett

        //internal const string LoadBalanceTimeout     = ConnectionLifetime;
        internal const string ConnectionLifetime = "connection lifetime";

        //internal const string NetworkLibrary         = NET+","+NETWORK;
        internal const string NET = "net";
        internal const string NETWORK = "network";

        //internal const string Password               = Pwd;
        internal const string Pwd = "pwd";

        //internal const string PersistSecurityInfo    = PERSISTSECURITYINFO;
        internal const string PERSISTSECURITYINFO = "persistsecurityinfo";

        //internal const string UserID                 = UID+","+User;
        internal const string UID = "uid";
        internal const string User = "user";

        //internal const string WorkstationID          = WSID;
        internal const string WSID = "wsid";
    }
}


text:
package com.mmtechco.surface.ui;

public interface ObserverScreen {
	void setStatus(String status);
	String getStatus();
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef VISIBILITYMAP_H
#define VISIBILITYMAP_H

#include "utils/relcache.h"
#include "storage/buf.h"
#include "storage/itemptr.h"
#include "access/xlogdefs.h"

extern void visibilitymap_clear(Relation rel, BlockNumber heapBlk);
extern void visibilitymap_pin(Relation rel, BlockNumber heapBlk,
				  Buffer *vmbuf);
extern void visibilitymap_set(Relation rel, BlockNumber heapBlk,
				  XLogRecPtr recptr, Buffer *vmbuf);
extern bool visibilitymap_test(Relation rel, BlockNumber heapBlk, Buffer *vmbuf);
extern void visibilitymap_truncate(Relation rel, BlockNumber heapblk);

#endif   /* VISIBILITYMAP_H */


text:
package org.springframework.boot.actuate.endpoint;

import java.util.Map;

import org.springframework.boot.actuate.endpoint.invoke.OperationInvoker;
import org.springframework.util.Assert;

/**
 * The context for the {@link OperationInvoker invocation of an operation}.
 *
 * @author Andy Wilkinson
 * @since 2.0.0
 */
public class InvocationContext {

	private final SecurityContext securityContext;

	private final Map<String, Object> arguments;

	/**
	 * Creates a new context for an operation being invoked by the given {@code principal}
	 * with the given available {@code arguments}.
	 * @param securityContext the current security context. Never {@code null}
	 * @param arguments the arguments available to the operation. Never {@code null}
	 */
	public InvocationContext(SecurityContext securityContext,
			Map<String, Object> arguments) {
		Assert.notNull(securityContext, "SecurityContext must not be null");
		Assert.notNull(arguments, "Arguments must not be null");
		this.securityContext = securityContext;
		this.arguments = arguments;
	}

	public SecurityContext getSecurityContext() {
		return this.securityContext;
	}

	public Map<String, Object> getArguments() {
		return this.arguments;
	}

}


text:
// C++ Standard Libraries
#include <cstdlib>

// Eigen matrix library
#include "Eigen/Core"

// Darwin library
#include "drwnBase.h"
#include "drwnEngine.h"

// Lua library
#include "lua.hpp"

// Plugin library
#include "drwnLuaNodes.h"
#include "drwnLuaShell.h"

using namespace std;
using namespace Eigen;

// drwnLuaNode ------------------------------------------------------------

drwnLuaNode::drwnLuaNode(const char *name, drwnGraph *owner) :
    drwnNode(name, owner), _nInputs(1), _nOutputs(1), _colour(-1), _luaEngine(NULL)
{
    _nVersion = 100;
    _desc = string("Interface to Lua (") + string(LUA_RELEASE) + string(")");

    // declare ports
    _inputPorts.push_back(new drwnInputPort(this, "dataIn", "N-by-D data matrix"));
    _outputPorts.push_back(new drwnOutputPort(this, "dataOut", "N-by-D data matrix"));

    // declare propertys
    declareProperty("numInputs", new drwnIntegerProperty(&_nInputs));
    declareProperty("numOutputs", new drwnIntegerProperty(&_nOutputs));
    declareProperty("fwdFunction", new drwnFilenameProperty(&_fwdFcnName));
    declareProperty("bckFunction", new drwnFilenameProperty(&_bckFcnName));
    declareProperty("initFunction", new drwnFilenameProperty(&_initFcnName));
    declareProperty("estFunction", new drwnFilenameProperty(&_estFcnName));
    declareProperty("colour", new drwnIntegerProperty(&_colour));
    declareProperty("theta", new drwnMatrixProperty(&_theta));
}

drwnLuaNode::drwnLuaNode(const drwnLuaNode& node) :
    drwnNode(node), _nInputs(node._nInputs), _nOutputs(node._nOutputs),
    _fwdFcnName(node._fwdFcnName), _bckFcnName(node._bckFcnName),
    _initFcnName(node._initFcnName), _estFcnName(node._estFcnName),
    _colour(node._colour), _theta(node._theta), _luaEngine(NULL)
{
    // declare propertys
    declareProperty("numInputs", new drwnIntegerProperty(&_nInputs));
    declareProperty("numOutputs", new drwnIntegerProperty(&_nOutputs));
    declareProperty("fwdFunction", new drwnFilenameProperty(&_fwdFcnName));
    declareProperty("bckFunction", new drwnFilenameProperty(&_bckFcnName));
    declareProperty("initFunction", new drwnFilenameProperty(&_initFcnName));
    declareProperty("estFunction", new drwnFilenameProperty(&_estFcnName));
    declareProperty("colour", new drwnIntegerProperty(&_colour));
    declareProperty("theta", new drwnMatrixProperty(&_theta));
}

drwnLuaNode::~drwnLuaNode()
{
    // close the lua engine
    if (_luaEngine != NULL) {
        lua_close(_luaEngine);
    }
}

// i/o
bool drwnLuaNode::load(drwnXMLNode& xml)
{
    drwnNode::load(xml);
    updatePorts();
    return true;
}

// gui
void drwnLuaNode::showWindow()
{
    if (_luaEngine == NULL) {
        _luaEngine = lua_open();
        luaL_openlibs(_luaEngine);
    }
    DRWN_ASSERT_MSG(_luaEngine != NULL, "can't initialize the Lua interpreter");

    if (_window != NULL) {
        _window->Show();
    } else {
        _window = new drwnLuaShell(this, _luaEngine);
        _window->Show();
    }
    updateWindow();
}

/*
void drwnLuaNode::hideWindow()
{
    if (_luaEngine != NULL) {
        lua_close(_luaEngine);
        _luaEngine = NULL;
    }

    if (_window != NULL) {
        delete _window;
        _window = NULL;
    }
}
*/

void drwnLuaNode::updateWindow()
{
    if (_luaEngine == NULL)
        return;
    if ((_window == NULL) || (!_window->IsShown()))
        return;

    // TODO: copy parameters?
}

void drwnLuaNode::evaluateForwards()
{
    // clear output tables and then update forwards
    clearOutput();
    updateForwards();
}

void drwnLuaNode::updateForwards()
{
    // error checking
    if (_fwdFcnName.empty()) {
        DRWN_LOG_ERROR("no forward function defined for node \"" << getName() << "\"");
        return;
    }

    if (!drwnFileExists(_fwdFcnName.c_str())) {
        DRWN_LOG_ERROR("can't find forward function \"" << _fwdFcnName << "\" required for node \"" << getName() << "\"");
        return;
    }

    // if no inputs, then execute as source node
    if (_nInputs == 0) {
        sourceUpdateForwards();
        return;
    }

    // check input tables
    for (int i = 0; i < _nInputs; i++) {
        drwnDataTable *tblIn = _inputPorts[i]->getTable();
        if (tblIn == NULL) {
            DRWN_LOG_WARNING("node " << getName() << " requires " << _nInputs << " inputs");
            return;
        }
    }

    // run Lua script on input records
    if (_luaEngine == NULL) {
        _luaEngine = lua_open();
        luaL_openlibs(_luaEngine);
    }

    // interate over input records
    vector<string> keys = _inputPorts[0]->getTable()->getKeys();
    DRWN_START_PROGRESS(getName().c_str(), keys.size());
    for (vector<string>::const_iterator it = keys.begin(); it != keys.end(); it++) {
        DRWN_INC_PROGRESS;

        // don't overwrite existing output records
        bool bKeyExists = true;
        for (int i = 0; i < _nOutputs; i++) {
            drwnDataTable *tblOut = _outputPorts[i]->getTable();
            if (!tblOut->hasKey(*it)) {
                bKeyExists = false;
                break;
            }
        }
        if (bKeyExists) continue;

        // TODO
        DRWN_TODO;
    }
    DRWN_END_PROGRESS;
}

void drwnLuaNode::sourceUpdateForwards()
{
    // TODO: run Lua script
    DRWN_TODO;
}

void drwnLuaNode::propertyChanged(const string& name)
{
    if ((name == string("numInputs")) || (name == string("numOutputs"))) {
        _nInputs = std::max(0, _nInputs);
        _nOutputs = std::max(0, _nOutputs);
        updatePorts();
    } else {
        drwnNode::propertyChanged(name);
    }
}

void drwnLuaNode::updatePorts()
{
    // re-assign input ports
    if (_nInputs != (int)_inputPorts.size()) {
        for (vector<drwnInputPort *>::iterator it = _inputPorts.begin();
             it != _inputPorts.end(); it++) {
            delete *it;
        }
        _inputPorts.clear();

        if (_nInputs == 1) {
            _inputPorts.push_back(new drwnInputPort(this, "dataIn", "N-by-D data matrix"));
        } else {
            for (int i = 0; i < _nInputs; i++) {
                string portName = string("dataIn") + toString(i);
                _inputPorts.push_back(new drwnInputPort(this, portName.c_str(), "N-by-D data matrix"));
            }
        }
    }

    // re-assign input ports
    if (_nOutputs != (int)_outputPorts.size()) {
        for (vector<drwnOutputPort *>::iterator it = _outputPorts.begin();
             it != _outputPorts.end(); it++) {
            delete *it;
        }
        _outputPorts.clear();

        if (_nOutputs == 1) {
            _outputPorts.push_back(new drwnOutputPort(this, "dataOut", "N-by-D data matrix"));
        } else {
            for (int i = 0; i < _nOutputs; i++) {
                string portName = string("dataOut") + toString(i);
                _outputPorts.push_back(new drwnOutputPort(this, portName.c_str(), "N-by-D data matrix"));
            }
        }
    }
}

// auto registration ---------------------------------------------------------

DRWN_AUTOREGISTERNODE("Custom", drwnLuaNode);


text:
package requestsresponses

/*GetPullRequestActivitiesParams contains all the parameters to send to the API endpoint
for the get pull request activities operation typically these are written to a http.Request
*/
type GetPullRequestActivitiesParams struct {
	/*Limit
	  Probably defaults to 25. It is a best practice to check the limit attribute on the response to see what limit has been applied.
	*/
	Limit         *int64
	Project       string
	PullRequestID int64
	Repo          string
}

type GetPullRequestsParams struct {
	/*Limit
	  Probably defaults to 25. It is a best practice to check the limit attribute on the response to see what limit has been applied.
	*/
	Limit *int64
	/*Order
	  NEWEST is as in newest first.
	*/
	Order   *string
	Project string
	Repo    string
	Role1   *string
	Role2   *string
	/*Start
	  The count of the result to start with, inclusive (I think).
	*/
	Start *int64
	/*State
	  You probably want to include this in, and probably as ALL to see everything (which you won't by default).
	*/
	State     *string
	Username1 *string
	Username2 *string
}


text:
using System.Collections.Generic;
using System.Linq;
using System.Data;
using Simple.Data.Extensions;

namespace Simple.Data.Ado
{
    using System;

    public static class DataReaderExtensions
    {
        public static IDictionary<string,object> ToDictionary(this IDataReader dataReader)
        {
            return dataReader.ToDictionary(dataReader.CreateDictionaryIndex());
        }

        public static IEnumerable<IDictionary<string, object>> ToDictionaries(this IDataReader reader)
        {
            using (reader)
            {
                return ToDictionariesImpl(reader).ToArray().AsEnumerable();
            }
        }

        public static IEnumerable<IEnumerable<IDictionary<string, object>>> ToMultipleDictionaries(this IDataReader reader)
        {
            using (reader)
            {
                return ToMultipleDictionariesImpl(reader).ToArray().AsEnumerable();
            }
        }

        private static IEnumerable<IEnumerable<IDictionary<string,object>>> ToMultipleDictionariesImpl(IDataReader reader)
        {
            do
            {
                yield return ToDictionariesImpl(reader).ToArray().AsEnumerable();
            } while (reader.NextResult());

        }

        private static IEnumerable<IDictionary<string,object>> ToDictionariesImpl(IDataReader reader)
        {
            var index = reader.CreateDictionaryIndex();
            var values = new object[reader.FieldCount];
            while (reader.Read())
            {
                reader.GetValues(values);

                ReplaceDbNullsWithClrNulls(values);

                yield return OptimizedDictionary.Create(index, values);
            }
        }

        private static void ReplaceDbNullsWithClrNulls(object[] values)
        {
            int dbNullIndex;
            while ((dbNullIndex = Array.IndexOf(values, DBNull.Value)) > -1)
            {
                values[dbNullIndex] = null;
            }
        }
    }
}


text:
package font

import "io/ioutil"

func buildDefault() ([]byte, error) {
	return ioutil.ReadFile("/usr/share/fonts/truetype/droid/DroidSans.ttf")
}

func buildMonospace() ([]byte, error) {
	return ioutil.ReadFile("/usr/share/fonts/truetype/droid/DroidSansMono.ttf")
}


text:
package org.openbakery.output;

import org.gradle.logging.StyledTextOutput;

/**
 * Created by rene on 06.08.14.
 */
public class ConsoleOutputAppender implements OutputAppender {

	private StyledTextOutput output;

	public ConsoleOutputAppender(StyledTextOutput output) {
		this.output = output;
	}

	@Override
	public void append(String line) {
		output.withStyle(StyledTextOutput.Style.Info).println(line);

	}

}


text:
typedef struct tagBITMAPFILEHEADER
{
	WORD  bfType;
	DWORD bfSize;
	WORD  bfReserved1;
	WORD  bfReserved2;
	DWORD bfOffBits;
} BITMAPFILEHEADER, *PBITMAPFILEHEADER;
typedef struct tagBITMAPINFOHEADER
{
	DWORD biSize;
	LONG biWidth;
	LONG biHeight;
	WORD biPlanes;
	WORD biBitCount;
	DWORD biCompression;
	DWORD biSizeImage;
	LONG biXPelsPerMeter;
	LONG biYPelsPerMeter;
	DWORD biClrUsed;
	DWORD biClrImportant;
} BITMAPINFOHEADER;
#endif

#include <iostream>

using namespace std;

Texture::~Texture(void)
{
	GLuint t;
	// free up all the textures
	for (map<int, string>::iterator it = textures.begin(); it != textures.end(); ++it)
	{
		t = static_cast<GLuint>(it->first);
		glDeleteTextures(static_cast<GLsizei>(1), &t);
	}
}

// Loads a bitmap into texture memory
int Texture::GetTexture(string fileName)
{
	for (map<int, string>::iterator ii = textures.begin(); ii != textures.end(); ++ii)
	{
		if (ii->second == fileName)
		{
			return ii->first;
		}
	}

	BITMAPFILEHEADER fileHeader;
	BITMAPINFOHEADER infoHeader;
	unsigned char *pixelBuffer;
	GLuint texObject;
	FILE *bitmapFile = fopen(fileName.c_str(), "r");

	// Check file opened
	if (bitmapFile == NULL)
	{
		printf("Error: Failed to open the file at path %s\n", fileName.c_str());
		delete[] bitmapFile;
		return -1;	// error
	}
	fread(&fileHeader, 14, 1, bitmapFile);

	// Check for valid window bitmap
	if (fileHeader.bfType != 0x4D42)
	{
		printf("Error: Trying to load %s it is in an invalid bitmap format.\n", fileName.c_str());
		fclose(bitmapFile);
		return -1;	// error
	}

	// read in file header
	fread(&infoHeader, sizeof(BITMAPINFOHEADER), 1, bitmapFile);

	// Check the image is at least RGB ... i.e 24 bits per pixel
	if (infoHeader.biBitCount < 24)
	{
		printf("Error: Trying to load %s.\nThe file is not in RGB or RGBA format.\nIt may be in grayscale format, open it in an image editor of your choice and change the image mode to RGB or RGBA.\n", fileName.c_str());
		fclose(bitmapFile);
		return -1;	// error
	}

	// ofset the pointer to the start of the pixel data
	fseek(bitmapFile, fileHeader.bfOffBits, SEEK_SET);

	// Read in the pixel data
	pixelBuffer = new unsigned char[infoHeader.biWidth * infoHeader.biHeight * (infoHeader.biBitCount / 8)];
	fread(pixelBuffer, sizeof(unsigned char), infoHeader.biWidth * infoHeader.biHeight * (infoHeader.biBitCount / 8), bitmapFile);

	// If texture is in ABGR format swizzle it into RGBA for openGL upload
	if (infoHeader.biBitCount == 32)
	{
		unsigned char c;
		for (int i = 0; i < infoHeader.biWidth * infoHeader.biHeight; i++)
		{
			c = pixelBuffer[i * 4];
			pixelBuffer[i * 4] = pixelBuffer[i * 4 + 3];
			pixelBuffer[i * 4 + 3] = c;
			c = pixelBuffer[i * 4 + 1];
			pixelBuffer[i * 4 + 1] = pixelBuffer[i * 4 + 2];
			pixelBuffer[i * 4 + 2] = c;
		}
	}

	// Enable texturing
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);

	// Generate a texture buffer
	glGenTextures(static_cast<GLsizei>(1), &texObject);

	// Bin to buffer
	glBindTexture(GL_TEXTURE_2D, texObject);

	// Set texture parameters
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	// Upload texture data
	glTexImage2D(GL_TEXTURE_2D, static_cast<GLint>(0), infoHeader.biBitCount == 32 ? GL_RGBA : GL_RGB,
		static_cast<GLsizei>(infoHeader.biWidth), static_cast<GLsizei>(infoHeader.biHeight),
		static_cast<GLint>(0), infoHeader.biBitCount == 32 ? GL_RGBA : GL_BGR_EXT, GL_UNSIGNED_BYTE,
		static_cast<GLvoid*>(pixelBuffer));

	// insert texture into texture list
	textures.insert(textures.end(), pair<int, string>(static_cast<int>(texObject), fileName));

	// Delete old copy of pixel data
	delete[] pixelBuffer;
	fclose(bitmapFile);
	glDisable(GL_TEXTURE_2D);

	return static_cast<int>(texObject);
}


text:
java_import org.lwjgl.opengl.Display
java_import org.lwjgl.opengl.DisplayMode
java_import org.lwjgl.opengl.GL11
java_import org.lwjgl.opengl.GL15
java_import org.lwjgl.opengl.GL20
java_import org.lwjgl.opengl.GL30
java_import org.lwjgl.BufferUtils

require "opengl/gl_utils"

#
# Let's display a triangle, with a gradient
class OpenGL::ShowTriangleGradient
	include OpenGL::GLUtils
	add_start

	# initialise
	def initialize

		@vertex_positions = [
			0.75, 0.75, 0.0, 1.0,
			0.75, -0.75, 0.0, 1.0,
			-0.75, -0.75, 0.0, 1.0,
		]

		create_display("I am a triangle! (with a gradient!)")

		#initialise the viewport
		GL11.gl_viewport(0, 0, Display.width, Display.height)

		@program_id = compile_program('basic_vertex.glsl', 'gradient_fragment.glsl')
		init_vertex_buffers

		render_loop { display }

		destroy_display

	end

	# display loop
	def display

		#set the colour to clear.
		GL11.gl_clear_color(0.0, 0.0, 0.0, 0.0)

		#clear the buffer. Remember that Java static types come back as Ruby Constants.
		GL11.gl_clear(GL11::GL_COLOR_BUFFER_BIT)
		GL20.gl_use_program(@program_id)

		GL15.gl_bind_buffer(GL15::GL_ARRAY_BUFFER, @buffer_id)
		GL20.gl_enable_vertex_attrib_array(0)
		GL20.gl_vertex_attrib_pointer(0, 4, GL11::GL_FLOAT, false, 0, 0)
		GL11.gl_draw_arrays(GL11::GL_TRIANGLES, 0, 3)

		GL20.gl_disable_vertex_attrib_array(0)
		GL20.gl_use_program(0)

	end

	# initialise the vertex buffers
	def init_vertex_buffers
		#vao_id = GL30.gl_gen_vertex_arrays
		#GL30.gl_bind_vertex_array(vao_id)

		@buffer_id = GL15.gl_gen_buffers
		GL15.gl_bind_buffer(GL15::GL_ARRAY_BUFFER, @buffer_id)

		float_buffer = BufferUtils.create_float_buffer(@vertex_positions.size)
		float_buffer.put(@vertex_positions.to_java(:float))

		#MUST FLIP THE BUFFER! THIS PUTS IT BACK TO THE BEGINNING!
		float_buffer.flip

		GL15.gl_buffer_data(GL15::GL_ARRAY_BUFFER, float_buffer, GL15::GL_STATIC_DRAW)

		# cleanup
		GL15.gl_bind_buffer(GL15::GL_ARRAY_BUFFER, 0)
		#GL30.gl_bind_vertex_array(0)
	end

end


text:
import { Component, ViewChild } from '@angular/core';

import { NavController } from 'ionic-angular';
import { List } from 'ionic-angular';

import { BeanSearch, IBeanArrayItem } from '../../services/bean.search';

@Component({
  selector: 'page-beans',
  templateUrl: 'pick.html'
})
export class PickPage {
  @ViewChild(List) list: List;

  constructor(
    public navCtrl: NavController,
    public beanSearch: BeanSearch ) {
  }

  stopSliding() {
    this.list.sliding = false;
  }

  beanSelected(b: IBeanArrayItem) {
    this.beanSearch.setSelectedBean(b)
    this.navCtrl.pop();
  }
}


text:
from theano import Op, Apply
from theano.tensor import as_tensor_variable

class DoubleOp(Op):
    __props__ = ()

    def make_node(self, x):
        x = as_tensor_variable(x)
        return Apply(self, [x], [x.type()])

    def perform(self, node, inputs, output_storage):
        x = inputs[0]
        z = output_storage[0]
        z[0] = x * 2

    def infer_shape(self, node, input_shapes):
        return input_shapes

    def grad(self, inputs, output_grads):
        return [output_grads[0] * 2]

    def R_op(self, inputs, eval_points):
        if eval_points[0] is None:
            return eval_points
        return self.grad(inputs, eval_points)


text:
var dbtypes;
$(document).ready(function() {
	dbtypes={
		sqlite:!!$('#hasSQLite').val(),
		mysql:!!$('#hasMySQL').val(),
		postgresql:!!$('#hasPostgreSQL').val(),
		oracle:!!$('#hasOracle').val()
	};

	$('#selectDbType').buttonset();
	// change links inside an info box back to their default appearance
	$('#selectDbType p.info a').button('destroy');

	if($('#hasSQLite').val()){
		$('#use_other_db').hide();
		$('#use_oracle_db').hide();
	} else {
		$('#sqliteInformation').hide();
	}
	$('#adminlogin').change(function(){
		$('#adminlogin').val($.trim($('#adminlogin').val()));
	});
	$('#sqlite').click(function() {
		$('#use_other_db').slideUp(250);
		$('#use_oracle_db').slideUp(250);
		$('#sqliteInformation').show();
		$('#dbname').attr('pattern','[0-9a-zA-Z$_-]+');
	});

	$('#mysql,#pgsql').click(function() {
		$('#use_other_db').slideDown(250);
		$('#use_oracle_db').slideUp(250);
		$('#sqliteInformation').hide();
		$('#dbname').attr('pattern','[0-9a-zA-Z$_-]+');
	});

	$('#oci').click(function() {
		$('#use_other_db').slideDown(250);
		$('#use_oracle_db').show(250);
		$('#sqliteInformation').hide();
		$('#dbname').attr('pattern','[0-9a-zA-Z$_-.]+');
	});

	$('input[checked]').trigger('click');

	$('#showAdvanced').click(function(e) {
		e.preventDefault();
		$('#datadirContent').slideToggle(250);
		$('#databaseBackend').slideToggle(250);
		$('#databaseField').slideToggle(250);
	});
	$("form").submit(function(){
		// Save form parameters
		var post = $(this).serializeArray();

		// Show spinner while finishing setup
		$('.float-spinner').show(250);

		// Disable inputs
		$(':submit', this).attr('disabled','disabled').val($(':submit', this).data('finishing'));
		$('input', this).addClass('ui-state-disabled').attr('disabled','disabled');
		// only disable buttons if they are present
		if($('#selectDbType').find('.ui-button').length > 0) {
			$('#selectDbType').buttonset('disable');
		}
		$('.strengthify-wrapper, .tipsy')
			.css('-ms-filter', '"progid:DXImageTransform.Microsoft.Alpha(Opacity=30)"')
			.css('filter', 'alpha(opacity=30)')
			.css('opacity', .3);

		// Create the form
		var form = $('<form>');
		form.attr('action', $(this).attr('action'));
		form.attr('method', 'POST');

		for(var i=0; i<post.length; i++){
			var input = $('<input type="hidden">');
			input.attr(post[i]);
			form.append(input);
		}

		// Submit the form
		form.appendTo(document.body);
		form.submit();
		return false;
	});

	// Expand latest db settings if page was reloaded on error
	var currentDbType = $('input[type="radio"]:checked').val();

	if (currentDbType === undefined){
		$('input[type="radio"]').first().click();
	}

	if (
		currentDbType === 'sqlite' ||
		(dbtypes.sqlite && currentDbType === undefined)
	){
		$('#datadirContent').hide(250);
		$('#databaseBackend').hide(250);
		$('#databaseField').hide(250);
		$('.float-spinner').hide(250);
	}

	$('#adminpass').strengthify({
		zxcvbn: OC.linkTo('core','vendor/zxcvbn/dist/zxcvbn.js'),
		titles: [
			t('core', 'Very weak password'),
			t('core', 'Weak password'),
			t('core', 'So-so password'),
			t('core', 'Good password'),
			t('core', 'Strong password')
		],
		drawTitles: true
	});

	// centers the database chooser if it is too wide
	if($('#databaseBackend').width() > 300) {
		// this somehow needs to wait 250 milliseconds
		// otherwise it gets overwritten
		setTimeout(function(){
			// calculate negative left margin
			// half of the difference of width and default bix width of 300
			// add 10 to clear left side padding of button group
			var leftMargin = (($('#databaseBackend').width() - 300) / 2 + 10 ) * -1;

			$('#databaseBackend').css('margin-left', Math.floor(leftMargin) + 'px');
		}, 250);
	}
});


text:
export declare function createLogger(name: string): {
    log: (...args: unknown[]) => void;
};


text:
package com.bt.pi.ops.website.controllers;

import javax.annotation.Resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.bt.pi.app.common.entities.AvailabilityZone;
import com.bt.pi.app.common.entities.AvailabilityZones;
import com.bt.pi.app.common.entities.InstanceTypeConfiguration;
import com.bt.pi.app.common.entities.InstanceTypes;
import com.bt.pi.app.instancemanager.health.AvailableResourcesHeartBeatFiller;
import com.bt.pi.core.application.health.entity.HeartbeatEntity;
import com.bt.pi.core.application.health.entity.HeartbeatEntityCollection;
import com.bt.pi.core.id.PId;
import com.bt.pi.ops.website.entities.AvailableResources;
import com.bt.pi.ops.website.reporting.HeartbeatRetriever;

@Component
@Path("/resources/{availabilityzone}")
public class AvailableResourcesController extends ControllerBase {

	private static final int ONE_OH_TWO_FOUR = 1024;

	private static final Log LOG = LogFactory.getLog(AvailableResourcesController.class);

	@Resource
	private HeartbeatRetriever heartbeatRetriever;

	public AvailableResourcesController() {
	}

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public String getAvailableResources(@PathParam("availabilityzone") String availabilityZoneName) {
		AvailabilityZone availabilityZone = getAvailabilityZoneFromCache(availabilityZoneName);
		HeartbeatEntityCollection heartbeatEntityCollection = heartbeatRetriever.getAllHeartbeats(availabilityZone.getRegionCode(), availabilityZone.getAvailabilityZoneCodeWithinRegion());
		AvailableResources availableResources = getFreeResourcesInAvailabilityZone(heartbeatEntityCollection);

		return getKoalaJsonParser().getJson(availableResources);
	}

	private void calculateAndStoreAvailableInstances(AvailableResources availableResources, HeartbeatEntity heartbeatEntity, InstanceTypes instanceTypes) {
		LOG.debug(String.format("calculateAndStoreAvailableInstances(%s, %s, %s)", availableResources, heartbeatEntity, instanceTypes));
		for (InstanceTypeConfiguration instanceTypeConfiguration : instanceTypes.getInstanceTypes().values()) {
			if (instanceTypeConfiguration.isDeprecated())
				continue;
			if (instanceTypeConfiguration.getDiskSizeInGB() > 0 && instanceTypeConfiguration.getMemorySizeInMB() > 0 && instanceTypeConfiguration.getNumCores() > 0) {
				Long freeMemory = heartbeatEntity.getAvailableResources().get(AvailableResourcesHeartBeatFiller.FREE_MEMORY);
				long memoryNumber = null == freeMemory ? 0 : freeMemory / instanceTypeConfiguration.getMemorySizeInMB();

				Long freeDisk = heartbeatEntity.getAvailableResources().get(AvailableResourcesHeartBeatFiller.FREE_DISK);
				long diskNumber = null == freeDisk ? 0 : freeDisk / ((long) instanceTypeConfiguration.getDiskSizeInGB() * ONE_OH_TWO_FOUR);

				Long freeCores = heartbeatEntity.getAvailableResources().get(AvailableResourcesHeartBeatFiller.FREE_CORES);
				long coreNumber = null == freeCores ? 0 : freeCores / instanceTypeConfiguration.getNumCores();
				long numberOfInstances = Math.min(coreNumber, Math.min(memoryNumber, diskNumber));
				availableResources.addInstancesToType(instanceTypeConfiguration.getInstanceType(), numberOfInstances);
			}
		}
	}

	private AvailableResources getFreeResourcesInAvailabilityZone(HeartbeatEntityCollection heartbeatEntityCollection) {
		InstanceTypes instanceTypes = getInstanceTypes();
		AvailableResources result = new AvailableResources();
		long freeMemoryInMB = 0;
		long freeDiskInMb = 0;
		int freeCores = 0;
		for (HeartbeatEntity heartbeatEntity : heartbeatEntityCollection.getEntities()) {
			Long long1 = heartbeatEntity.getAvailableResources().get(AvailableResourcesHeartBeatFiller.FREE_MEMORY);
			if (null != long1)
				freeMemoryInMB += long1;

			Long long2 = heartbeatEntity.getAvailableResources().get(AvailableResourcesHeartBeatFiller.FREE_DISK);
			if (null != long2)
				freeDiskInMb += long2;

			Long long3 = heartbeatEntity.getAvailableResources().get(AvailableResourcesHeartBeatFiller.FREE_CORES);
			if (null != long3)
				freeCores += long3;

			if (instanceTypes != null)
				calculateAndStoreAvailableInstances(result, heartbeatEntity, instanceTypes);
		}
		result.setFreeCores(freeCores);
		result.setFreeDiskInMB(freeDiskInMb);
		result.setFreeMemoryInMB(freeMemoryInMB);
		LOG.debug(String.format("returning " + result));
		return result;
	}

	private AvailabilityZone getAvailabilityZoneFromCache(String availabilityZoneName) {
		PId availabilityZonesId = getPiIdBuilder().getAvailabilityZonesId();
		AvailabilityZones availabilityZones = getBlockingDhtCache().get(availabilityZonesId);
		AvailabilityZone availabilityZone = availabilityZones.getAvailabilityZoneByName(availabilityZoneName);
		if (availabilityZone == null)
			throw new IllegalArgumentException(String.format("Availability zone %s not found", availabilityZoneName));
		return availabilityZone;
	}

	private InstanceTypes getInstanceTypes() {
		PId instanceTypesId = getPiIdBuilder().getPId(InstanceTypes.URL_STRING);
		return getBlockingDhtCache().get(instanceTypesId);
	}
}


text:
namespace OneSky.CSharp.Json
{
    public interface IProjectPlugin : IProject
    {
        string Platform { get; }

        ILocale BaseLanguage { get; }
    }
}


text:
require 'file_data/version'
require 'file_data/file_types/file_info'
require 'file_data/formats/exif/exif'
require 'file_data/formats/mpeg4/mpeg4'


text:
use std::ops::Range;
use std::sync::atomic::Ordering;
use std::sync::Arc;

// AtomicU64 have not landed in stable.
// For the moment let's just use AtomicUsize on
// x86/64 bit platform, and a mutex on other platform.
#[cfg(target_arch = "x86_64")]
mod archicture_impl {

    use std::sync::atomic::{AtomicUsize, Ordering};

    #[derive(Default)]
    pub struct AtomicU64Ersatz(AtomicUsize);

    impl AtomicU64Ersatz {
        pub fn new(first_opstamp: u64) -> AtomicU64Ersatz {
            AtomicU64Ersatz(AtomicUsize::new(first_opstamp as usize))
        }

        pub fn fetch_add(&self, val: u64, order: Ordering) -> u64 {
            self.0.fetch_add(val as usize, order) as u64
        }
    }
}

#[cfg(not(target_arch = "x86_64"))]
mod archicture_impl {

    use std::sync::atomic::Ordering;
    /// Under other architecture, we rely on a mutex.
    use std::sync::RwLock;

    #[derive(Default)]
    pub struct AtomicU64Ersatz(RwLock<u64>);

    impl AtomicU64Ersatz {
        pub fn new(first_opstamp: u64) -> AtomicU64Ersatz {
            AtomicU64Ersatz(RwLock::new(first_opstamp))
        }

        pub fn fetch_add(&self, incr: u64, _order: Ordering) -> u64 {
            let mut lock = self.0.write().unwrap();
            let previous_val = *lock;
            *lock = previous_val + incr;
            previous_val
        }
    }
}

use self::archicture_impl::AtomicU64Ersatz;

#[derive(Clone, Default)]
pub struct Stamper(Arc<AtomicU64Ersatz>);

impl Stamper {
    pub fn new(first_opstamp: u64) -> Stamper {
        Stamper(Arc::new(AtomicU64Ersatz::new(first_opstamp)))
    }

    pub fn stamp(&self) -> u64 {
        self.0.fetch_add(1u64, Ordering::SeqCst) as u64
    }

    /// Given a desired count `n`, `stamps` returns an iterator that
    /// will supply `n` number of u64 stamps.
    pub fn stamps(&self, n: u64) -> Range<u64> {
        let start = self.0.fetch_add(n, Ordering::SeqCst);
        Range {
            start,
            end: start + n,
        }
    }
}

#[cfg(test)]
mod test {

    use super::Stamper;

    #[test]
    fn test_stamper() {
        let stamper = Stamper::new(7u64);
        assert_eq!(stamper.stamp(), 7u64);
        assert_eq!(stamper.stamp(), 8u64);

        let stamper_clone = stamper.clone();
        assert_eq!(stamper.stamp(), 9u64);

        assert_eq!(stamper.stamp(), 10u64);
        assert_eq!(stamper_clone.stamp(), 11u64);
        assert_eq!(stamper.stamps(3u64), (12..15));
        assert_eq!(stamper.stamp(), 15u64);
    }
}


text:
chicago-snow-viz
================

Visualizing historical snowfall levels in Chicago.

## Contents

* [Background](#background)
* [Data Source](#data-source)
  * [Getting The Data](#getting-the-data)
* [Setting Up Your Development Environment](#setting-up-your-development-environment)

## Background

I live in Chicago, and the 2013-2014 winter so far has felt oppressive in its amount of snowfall and how much has stayed on the ground unmelting. It feels like the worst winter I can remember, but I recognize that my perception could be colored by many external factors. This is my attempt to justify, or abolish, my feelings about the winter and to get a longer ranging perspective on what Chicago winters are like.

## Data Source

Where can we get measurements of snowfall in Chicago? The [NOAA](http://www.noaa.gov/) (National Oceanic and Atmospheric Administration) operates an arm called the [NCDC](http://www.ncdc.noaa.gov/) (National Climatic Data Center), which provides free access to climate data sets through their [Climate Data Online](http://www.ncdc.noaa.gov/cdo-web/) service.

We want daily measurements that include snow depth, so we'll use the [GHCN Daily](http://gis.ncdc.noaa.gov/geoportal/catalog/search/resource/details.page?id=gov.noaa.ncdc:C00838) (Global Historical Climatology Network) data set. Documentation on the GHCN Daily data set can be found in [this PDF](http://www1.ncdc.noaa.gov/pub/data/cdo/documentation/GHCND_documentation.pdf).

If you go to the main GHCN Daily page, you will find several ways to access the data and find what you're looking for. We'll use the [text search](http://www.ncdc.noaa.gov/cdo-web/search?datasetid=GHCND), where we'll choose the following selections:

![CDO Step 1](images/CDO_Step_1.png)

The search results contain a number of stations with "Chicago" in their name, and each result also shows the "Period of Record", or the range of time for which measurements are available for download. Strangely, even though I chose a date range going back to 1964, it shows me weather stations that have far less data than that. I have to scroll through the results examining the Period of Record until I find that [CHICAGO OHARE INTERNATIONAL AIRPORT](http://www.ncdc.noaa.gov/cdo-web/datasets/GHCND/stations/GHCND:USW00094846/detail) has data from 1958-11-01 to the present day.

![CDO Step 2](images/CDO_Step_2.png)

At the bottom of the station's page, there is an area where you can explore the types of data recorded by this weather station and how complete each type is. We're primarily interested in measurements related to snow, so we click on "Precipitation" to see that there is 98% coverage for SNWD (snow depth) and 99% coverage for SNOW (snowfall). I'm guessing that the last 1-2% may be from non-winter days, but it's still pretty good if it's missing some data from a few days in the winter.

![CDO Step 3](images/CDO_Step_3.png)

### Getting The Data

Data sets are created on the fly for you and take some time for the system to generate. You specify what data you would like, submit the job to the system with your email address, and a link to the data will be sent to you when it's ready.

To get started, you have to add the station to your data shopping cart with the ADD TO CART button:

![CDO Step 4](images/CDO_Step_4.png)

Then go to your [shopping cart](http://www.ncdc.noaa.gov/cdo-web/cart) through the link in the top right corner of the site:

![CDO Step 5](images/CDO_Step_5.png)

We will make sure that the Date Range is still 1964-01-01 to 2014-02-07. Next, choose "Custom GHCN-Daily CSV" for the output format. Then click the CONTINUE button at the bottom of the page:

![CDO Step 6](images/CDO_Step_6.png)

On the next page there are options for what you want included in the data set. In the "Station Detail & Data Flag Options" area, uncheck all the options. While station name might be interesting, this unnecessarily bloats the file as the station name is redundantly included on every line of the CSV file and we're only querying one station at a time:

![CDO Step 7](images/CDO_Step_7.png)

In the "Select data types for custom output" area, expand the Precipitation header and check the boxes for Snow depth and Snowfall. Then click the CONTINUE button at the bottom of the page:

![CDO Step 8](images/CDO_Step_8.png)

Enter your email address where you would like the data download URL to be sent and then click the SUBMIT ORDER button at the bottom of the page:

![CDO Step 9](images/CDO_Step_9.png)

If you use GMail, the NCDC email may be automatically categorized in the Promotions area. Check in your different email categories if you don't see the email appear immediately in your Inbox. The email will look like this:

![CDO Step 10](images/CDO_Step_10.png)

There is a link to check the status of the data set generation job. It's mostly useless, since you'll get another email dispatched as soon as it's ready for download. For this particular data set, which I've requested several times over in the process of creating this documentation, I had to wait about 12 minutes to get the download link at non-business hours. This wait will change depending on the number of requests that CDO is currently handling, so be patient.

## Setting Up Your Development Environment

I develop visualizations with [D3js](http://d3js.org/), Data-Driven Documents, a fantastic JavaScript data visualization library that manipulates the [DOM](https://developer.mozilla.org/en-US/docs/DOM) (Document Object Model) using your data as the driver. Check out the list of excellent D3 tutorials [here](https://github.com/mbostock/d3/wiki/Tutorials).

In order to be able to make changes rapidly and see the effects immediately, I use Python to run a local web server:

```
python -m SimpleHTTPServer 8000
```

I run this from the root of this repository, so if I'm editing `snowdepth.html` then I can just browse to [http://localhost:8000/snowdepth.html](http://localhost:8000/snowdepth.html) to see my changes. As soon as I make changes and save the file, I can refresh the page in my browser to see the result.


text:
var assert = require('assert'),
		sinon = require('sinon'),
		store = require('../lib/store.js'),
		users = require('../lib/users.js');

describe('users', function() {
  describe('validate', function() {
    describe('username', function() {
      before(function() {
        sinon.stub(users.find, 'username');
      });
      after(function() {
        users.find.username.restore();
      });
      it('should return error if username is too short', function(done) {
        users.validate.username('12345', function(e) {
          assert.notEqual(e, null);
          done();
        });
      });
      it('should return error if users search fails', function(done) {
        users.find.username.yields('ERROR');
        users.validate.username('123456', function(e) {
          assert.equal(e, 'ERROR');
          done();
        });
      });
      it('should return error if users search finds username', function(done) {
        users.find.username.yields(null, { });
        users.validate.username('123456', function(e) {
          assert.equal(e, 'This username is already being used!');
          done();
        });
      });
      it('should return ok if users search fails to find username', function(done) {
        users.find.username.yields(null, null);
        users.validate.username('123456', done);
      });
    });
    describe('email', function() {
      it('should return error if emailname is too short', function(done) {
        users.validate.email('12345', function(e) {
          assert.notEqual(e, null);
          done();
        });
      });
      it('should return ok if email valid', function(done) {
        users.validate.email('will@goldston.com', done);
      });
    });
  });
  describe('with stubbed store', function() {
    before(function() {
      sinon.stub(store, 'getCollection');
    });
    after(function() {
      store.getCollection.restore();
    });
    describe('collection', function() {
      var collection = null;
      beforeEach(function() {
        store.getCollection.reset();
        collection = sinon.stub();
        store.getCollection.yields(null, collection);
      });
      it('should not error', function(done) {
        users.collection(done);
      });
      it('should call getCollection once', function(done) {
        users.collection(function() {
          assert.equal(store.getCollection.calledOnce, true);
          done();
        });
      });
      it('should call getCollection with correct arguments', function(done) {
        users.collection(function() {
          assert.equal(store.getCollection.args[0][0], 'users');
          done();
        });
      });
      it('should return error if getCollection fails', function(done) {
        store.getCollection.yields('ERROR');
        users.collection(function(e) {
          assert.equal(e, 'ERROR');
          done();
        });
      });
    });
    describe('find.username', function() {
      var collection = null;
      beforeEach(function() {
        store.getCollection.reset();
        collection = sinon.stub();
        collection.findOne = sinon.stub();
        collection.findOne.yields(null, 'USER');
        store.getCollection.yields(null, collection);
      });
      it('should not error', function(done) {
        users.find.username('username', done);
      });
      it('should call getCollection once', function(done) {
        users.find.username('username', function() {
          assert.equal(store.getCollection.calledOnce, true);
          done();
        });
      });
      it('should call getCollection with correct arguments', function(done) {
        users.find.username('username', function() {
          assert.equal(store.getCollection.args[0][0], 'users');
          done();
        });
      });
      it('should call findOne once', function(done) {
        users.find.username('username', function() {
          assert.equal(collection.findOne.calledOnce, true);
          done();
        });
      });
      it('should call findOne with correct arguments', function(done) {
        users.find.username('username', function() {
          assert.deepEqual(collection.findOne.args[0][0], { _id: 'username' });
          done();
        });
      });
      it('should call done returning found user', function(done) {
        users.find.username('username', function(e, user) {
          assert.equal(user, 'USER');
          done();
        });
      });
      it('should return error if getCollection fails', function(done) {
        store.getCollection.yields('ERROR');
        users.find.username('username', function(e) {
          assert.equal(e, 'ERROR');
          done();
        });
      });
      it('should return error if findOne fails', function(done) {
        collection.findOne.yields('ERROR');
        users.find.username('username', function(e) {
          assert.equal(e, 'ERROR');
          done();
        });
      });
    });
  });
});


text:
package org.hibernate.test.jpa;
import java.math.BigDecimal;

/**
 * @author Steve Ebersole
 */
public class Part {
	private Long id;
	private Item item;
	private String name;
	private String stockNumber;
	private BigDecimal unitPrice;

	public Part() {
	}

	public Part(Item item, String name, String stockNumber, BigDecimal unitPrice) {
		this.item = item;
		this.name = name;
		this.stockNumber = stockNumber;
		this.unitPrice = unitPrice;

		this.item.getParts().add( this );
	}

	public Long getId() {
		return id;
	}

	private void setId(Long id) {
		this.id = id;
	}

	public Item getItem() {
		return item;
	}

	private void setItem(Item item) {
		this.item = item;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getStockNumber() {
		return stockNumber;
	}

	public void setStockNumber(String stockNumber) {
		this.stockNumber = stockNumber;
	}

	public BigDecimal getUnitPrice() {
		return unitPrice;
	}

	public void setUnitPrice(BigDecimal unitPrice) {
		this.unitPrice = unitPrice;
	}
}


text:
**Update July 13, 2015**: Combine PaperColor.vim and PaperColor-Dark.vim into a single PaperColor.vim. See updated usage instruction.

PaperColor Theme
===================
Light & Dark color schemes for **Vim** terminal editor and **gVim**

Inspired by Google's Material Design

Improve code readability; great for presentation

Currently designed for these languages:  C, C++, Makefile, CMake, Lex/Flex & Yacc/Bison, Bash, VimL, Golang, JavaScript, Python, Ruby, Markdown, DTrace, SystemTap, PlantUML, Haskell, Assembly (MIPS, GAS, NASM), SQL/MySQL, Octave/MATLAB, Fortran, R, PHP, Perl

Other languages can still display well as long as your Vim is set up to recognize the language syntax even though that may not be the optimal experience. So, if the language you are working on isn't listed here, feel free to make a design request.

Plugin support: Netrw, NERDTree, Tagbar, Tabline, Vimdiff, Vim-Airline

(see below for syntax-highlighting plugins target)

## Installation
Place 'PaperColor.vim' file into 'colors' folder within your Vim directory, e.g. `~/.vim/colors/`

Or simply use a plugin manager like [Vundle](https://github.com/gmarik/Vundle.vim) (recommended for easy `:PluginUpdate`):

    Plugin 'NLKNguyen/papercolor-theme'

Then, put this in your `~/.vimrc`

```VimL
    set t_Co=256   " This is may or may not needed.

    set background=light
    colorscheme PaperColor
```

Or using the dark version:

```VimL
    set background=dark
    colorscheme PaperColor
```

To switch to dark or light variant during session: `:set background=dark` or `:set background=light`

To quickly toggle between them, use [vim-unimpaired](https://github.com/tpope/vim-unimpaired)'s keymap `cob`

*Optional*: turn on line numbers and status bar

```VimL
    set number
    set laststatus=2
```

##Highlighting Customization
Some elements have default highlighting color that may not fit everyone, and you can customize their HEX color code in your .vimrc file.
Refer to 256-color table when choosing color.

Below is an example of the most often asked.

**CursorLine**

    let g:PaperColor_Light_CursorLine = "#dfdfff"

*Note*: Replace `_Light_` with `_Dark_` for the dark theme.

## Syntax Highlighting Plugins Target
There are syntax highlighting enhancement plugins that improve upon Vim built-in syntax highlighting, and each can have many different implementations. This is the list of plugins that this color scheme targets.

* C: [c-syntax.vim](https://github.com/NLKNguyen/c-syntax.vim)
* JavaScript: [vim-javascript](https://github.com/pangloss/vim-javascript)
* Go: [vim-go](https://github.com/fatih/vim-go)
* DTrace: [dtrace-syntax-file](https://github.com/vim-scripts/dtrace-syntax-file)
* SystemTap: [vim-systemtap](https://github.com/nickhutchinson/vim-systemtap)
* Haskell: [haskell-vim](https://github.com/raichoo/haskell-vim)
* PlantUML: [plantuml-syntax](https://github.com/aklt/plantuml-syntax)
* Markdown: [vim-markdown](https://github.com/plasticboy/vim-markdown)
* Assembly MIPS: [mips](https://github.com/vim-scripts/mips.vim)
* Assembly GAS: [vim-gas](https://github.com/Shirk/vim-gas)
* Octave/MATLAB: [vim-octave](https://github.com/jvirtanen/vim-octave)
* Python: [python-syntax](https://github.com/hdima/python-syntax/)

## Screenshots

![Sample Ruby code](https://nlknguyen.files.wordpress.com/2015/05/ruby1.png)

![Sample DTrace code](https://nlknguyen.files.wordpress.com/2015/05/dtrace1.png)

![Sample MySQL code](https://nlknguyen.files.wordpress.com/2015/05/mysql.png)

![Sample Assembly code](https://nlknguyen.files.wordpress.com/2015/05/asm.png)

*Note*: The background of the dark color scheme was brightened a bit to reduce contrast after these following screenshots were taken.

![Sample Ruby code](https://nlknguyen.files.wordpress.com/2015/05/ruby-dark.png)

![Sample Go code](https://nlknguyen.files.wordpress.com/2015/05/go-dark.png)

![Sample JavaScript code](https://nlknguyen.files.wordpress.com/2015/05/javascript-dark2.png)

![Sample C code](https://nlknguyen.files.wordpress.com/2015/05/c-dark-split.png)

![Vim-airline support](https://nlknguyen.files.wordpress.com/2015/05/gifrecord_2015-05-31_010251.gif)

To set [vim-airline](https://github.com/bling/vim-airline) theme:

    let g:airline_theme='PaperColor'

For more sceenshots, story behind the project, and other users' designs inspired by Paper Color, go to [this blog post](http://nlknguyen.com/2015/05/21/vim-paper-color-theme/)

Suggestions/Wishes/Questions/Comments are welcome via [Github issues](https://github.com/NLKNguyen/papercolor-theme/issues) or via the blog above.


text:
<?php

namespace Looptribe\Paytoshi\Tests\Model;

use Looptribe\Paytoshi\Model\Payout;
use Looptribe\Paytoshi\Model\PayoutQueryBuilder;

class PayoutQueryBuilderTest extends \PHPUnit_Framework_TestCase
{
    public function testGetLastByRecipientAndIp1()
    {
        $ip = '10.10.10.10';
        $address = 'addr1';

        $self = $this;
        $connection = $this->getMockBuilder('Doctrine\DBAL\Connection')
            ->disableOriginalConstructor()
            ->getMock();

        $qb = $this->getMockBuilder('\Doctrine\DBAL\Query\QueryBuilder')
            ->disableOriginalConstructor()
            ->getMock();
        $qb->method('select')
            ->with('*')
            ->willReturn($qb);
        $qb->method('from')
            ->with('paytoshi_payouts')
            ->willReturn($qb);
        $qb->method('where')
            ->willReturn($qb);
        $qb->expects($this->exactly(2))
            ->method('setParameter')
            ->willReturnCallback(function($field, $value) use ($self, $qb, $ip, $address) {
                switch ($field) {
                    case 'ip':
                        $self->assertSame($ip, $value);
                        break;
                    case 'address':
                        $self->assertSame($address, $value);
                        break;
                    default:
                        $self->fail('Invalid field');
                        break;
                }
                return $qb;
            });
        $qb->method('orderBy')
            ->with('created_at', 'DESC')
            ->willReturn($qb);
        $qb->method('orWhere')
            ->willReturn($qb);
        $connection->method('createQueryBuilder')
            ->willReturn($qb);

        $sut = new PayoutQueryBuilder($connection);
        $result = $sut->getLastByRecipientAndIpQuery($ip, $address);
        $this->assertInstanceOf('\Doctrine\DBAL\Query\QueryBuilder', $result);
    }

    public function testGetLastByRecipientAndIp2()
    {
        $ip = '10.10.10.10';

        $connection = $this->getMockBuilder('Doctrine\DBAL\Connection')
            ->disableOriginalConstructor()
            ->getMock();

        $qb = $this->getMockBuilder('\Doctrine\DBAL\Query\QueryBuilder')
            ->disableOriginalConstructor()
            ->getMock();
        $qb->method('select')
            ->with('*')
            ->willReturn($qb);
        $qb->method('from')
            ->with('paytoshi_payouts')
            ->willReturn($qb);
        $qb->method('where')
            ->willReturn($qb);
        $qb->expects($this->once())
            ->method('setParameter')
            ->with($this->anything(), $ip)
            ->willReturn($qb);
        $qb->method('orderBy')
            ->with('created_at', 'DESC')
            ->willReturn($qb);
        $connection->method('createQueryBuilder')
            ->willReturn($qb);

        $sut = new PayoutQueryBuilder($connection);
        $result = $sut->getLastByRecipientAndIpQuery($ip);
        $this->assertInstanceOf('\Doctrine\DBAL\Query\QueryBuilder', $result);
    }

    public function testGetInsertQuery1()
    {
        $self = $this;
        $payout = new Payout();
        $payout->setRecipientAddress('addr1');
        $payout->setEarning(100);
        $payout->setIp('10.10.10.10');
        $payout->setCreatedAt(new \DateTime());

        $connection = $this->getMockBuilder('Doctrine\DBAL\Connection')
            ->disableOriginalConstructor()
            ->getMock();

        $qb = $this->getMockBuilder('\Doctrine\DBAL\Query\QueryBuilder')
            ->disableOriginalConstructor()
            ->getMock();
        $qb->method('insert')
            ->with('paytoshi_payouts')
            ->willReturn($qb);
        $qb->method('values')
            ->willReturn($qb);
        $qb->method('setParameter')
            ->willReturnCallback(function($field, $value) use ($self, $qb, $payout) {
                switch($field)
                {
                    case 'recipient_address':
                        $self->assertSame($payout->getRecipientAddress(), $value);
                        break;
                    case 'earning':
                        $self->assertSame($payout->getEarning(), $value);
                        break;
                    case 'referral_recipient_address':
                        $self->assertSame(null, $value);
                        break;
                    case 'referral_earning':
                        $self->assertSame(0, $value);
                        break;
                    case 'ip':
                        $self->assertSame($payout->getIp(), $value);
                        break;
                    case 'created_at':
                        $self->assertSame($payout->getCreatedAt(), $value);
                        break;
                    default:
                        $self->fail('Invalid field');
                        break;
                }
                return $qb;
            });
        $connection->method('createQueryBuilder')
            ->willReturn($qb);

        $sut = new PayoutQueryBuilder($connection);
        $result = $sut->getInsertQuery($payout);
        $this->assertInstanceOf('\Doctrine\DBAL\Query\QueryBuilder', $result);
    }

    public function testGetInsertQuery2()
    {
        $self = $this;
        $payout = new Payout();
        $payout->setRecipientAddress('addr1');
        $payout->setEarning(100);
        $payout->setReferralRecipientAddress('refaddr1');
        $payout->setReferralEarning(10);
        $payout->setIp('10.10.10.10');
        $payout->setCreatedAt(new \DateTime());

        $connection = $this->getMockBuilder('Doctrine\DBAL\Connection')
            ->disableOriginalConstructor()
            ->getMock();

        $qb = $this->getMockBuilder('\Doctrine\DBAL\Query\QueryBuilder')
            ->disableOriginalConstructor()
            ->getMock();
        $qb->method('insert')
            ->with('paytoshi_payouts')
            ->willReturn($qb);
        $qb->method('values')
            ->willReturn($qb);
        $qb->method('setParameter')
            ->willReturnCallback(function($field, $value) use ($self, $qb, $payout) {
                switch($field)
                {
                    case 'recipient_address':
                        $self->assertSame($payout->getRecipientAddress(), $value);
                        break;
                    case 'earning':
                        $self->assertSame($payout->getEarning(), $value);
                        break;
                    case 'referral_recipient_address':
                        $self->assertSame($payout->getReferralRecipientAddress(), $value);
                        break;
                    case 'referral_earning':
                        $self->assertSame($payout->getReferralEarning(), $value);
                        break;
                    case 'ip':
                        $self->assertSame($payout->getIp(), $value);
                        break;
                    case 'created_at':
                        $self->assertSame($payout->getCreatedAt(), $value);
                        break;
                    default:
                        $self->fail('Invalid field');
                        break;
                }
                return $qb;
            });
        $connection->method('createQueryBuilder')
            ->willReturn($qb);

        $sut = new PayoutQueryBuilder($connection);
        $result = $sut->getInsertQuery($payout);
        $this->assertInstanceOf('\Doctrine\DBAL\Query\QueryBuilder', $result);
    }
}


text:
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#undef XN_CROSS_PLATFORM
#include <XnOS.h>

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------
XN_CORE_API XnStatus XnOSLoadLibrary(const XN_CHAR* cpFileName, XN_LIB_HANDLE* pLibHandle)
{
	return (XN_STATUS_OS_UNSUPPORTED_FUNCTION);
}

XN_CORE_API XnStatus XnOSFreeLibrary(const XN_LIB_HANDLE LibHandle)
{
	return (XN_STATUS_OS_UNSUPPORTED_FUNCTION);
}

XN_CORE_API XnStatus XnOSGetProcAddress(const XN_LIB_HANDLE LibHandle, const XN_CHAR* cpProcName, XN_FARPROC* pProcAddr)
{
	return (XN_STATUS_OS_UNSUPPORTED_FUNCTION);
}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.h"

#include "third_party/blink/public/common/privacy_budget/identifiability_metric_builder.h"
#include "third_party/blink/public/common/privacy_budget/identifiability_study_settings.h"
#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
#include "third_party/blink/public/common/privacy_budget/identifiable_token_builder.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_insertable_streams.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_rtcp_parameters.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_rtp_capabilities.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_rtp_codec_parameters.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_rtp_decoding_parameters.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_rtp_header_extension_capability.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_rtp_header_extension_parameters.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/streams/readable_stream.h"
#include "third_party/blink/renderer/core/streams/writable_stream.h"
#include "third_party/blink/renderer/modules/peerconnection/identifiability_metrics.h"
#include "third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_receiver_sink_optimizer.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_receiver_source_optimizer.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_underlying_sink.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_underlying_source.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_video_underlying_sink.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_video_underlying_source.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_stats_report.h"
#include "third_party/blink/renderer/modules/peerconnection/web_rtc_stats_report_callback_resolver.h"
#include "third_party/blink/renderer/platform/bindings/microtask.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/peerconnection/rtc_encoded_video_stream_transformer.h"
#include "third_party/blink/renderer/platform/peerconnection/rtc_stats.h"
#include "third_party/blink/renderer/platform/privacy_budget/identifiability_digest_helpers.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/webrtc/api/rtp_parameters.h"

namespace blink {

RTCRtpReceiver::RTCRtpReceiver(RTCPeerConnection* pc,
                               std::unique_ptr<RTCRtpReceiverPlatform> receiver,
                               MediaStreamTrack* track,
                               MediaStreamVector streams,
                               bool force_encoded_audio_insertable_streams,
                               bool force_encoded_video_insertable_streams)
    : ExecutionContextLifecycleObserver(pc->GetExecutionContext()),
      pc_(pc),
      receiver_(std::move(receiver)),
      track_(track),
      streams_(std::move(streams)),
      force_encoded_audio_insertable_streams_(
          force_encoded_audio_insertable_streams),
      force_encoded_video_insertable_streams_(
          force_encoded_video_insertable_streams) {
  DCHECK(pc_);
  DCHECK(receiver_);
  DCHECK(track_);
  if (force_encoded_audio_insertable_streams_ && track_->kind() == "audio") {
    encoded_audio_transformer_ =
        receiver_->GetEncodedAudioStreamTransformer()->GetBroker();
    RegisterEncodedAudioStreamCallback();
  }
  if (force_encoded_video_insertable_streams_ && track_->kind() == "video")
    RegisterEncodedVideoStreamCallback();
}

MediaStreamTrack* RTCRtpReceiver::track() const {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return track_;
}

RTCDtlsTransport* RTCRtpReceiver::transport() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return transport_;
}

RTCDtlsTransport* RTCRtpReceiver::rtcpTransport() {
  // Chrome does not support turning off RTCP-mux.
  return nullptr;
}

absl::optional<double> RTCRtpReceiver::playoutDelayHint() const {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return playout_delay_hint_;
}

void RTCRtpReceiver::setPlayoutDelayHint(absl::optional<double> hint,
                                         ExceptionState& exception_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (hint.has_value() && hint.value() < 0.0) {
    exception_state.ThrowTypeError("playoutDelayHint can't be negative");
    return;
  }

  playout_delay_hint_ = hint;
  receiver_->SetJitterBufferMinimumDelay(playout_delay_hint_);
}

HeapVector<Member<RTCRtpSynchronizationSource>>
RTCRtpReceiver::getSynchronizationSources(ScriptState* script_state,
                                          ExceptionState& exception_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (!script_state->ContextIsValid()) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "Window is detached");
    return HeapVector<Member<RTCRtpSynchronizationSource>>();
  }

  UpdateSourcesIfNeeded();

  LocalDOMWindow* window = LocalDOMWindow::From(script_state);
  DocumentLoadTiming& time_converter =
      window->GetFrame()->Loader().GetDocumentLoader()->GetTiming();

  HeapVector<Member<RTCRtpSynchronizationSource>> synchronization_sources;
  for (const auto& web_source : web_sources_) {
    if (web_source->SourceType() != RTCRtpSource::Type::kSSRC)
      continue;
    RTCRtpSynchronizationSource* synchronization_source =
        MakeGarbageCollected<RTCRtpSynchronizationSource>();
    synchronization_source->setTimestamp(
        time_converter.MonotonicTimeToPseudoWallTime(web_source->Timestamp())
            .InMilliseconds());
    synchronization_source->setSource(web_source->Source());
    if (web_source->AudioLevel().has_value()) {
      synchronization_source->setAudioLevel(web_source->AudioLevel().value());
    }
    if (web_source->CaptureTimestamp().has_value()) {
      synchronization_source->setCaptureTimestamp(
          web_source->CaptureTimestamp().value());
    }
    if (web_source->SenderCaptureTimeOffset().has_value()) {
      synchronization_source->setSenderCaptureTimeOffset(
          web_source->SenderCaptureTimeOffset().value());
    }
    synchronization_source->setRtpTimestamp(web_source->RtpTimestamp());
    synchronization_sources.push_back(synchronization_source);
  }
  return synchronization_sources;
}

HeapVector<Member<RTCRtpContributingSource>>
RTCRtpReceiver::getContributingSources(ScriptState* script_state,
                                       ExceptionState& exception_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (!script_state->ContextIsValid()) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "Window is detached");
    return HeapVector<Member<RTCRtpContributingSource>>();
  }

  UpdateSourcesIfNeeded();

  LocalDOMWindow* window = LocalDOMWindow::From(script_state);
  DocumentLoadTiming& time_converter =
      window->GetFrame()->Loader().GetDocumentLoader()->GetTiming();

  HeapVector<Member<RTCRtpContributingSource>> contributing_sources;
  for (const auto& web_source : web_sources_) {
    if (web_source->SourceType() != RTCRtpSource::Type::kCSRC)
      continue;
    RTCRtpContributingSource* contributing_source =
        MakeGarbageCollected<RTCRtpContributingSource>();
    contributing_source->setTimestamp(
        time_converter.MonotonicTimeToPseudoWallTime(web_source->Timestamp())
            .InMilliseconds());
    contributing_source->setSource(web_source->Source());
    if (web_source->AudioLevel().has_value()) {
      contributing_source->setAudioLevel(web_source->AudioLevel().value());
    }
    if (web_source->CaptureTimestamp().has_value()) {
      contributing_source->setCaptureTimestamp(
          web_source->CaptureTimestamp().value());
    }
    if (web_source->SenderCaptureTimeOffset().has_value()) {
      contributing_source->setSenderCaptureTimeOffset(
          web_source->SenderCaptureTimeOffset().value());
    }
    contributing_source->setRtpTimestamp(web_source->RtpTimestamp());
    contributing_sources.push_back(contributing_source);
  }
  return contributing_sources;
}

ScriptPromise RTCRtpReceiver::getStats(ScriptState* script_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
  ScriptPromise promise = resolver->Promise();
  receiver_->GetStats(
      WTF::Bind(WebRTCStatsReportCallbackResolver, WrapPersistent(resolver)),
      GetExposedGroupIds(script_state));
  return promise;
}

RTCInsertableStreams* RTCRtpReceiver::createEncodedStreams(
    ScriptState* script_state,
    ExceptionState& exception_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (track_->kind() == "audio")
    return createEncodedAudioStreams(script_state, exception_state);
  DCHECK_EQ(track_->kind(), "video");
  return createEncodedVideoStreams(script_state, exception_state);
}

RTCInsertableStreams* RTCRtpReceiver::createEncodedAudioStreams(
    ScriptState* script_state,
    ExceptionState& exception_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (!force_encoded_audio_insertable_streams_) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "Encoded audio streams not requested at PC initialization");
    return nullptr;
  }
  if (encoded_audio_streams_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "Encoded audio streams already created");
    return nullptr;
  }

  InitializeEncodedAudioStreams(script_state);
  return encoded_audio_streams_;
}

RTCInsertableStreams* RTCRtpReceiver::createEncodedVideoStreams(
    ScriptState* script_state,
    ExceptionState& exception_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (!force_encoded_video_insertable_streams_) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "Encoded video streams not requested at PC initialization");
    return nullptr;
  }
  if (encoded_video_streams_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "Encoded video streams already created");
    return nullptr;
  }

  InitializeEncodedVideoStreams(script_state);
  return encoded_video_streams_;
}

RTCRtpReceiverPlatform* RTCRtpReceiver::platform_receiver() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return receiver_.get();
}

MediaStreamVector RTCRtpReceiver::streams() const {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return streams_;
}

void RTCRtpReceiver::set_streams(MediaStreamVector streams) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  streams_ = std::move(streams);
}

void RTCRtpReceiver::set_transceiver(RTCRtpTransceiver* transceiver) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  transceiver_ = transceiver;
}

void RTCRtpReceiver::set_transport(RTCDtlsTransport* transport) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  transport_ = transport;
}

void RTCRtpReceiver::UpdateSourcesIfNeeded() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (!web_sources_needs_updating_)
    return;
  web_sources_ = receiver_->GetSources();
  // Clear the flag and schedule a microtask to reset it to true. This makes
  // the cache valid until the next microtask checkpoint. As such, sources
  // represent a snapshot and can be compared reliably in .js code, no risk of
  // being updated due to an RTP packet arriving. E.g.
  // "source.timestamp == source.timestamp" will always be true.
  web_sources_needs_updating_ = false;
  Microtask::EnqueueMicrotask(
      WTF::Bind(&RTCRtpReceiver::SetContributingSourcesNeedsUpdating,
                WrapWeakPersistent(this)));
}

void RTCRtpReceiver::ContextDestroyed() {
  {
    WTF::MutexLocker locker(audio_underlying_source_mutex_);
    audio_from_depacketizer_underlying_source_.Clear();
  }
  {
    WTF::MutexLocker locker(audio_underlying_sink_mutex_);
    audio_to_decoder_underlying_sink_.Clear();
  }
}

void RTCRtpReceiver::SetContributingSourcesNeedsUpdating() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  web_sources_needs_updating_ = true;
}

void RTCRtpReceiver::Trace(Visitor* visitor) const {
  visitor->Trace(pc_);
  visitor->Trace(track_);
  visitor->Trace(transport_);
  visitor->Trace(streams_);
  visitor->Trace(transceiver_);
  visitor->Trace(encoded_audio_streams_);
  visitor->Trace(video_from_depacketizer_underlying_source_);
  visitor->Trace(video_to_decoder_underlying_sink_);
  visitor->Trace(encoded_video_streams_);
  ScriptWrappable::Trace(visitor);
  ExecutionContextLifecycleObserver::Trace(visitor);
}

RTCRtpCapabilities* RTCRtpReceiver::getCapabilities(ScriptState* state,
                                                    const String& kind) {
  if (kind != "audio" && kind != "video")
    return nullptr;

  RTCRtpCapabilities* capabilities = RTCRtpCapabilities::Create();
  capabilities->setCodecs(HeapVector<Member<RTCRtpCodecCapability>>());
  capabilities->setHeaderExtensions(
      HeapVector<Member<RTCRtpHeaderExtensionCapability>>());

  std::unique_ptr<webrtc::RtpCapabilities> rtc_capabilities =
      PeerConnectionDependencyFactory::From(*ExecutionContext::From(state))
          .GetReceiverCapabilities(kind);

  HeapVector<Member<RTCRtpCodecCapability>> codecs;
  codecs.ReserveInitialCapacity(
      SafeCast<wtf_size_t>(rtc_capabilities->codecs.size()));
  for (const auto& rtc_codec : rtc_capabilities->codecs) {
    auto* codec = RTCRtpCodecCapability::Create();
    codec->setMimeType(WTF::String::FromUTF8(rtc_codec.mime_type()));
    if (rtc_codec.clock_rate)
      codec->setClockRate(rtc_codec.clock_rate.value());
    if (rtc_codec.num_channels)
      codec->setChannels(rtc_codec.num_channels.value());
    if (!rtc_codec.parameters.empty()) {
      std::string sdp_fmtp_line;
      for (const auto& parameter : rtc_codec.parameters) {
        if (!sdp_fmtp_line.empty())
          sdp_fmtp_line += ";";
        if (parameter.first.empty()) {
          sdp_fmtp_line += parameter.second;
        } else {
          sdp_fmtp_line += parameter.first + "=" + parameter.second;
        }
      }
      codec->setSdpFmtpLine(sdp_fmtp_line.c_str());
    }
    codecs.push_back(codec);
  }
  capabilities->setCodecs(codecs);

  HeapVector<Member<RTCRtpHeaderExtensionCapability>> header_extensions;
  header_extensions.ReserveInitialCapacity(
      SafeCast<wtf_size_t>(rtc_capabilities->header_extensions.size()));
  for (const auto& rtc_header_extension : rtc_capabilities->header_extensions) {
    auto* header_extension = RTCRtpHeaderExtensionCapability::Create();
    header_extension->setUri(WTF::String::FromUTF8(rtc_header_extension.uri));
    header_extensions.push_back(header_extension);
  }
  capabilities->setHeaderExtensions(header_extensions);

  if (IdentifiabilityStudySettings::Get()->IsTypeAllowed(
          IdentifiableSurface::Type::kRtcRtpReceiverGetCapabilities)) {
    IdentifiableTokenBuilder builder;
    IdentifiabilityAddRTCRtpCapabilitiesToBuilder(builder, *capabilities);
    IdentifiabilityMetricBuilder(ExecutionContext::From(state)->UkmSourceID())
        .Add(IdentifiableSurface::FromTypeAndToken(
                 IdentifiableSurface::Type::kRtcRtpReceiverGetCapabilities,
                 IdentifiabilityBenignStringToken(kind)),
             builder.GetToken())
        .Record(ExecutionContext::From(state)->UkmRecorder());
  }
  return capabilities;
}

RTCRtpReceiveParameters* RTCRtpReceiver::getParameters() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  RTCRtpReceiveParameters* parameters = RTCRtpReceiveParameters::Create();
  std::unique_ptr<webrtc::RtpParameters> webrtc_parameters =
      receiver_->GetParameters();

  RTCRtcpParameters* rtcp = RTCRtcpParameters::Create();
  rtcp->setReducedSize(webrtc_parameters->rtcp.reduced_size);
  parameters->setRtcp(rtcp);

  HeapVector<Member<RTCRtpDecodingParameters>> encodings;
  encodings.ReserveCapacity(
      SafeCast<wtf_size_t>(webrtc_parameters->encodings.size()));
  for (const auto& webrtc_encoding : webrtc_parameters->encodings) {
    RTCRtpDecodingParameters* encoding = RTCRtpDecodingParameters::Create();
    if (!webrtc_encoding.rid.empty()) {
      // TODO(orphis): Add rid when supported by WebRTC
    }
    encodings.push_back(encoding);
  }
  parameters->setEncodings(encodings);

  HeapVector<Member<RTCRtpHeaderExtensionParameters>> headers;
  headers.ReserveCapacity(
      SafeCast<wtf_size_t>(webrtc_parameters->header_extensions.size()));
  for (const auto& webrtc_header : webrtc_parameters->header_extensions) {
    headers.push_back(ToRtpHeaderExtensionParameters(webrtc_header));
  }
  parameters->setHeaderExtensions(headers);

  HeapVector<Member<RTCRtpCodecParameters>> codecs;
  codecs.ReserveCapacity(
      SafeCast<wtf_size_t>(webrtc_parameters->codecs.size()));
  for (const auto& webrtc_codec : webrtc_parameters->codecs) {
    codecs.push_back(ToRtpCodecParameters(webrtc_codec));
  }
  parameters->setCodecs(codecs);

  return parameters;
}

void RTCRtpReceiver::RegisterEncodedAudioStreamCallback() {
  encoded_audio_transformer_->SetTransformerCallback(
      WTF::CrossThreadBindRepeating(
          &RTCRtpReceiver::OnAudioFrameFromDepacketizer,
          WrapCrossThreadWeakPersistent(this)));
}

void RTCRtpReceiver::UnregisterEncodedAudioStreamCallback() {
  encoded_audio_transformer_->ResetTransformerCallback();
}

void RTCRtpReceiver::SetAudioUnderlyingSource(
    RTCEncodedAudioUnderlyingSource* new_underlying_source,
    scoped_refptr<base::SingleThreadTaskRunner> new_source_task_runner) {
  if (!GetExecutionContext()) {
    // If our context is destroyed, then the RTCRtpReceiver, underlying
    // source(s), and transformer are about to be garbage collected, so there's
    // no reason to continue.
    return;
  }
  {
    WTF::MutexLocker locker(audio_underlying_source_mutex_);
    audio_from_depacketizer_underlying_source_->OnSourceTransferStarted();
    audio_from_depacketizer_underlying_source_ = new_underlying_source;
  }

  encoded_audio_transformer_->SetSourceTaskRunner(
      std::move(new_source_task_runner));
}

void RTCRtpReceiver::SetAudioUnderlyingSink(
    RTCEncodedAudioUnderlyingSink* new_underlying_sink) {
  if (!GetExecutionContext()) {
    // If our context is destroyed, then the RTCRtpReceiver and underlying
    // sink(s) are about to be garbage collected, so there's no reason to
    // continue.
    return;
  }
  WTF::MutexLocker locker(audio_underlying_sink_mutex_);
  audio_to_decoder_underlying_sink_ = new_underlying_sink;
}

void RTCRtpReceiver::InitializeEncodedAudioStreams(ScriptState* script_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK(!encoded_audio_streams_);
  DCHECK(force_encoded_audio_insertable_streams_);

  encoded_audio_streams_ = RTCInsertableStreams::Create();

  {
    WTF::MutexLocker locker(audio_underlying_source_mutex_);
    DCHECK(!audio_from_depacketizer_underlying_source_);

    // Set up readable.
    audio_from_depacketizer_underlying_source_ =
        MakeGarbageCollected<RTCEncodedAudioUnderlyingSource>(
            script_state,
            WTF::CrossThreadBindOnce(
                &RTCRtpReceiver::UnregisterEncodedAudioStreamCallback,
                WrapCrossThreadWeakPersistent(this)),
            /*is_receiver=*/true);

    auto set_underlying_source =
        WTF::CrossThreadBindRepeating(&RTCRtpReceiver::SetAudioUnderlyingSource,
                                      WrapCrossThreadWeakPersistent(this));
    auto disconnect_callback = WTF::CrossThreadBindOnce(
        &RTCRtpReceiver::UnregisterEncodedAudioStreamCallback,
        WrapCrossThreadWeakPersistent(this));
    // The high water mark for the readable stream is set to 0 so that frames
    // are removed from the queue right away, without introducing a new buffer.
    ReadableStream* readable_stream =
        ReadableStream::CreateWithCountQueueingStrategy(
            script_state, audio_from_depacketizer_underlying_source_,
            /*high_water_mark=*/0, AllowPerChunkTransferring(false),
            absl::make_unique<RtcEncodedAudioReceiverSourceOptimizer>(
                std::move(set_underlying_source),
                std::move(disconnect_callback)));
    encoded_audio_streams_->setReadable(readable_stream);
  }

  WritableStream* writable_stream;
  {
    WTF::MutexLocker locker(audio_underlying_sink_mutex_);
    DCHECK(!audio_to_decoder_underlying_sink_);

    // Set up writable.
    audio_to_decoder_underlying_sink_ =
        MakeGarbageCollected<RTCEncodedAudioUnderlyingSink>(
            script_state, encoded_audio_transformer_);

    auto set_underlying_sink =
        WTF::CrossThreadBindOnce(&RTCRtpReceiver::SetAudioUnderlyingSink,
                                 WrapCrossThreadWeakPersistent(this));

    // The high water mark for the stream is set to 1 so that the stream seems
    // ready to write, but without queuing frames.
    writable_stream = WritableStream::CreateWithCountQueueingStrategy(
        script_state, audio_to_decoder_underlying_sink_,
        /*high_water_mark=*/1,
        absl::make_unique<RtcEncodedAudioReceiverSinkOptimizer>(
            std::move(set_underlying_sink), encoded_audio_transformer_));
  }

  encoded_audio_streams_->setWritable(writable_stream);
}

void RTCRtpReceiver::OnAudioFrameFromDepacketizer(
    std::unique_ptr<webrtc::TransformableFrameInterface> encoded_audio_frame) {
  WTF::MutexLocker locker(audio_underlying_source_mutex_);
  if (audio_from_depacketizer_underlying_source_) {
    audio_from_depacketizer_underlying_source_->OnFrameFromSource(
        std::move(encoded_audio_frame));
  }
}

void RTCRtpReceiver::RegisterEncodedVideoStreamCallback() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK(!platform_receiver()
              ->GetEncodedVideoStreamTransformer()
              ->HasTransformerCallback());
  DCHECK_EQ(track_->kind(), "video");
  platform_receiver()
      ->GetEncodedVideoStreamTransformer()
      ->SetTransformerCallback(
          WTF::BindRepeating(&RTCRtpReceiver::OnVideoFrameFromDepacketizer,
                             WrapWeakPersistent(this)));
}

void RTCRtpReceiver::UnregisterEncodedVideoStreamCallback() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK_EQ(track_->kind(), "video");
  platform_receiver()
      ->GetEncodedVideoStreamTransformer()
      ->ResetTransformerCallback();
}

void RTCRtpReceiver::InitializeEncodedVideoStreams(ScriptState* script_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK(!encoded_video_streams_);
  DCHECK(!video_from_depacketizer_underlying_source_);
  DCHECK(!video_to_decoder_underlying_sink_);
  DCHECK(force_encoded_video_insertable_streams_);

  encoded_video_streams_ = RTCInsertableStreams::Create();

  // Set up readable.
  video_from_depacketizer_underlying_source_ =
      MakeGarbageCollected<RTCEncodedVideoUnderlyingSource>(
          script_state,
          WTF::Bind(&RTCRtpReceiver::UnregisterEncodedVideoStreamCallback,
                    WrapWeakPersistent(this)));
  // The high water mark for the readable stream is set to 0 so that frames are
  // removed from the queue right away, without introducing a new buffer.
  ReadableStream* readable_stream =
      ReadableStream::CreateWithCountQueueingStrategy(
          script_state, video_from_depacketizer_underlying_source_,
          /*high_water_mark=*/0);
  encoded_video_streams_->setReadable(readable_stream);

  // Set up writable.
  video_to_decoder_underlying_sink_ =
      MakeGarbageCollected<RTCEncodedVideoUnderlyingSink>(
          script_state,
          WTF::BindRepeating(
              [](RTCRtpReceiver* receiver)
                  -> RTCEncodedVideoStreamTransformer* {
                return receiver ? receiver->platform_receiver()
                                      ->GetEncodedVideoStreamTransformer()
                                : nullptr;
              },
              WrapWeakPersistent(this)),
          webrtc::TransformableFrameInterface::Direction::kReceiver);
  // The high water mark for the stream is set to 1 so that the stream seems
  // ready to write, but without queuing frames.
  WritableStream* writable_stream =
      WritableStream::CreateWithCountQueueingStrategy(
          script_state, video_to_decoder_underlying_sink_,
          /*high_water_mark=*/1);
  encoded_video_streams_->setWritable(writable_stream);
}

void RTCRtpReceiver::OnVideoFrameFromDepacketizer(
    std::unique_ptr<webrtc::TransformableVideoFrameInterface>
        encoded_video_frame) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (video_from_depacketizer_underlying_source_) {
    video_from_depacketizer_underlying_source_->OnFrameFromSource(
        std::move(encoded_video_frame));
  }
}

}  // namespace blink