text:
package org.apache.airavata.workflow.core.dag.port;

import org.apache.airavata.model.PortModel;
import org.apache.airavata.model.application.io.DataType;
import org.apache.airavata.model.application.io.OutputDataObjectType;
import org.apache.airavata.workflow.core.dag.edge.Edge;
import org.apache.airavata.workflow.core.dag.nodes.WorkflowNode;

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

public class OutPortImpl implements OutPort {

    private OutputDataObjectType outputDataObjectType;
    private List<Edge> outEdges = new ArrayList<Edge>();
    private boolean isSatisfy = false;
    private WorkflowNode node;
    private PortModel portModel;
    private DataType dataType;

    public OutPortImpl(PortModel portModel) {
        this.portModel = portModel;
    }

    @Override
    public void setOutputObject(OutputDataObjectType outputObject) {
        this.outputDataObjectType = outputObject;
    }

    @Override
    public OutputDataObjectType getOutputObject() {
        return this.outputDataObjectType;
    }

    @Override
    public List<Edge> getEdges() {
        return this.outEdges;
    }

    @Override
    public void addEdge(Edge edge) {
        this.outEdges.add(edge);
    }

    @Override
    public void setPortModel(PortModel portModel) {
        this.portModel = portModel;
    }

    @Override
    public PortModel getPortModel() {
        return portModel;
    }

    @Override
    public boolean isReady() {
        return this.outputDataObjectType.getValue() != null
                && !this.outputDataObjectType.getValue().equals("");
    }

    @Override
    public WorkflowNode getNode() {
        return this.node;
    }

    @Override
    public void setNode(WorkflowNode workflowNode) {
        this.node = workflowNode;
    }

    @Override
    public String getId() {
        return getPortModel().getPortId();
    }

    @Override
    public DataType getDataType() {
        return dataType;
    }

    @Override
    public void setDataType(DataType dataType) {
        this.dataType = dataType;
    }

    @Override
    public String getNodeId() {
        return getNode().getId();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ketai.data.inputService
</TITLE>

<META NAME="date" CONTENT="2012-05-23">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

ketai.data.inputService

Interfaces

IKetaiInputService

Classes

AbstractKetaiInputService

CameraService

LocationService

SensorService

redpajama_set_name: RedPajamaGithub


text:
package com.netflix.metacat.main.services;

import com.netflix.metacat.common.server.spi.MetacatCatalogConfig;
import com.netflix.metacat.main.manager.ConnectorManager;
import com.netflix.metacat.thrift.CatalogThriftService;
import com.netflix.metacat.thrift.CatalogThriftServiceFactory;

import javax.inject.Inject;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Metacat thrift service.
 *
 * @author zhenl
 * @since 1.1.0
 */
public class MetacatThriftService {
    private final ConnectorManager connectorManager;
    private final CatalogThriftServiceFactory thriftServiceFactory;

    /**
     * Constructor.
     *
     * @param catalogThriftServiceFactory factory
     * @param connectorManager            connecter manager
     */
    @Inject
    public MetacatThriftService(final CatalogThriftServiceFactory catalogThriftServiceFactory,
                                final ConnectorManager connectorManager) {
        this.thriftServiceFactory = catalogThriftServiceFactory;
        this.connectorManager = connectorManager;
    }

    protected List<CatalogThriftService> getCatalogThriftServices() {
        return connectorManager.getCatalogConfigs()
            .stream()
            .filter(MetacatCatalogConfig::isThriftInterfaceRequested)
            .map(catalog -> thriftServiceFactory.create(catalog.getCatalogName(), catalog.getThriftPort()))
            .collect(Collectors.toList());
    }

    /**
     * Start.
     *
     * @throws Exception error
     */
    public void start() throws Exception {
        for (CatalogThriftService service : getCatalogThriftServices()) {
            service.start();
        }
    }

    /**
     * Stop.
     *
     * @throws Exception error
     */
    public void stop() throws Exception {
        for (CatalogThriftService service : getCatalogThriftServices()) {
            service.stop();
        }
    }

}


text:
/**
 * @file node_helper.js
 *
 * @author fewieden
 * @license MIT
 *
 * @see  https://github.com/fewieden/MMM-Fuel
 */

/**
 * @external node_helper
 * @see https://github.com/MichMich/MagicMirror/blob/master/modules/node_modules/node_helper/index.js
 */
const NodeHelper = require('node_helper');

/**
 * @external logger
 * @see https://github.com/MichMich/MagicMirror/blob/master/js/logger.js
 */
const Log = require('logger');

/**
 * @external fs
 * @see https://nodejs.org/api/fs.html
 */
const fs = require('fs/promises');

/**
 * @external path
 * @see https://nodejs.org/api/path.html
 */
const path = require('path');

/**
 * @module node_helper
 * @description Backend for the module to query data from the API providers.
 *
 * @requires external:fs
 * @requires external:path
 * @requires external:node_helper
 * @requires external:logger
 */
module.exports = NodeHelper.create({
    /** @member {string} requiresVersion - Specifies minimum required version of MagicMirror². */
    requiresVersion: '2.15.0',

    /**
     * @function providerExists
     * @description Checks if the provider exists.
     * @async
     *
     * @param {string} providerName - Name of the provider
     *
     * @returns {boolean} Does provider exist?
     */
    async providerExists(providerName) {
        try {
            await fs.access(path.join(__dirname, 'apis', `${providerName}.js`));
            return true;
        } catch (e) {
            return false;
        }
    },

    /**
     * @function socketNotificationReceived
     * @description Receives socket notifications from the module.
     * @async
     * @override
     *
     * @param {string} notification - Notification name
     * @param {*} payload - Detailed payload of the notification.
     *
     * @returns {void}
     */
    async socketNotificationReceived(notification, payload) {
        if (notification === 'CONFIG') {
            this.config = payload;

            const providerExists = await this.providerExists(this.config.provider);

            if (providerExists) {
                // eslint-disable-next-line global-require, import/no-dynamic-require
                this.provider = await require(`./apis/${this.config.provider}`)(this.config);
                this.getData();
                setInterval(() => {
                    this.getData();
                }, this.config.updateInterval);
            } else {
                Log.error(`${this.name}: Couldn't load provider ${this.config.provider}`);
            }
        }
    },

    /**
     * @function getData
     * @description Uses API provider to get data.
     * @async
     *
     * @returns {void}
     */
    async getData() {
        try {
            const data = await this.provider.getData();
            this.sendSocketNotification('PRICELIST', data);
        } catch (e) {
            Log.error(`${this.name}: Failed to retrieve prices`, e);
        }
    }
});


text:
import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router';

import { ITeam, ITeamMember, TeamMember } from '../models/index';
import { RegisterService } from './register.service';
import { IdentityService } from '../services/index';

@Component({
    moduleId: module.id,
    templateUrl: 'register.component.html',
    styleUrls: ['register.component.css']
})
export class RegisterComponent {

    teamName: string;
    memberName: string;
    password: string;
    confirmPassword: string;
    passwordsMatch: boolean;
    error: Boolean = false;
    errorMessage: string;
    submitting: boolean = false;
    loading: boolean = false;
    activeStep: number = 1;
    teamMembers: ITeamMember[] = new Array<TeamMember>();
    @ViewChild('regForm') public registerForm: NgForm;

    constructor(
        private _router: Router,
        private _registerService: RegisterService,
        private _identityService: IdentityService) { }

    nextStep() {
        // adding team members
        if (this.activeStep === 2) {
            this.addTeamMember();
            if (this.teamMembers.length > 0) {
                this.activeStep++;
            } else {
                return;
            }
        } else if (this.activeStep === 3 && this.registerForm.valid && this.passwordsMatch) {
            this.activeStep++;
        } else if (this.registerForm.valid) {
            this.activeStep++;
        }
    }

    addTeamMember() {
        if (this.memberName && this.memberName !== '') {
            this.teamMembers.push(new TeamMember(this.memberName));
            this.memberName = '';
        }
    }

    passwordChanged(value: any) {
        this.passwordsMatch = (this.password === this.confirmPassword);
        if (this.passwordsMatch) {
            this.activeStep = 4;
        }
    }

    onRegister() {
        this.submitting = true;
        this.error = false;

        this._registerService.registerTeam({
            teamName: this.teamName,
            password: this.password,
            confirmPassword: this.confirmPassword,
            eventId: 1,
            members: this.teamMembers
        })
            .subscribe(
            team => this.handleSuccess(team),
            error => this.handleRegistrationError(error));
    }

    handleSuccess(createdTeam: ITeam) {
        this.submitting = false;

        this._identityService.identity = {
            teamId: createdTeam.TeamId,
            teamName: createdTeam.Name
        };

        this._router.navigate(['/challenges/1']);
    }

    handleRegistrationError(error: any) {
        this.submitting = false;
        this.error = true;
        this.errorMessage = error;
    }

    onTryAgain() {
        this.error = false;
    }

    eventListLoadingChange(loadingState: any) {
        this.loading = loadingState;
    }

}


text:
// Code generated by go-swagger; DO NOT EDIT.

package operations

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"fmt"
	"net/http"
	"strings"

	errors "github.com/go-openapi/errors"
	loads "github.com/go-openapi/loads"
	runtime "github.com/go-openapi/runtime"
	middleware "github.com/go-openapi/runtime/middleware"
	security "github.com/go-openapi/runtime/security"
	spec "github.com/go-openapi/spec"
	strfmt "github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"

	"github.com/go-swagger/go-swagger/examples/oauth2/restapi/operations/customers"

	models "github.com/go-swagger/go-swagger/examples/oauth2/models"
)

// NewOauthSampleAPI creates a new OauthSample instance
func NewOauthSampleAPI(spec *loads.Document) *OauthSampleAPI {
	return &OauthSampleAPI{
		handlers:            make(map[string]map[string]http.Handler),
		formats:             strfmt.Default,
		defaultConsumes:     "application/json",
		defaultProduces:     "application/json",
		ServerShutdown:      func() {},
		spec:                spec,
		ServeError:          errors.ServeError,
		BasicAuthenticator:  security.BasicAuth,
		APIKeyAuthenticator: security.APIKeyAuth,
		BearerAuthenticator: security.BearerAuth,
		JSONConsumer:        runtime.JSONConsumer(),
		JSONProducer:        runtime.JSONProducer(),
		GetAuthCallbackHandler: GetAuthCallbackHandlerFunc(func(params GetAuthCallbackParams) middleware.Responder {
			return middleware.NotImplemented("operation GetAuthCallback has not yet been implemented")
		}),
		GetLoginHandler: GetLoginHandlerFunc(func(params GetLoginParams) middleware.Responder {
			return middleware.NotImplemented("operation GetLogin has not yet been implemented")
		}),
		CustomersCreateHandler: customers.CreateHandlerFunc(func(params customers.CreateParams, principal *models.Principal) middleware.Responder {
			return middleware.NotImplemented("operation CustomersCreate has not yet been implemented")
		}),
		CustomersGetIDHandler: customers.GetIDHandlerFunc(func(params customers.GetIDParams, principal *models.Principal) middleware.Responder {
			return middleware.NotImplemented("operation CustomersGetID has not yet been implemented")
		}),

		OauthSecurityAuth: func(token string, scopes []string) (*models.Principal, error) {
			return nil, errors.NotImplemented("oauth2 bearer auth (OauthSecurity) has not yet been implemented")
		},

		// default authorizer is authorized meaning no requests are blocked
		APIAuthorizer: security.Authorized(),
	}
}

/*OauthSampleAPI the oauth sample API */
type OauthSampleAPI struct {
	spec            *loads.Document
	context         *middleware.Context
	handlers        map[string]map[string]http.Handler
	formats         strfmt.Registry
	defaultConsumes string
	defaultProduces string
	Middleware      func(middleware.Builder) http.Handler

	// BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function.
	// It has a default implemention in the security package, however you can replace it for your particular usage.
	BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator
	// APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function.
	// It has a default implemention in the security package, however you can replace it for your particular usage.
	APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator
	// BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function.
	// It has a default implemention in the security package, however you can replace it for your particular usage.
	BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator

	// JSONConsumer registers a consumer for a "application/json" mime type
	JSONConsumer runtime.Consumer

	// JSONProducer registers a producer for a "application/json" mime type
	JSONProducer runtime.Producer

	// OauthSecurityAuth registers a function that takes an access token and a collection of required scopes and returns a principal
	// it performs authentication based on an oauth2 bearer token provided in the request
	OauthSecurityAuth func(string, []string) (*models.Principal, error)

	// APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal
	APIAuthorizer runtime.Authorizer

	// GetAuthCallbackHandler sets the operation handler for the get auth callback operation
	GetAuthCallbackHandler GetAuthCallbackHandler
	// GetLoginHandler sets the operation handler for the get login operation
	GetLoginHandler GetLoginHandler
	// CustomersCreateHandler sets the operation handler for the create operation
	CustomersCreateHandler customers.CreateHandler
	// CustomersGetIDHandler sets the operation handler for the get Id operation
	CustomersGetIDHandler customers.GetIDHandler

	// ServeError is called when an error is received, there is a default handler
	// but you can set your own with this
	ServeError func(http.ResponseWriter, *http.Request, error)

	// ServerShutdown is called when the HTTP(S) server is shut down and done
	// handling all active connections and does not accept connections any more
	ServerShutdown func()

	// Custom command line argument groups with their descriptions
	CommandLineOptionsGroups []swag.CommandLineOptionsGroup

	// User defined logger function.
	Logger func(string, ...interface{})
}

// SetDefaultProduces sets the default produces media type
func (o *OauthSampleAPI) SetDefaultProduces(mediaType string) {
	o.defaultProduces = mediaType
}

// SetDefaultConsumes returns the default consumes media type
func (o *OauthSampleAPI) SetDefaultConsumes(mediaType string) {
	o.defaultConsumes = mediaType
}

// SetSpec sets a spec that will be served for the clients.
func (o *OauthSampleAPI) SetSpec(spec *loads.Document) {
	o.spec = spec
}

// DefaultProduces returns the default produces media type
func (o *OauthSampleAPI) DefaultProduces() string {
	return o.defaultProduces
}

// DefaultConsumes returns the default consumes media type
func (o *OauthSampleAPI) DefaultConsumes() string {
	return o.defaultConsumes
}

// Formats returns the registered string formats
func (o *OauthSampleAPI) Formats() strfmt.Registry {
	return o.formats
}

// RegisterFormat registers a custom format validator
func (o *OauthSampleAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) {
	o.formats.Add(name, format, validator)
}

// Validate validates the registrations in the OauthSampleAPI
func (o *OauthSampleAPI) Validate() error {
	var unregistered []string

	if o.JSONConsumer == nil {
		unregistered = append(unregistered, "JSONConsumer")
	}

	if o.JSONProducer == nil {
		unregistered = append(unregistered, "JSONProducer")
	}

	if o.OauthSecurityAuth == nil {
		unregistered = append(unregistered, "OauthSecurityAuth")
	}

	if o.GetAuthCallbackHandler == nil {
		unregistered = append(unregistered, "GetAuthCallbackHandler")
	}

	if o.GetLoginHandler == nil {
		unregistered = append(unregistered, "GetLoginHandler")
	}

	if o.CustomersCreateHandler == nil {
		unregistered = append(unregistered, "customers.CreateHandler")
	}

	if o.CustomersGetIDHandler == nil {
		unregistered = append(unregistered, "customers.GetIDHandler")
	}

	if len(unregistered) > 0 {
		return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", "))
	}

	return nil
}

// ServeErrorFor gets a error handler for a given operation id
func (o *OauthSampleAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) {
	return o.ServeError
}

// AuthenticatorsFor gets the authenticators for the specified security schemes
func (o *OauthSampleAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator {

	result := make(map[string]runtime.Authenticator)
	for name, scheme := range schemes {
		switch name {

		case "OauthSecurity":

			result[name] = o.BearerAuthenticator(scheme.Name, func(token string, scopes []string) (interface{}, error) {
				return o.OauthSecurityAuth(token, scopes)
			})

		}
	}
	return result

}

// Authorizer returns the registered authorizer
func (o *OauthSampleAPI) Authorizer() runtime.Authorizer {

	return o.APIAuthorizer

}

// ConsumersFor gets the consumers for the specified media types
func (o *OauthSampleAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer {

	result := make(map[string]runtime.Consumer)
	for _, mt := range mediaTypes {
		switch mt {

		case "application/json":
			result["application/json"] = o.JSONConsumer

		}
	}
	return result

}

// ProducersFor gets the producers for the specified media types
func (o *OauthSampleAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer {

	result := make(map[string]runtime.Producer)
	for _, mt := range mediaTypes {
		switch mt {

		case "application/json":
			result["application/json"] = o.JSONProducer

		}
	}
	return result

}

// HandlerFor gets a http.Handler for the provided operation method and path
func (o *OauthSampleAPI) HandlerFor(method, path string) (http.Handler, bool) {
	if o.handlers == nil {
		return nil, false
	}
	um := strings.ToUpper(method)
	if _, ok := o.handlers[um]; !ok {
		return nil, false
	}
	if path == "/" {
		path = ""
	}
	h, ok := o.handlers[um][path]
	return h, ok
}

// Context returns the middleware context for the oauth sample API
func (o *OauthSampleAPI) Context() *middleware.Context {
	if o.context == nil {
		o.context = middleware.NewRoutableContext(o.spec, o, nil)
	}

	return o.context
}

func (o *OauthSampleAPI) initHandlerCache() {
	o.Context() // don't care about the result, just that the initialization happened

	if o.handlers == nil {
		o.handlers = make(map[string]map[string]http.Handler)
	}

	if o.handlers["GET"] == nil {
		o.handlers["GET"] = make(map[string]http.Handler)
	}
	o.handlers["GET"]["/auth/callback"] = NewGetAuthCallback(o.context, o.GetAuthCallbackHandler)

	if o.handlers["GET"] == nil {
		o.handlers["GET"] = make(map[string]http.Handler)
	}
	o.handlers["GET"]["/login"] = NewGetLogin(o.context, o.GetLoginHandler)

	if o.handlers["POST"] == nil {
		o.handlers["POST"] = make(map[string]http.Handler)
	}
	o.handlers["POST"]["/customers"] = customers.NewCreate(o.context, o.CustomersCreateHandler)

	if o.handlers["GET"] == nil {
		o.handlers["GET"] = make(map[string]http.Handler)
	}
	o.handlers["GET"]["/customers"] = customers.NewGetID(o.context, o.CustomersGetIDHandler)

}

// Serve creates a http handler to serve the API over HTTP
// can be used directly in http.ListenAndServe(":8000", api.Serve(nil))
func (o *OauthSampleAPI) Serve(builder middleware.Builder) http.Handler {
	o.Init()

	if o.Middleware != nil {
		return o.Middleware(builder)
	}
	return o.context.APIHandler(builder)
}

// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit
func (o *OauthSampleAPI) Init() {
	if len(o.handlers) == 0 {
		o.initHandlerCache()
	}
}


text:
"""Unit tests for Superset"""
import json
import pytest
import prison
from sqlalchemy.sql import func

import tests.integration_tests.test_app
from superset import db
from superset.models.core import CssTemplate
from superset.utils.database import get_example_database

from tests.integration_tests.base_tests import SupersetTestCase

CSS_TEMPLATES_FIXTURE_COUNT = 5

class TestCssTemplateApi(SupersetTestCase):
    def insert_css_template(
        self,
        template_name: str,
        css: str,
        created_by_username: str = "admin",
    ) -> CssTemplate:
        admin = self.get_user(created_by_username)
        css_template = CssTemplate(
            template_name=template_name, css=css, created_by=admin, changed_by=admin
        )
        db.session.add(css_template)
        db.session.commit()
        return css_template

    @pytest.fixture()
    def create_css_templates(self):
        with self.create_app().app_context():
            css_templates = []
            for cx in range(CSS_TEMPLATES_FIXTURE_COUNT):
                css_templates.append(
                    self.insert_css_template(
                        template_name=f"template_name{cx}", css=f"css{cx}"
                    )
                )
            yield css_templates

            # rollback changes
            for css_template in css_templates:
                db.session.delete(css_template)
            db.session.commit()

    @pytest.mark.usefixtures("create_css_templates")
    def test_get_list_css_template(self):
        """
        CSS Template API: Test get list css template
        """
        css_templates = db.session.query(CssTemplate).all()

        self.login(username="admin")
        uri = f"api/v1/css_template/"
        rv = self.get_assert_metric(uri, "get_list")
        assert rv.status_code == 200
        data = json.loads(rv.data.decode("utf-8"))
        assert data["count"] == len(css_templates)
        expected_columns = [
            "changed_by",
            "changed_on_delta_humanized",
            "created_by",
            "created_on",
            "css",
            "id",
            "template_name",
        ]
        result_columns = list(data["result"][0].keys())
        result_columns.sort()
        assert expected_columns == result_columns
        created_by_columns = list(data["result"][0]["created_by"].keys())
        created_by_columns.sort()
        assert ["first_name", "id", "last_name"] == created_by_columns
        changed_by_columns = list(data["result"][0]["changed_by"].keys())
        changed_by_columns.sort()
        assert ["first_name", "id", "last_name"] == changed_by_columns

    @pytest.mark.usefixtures("create_css_templates")
    def test_get_list_sort_css_template(self):
        """
        CSS Template API: Test get list and sort CSS Template
        """
        css_templates = (
            db.session.query(CssTemplate)
            .order_by(CssTemplate.template_name.asc())
            .all()
        )
        self.login(username="admin")
        query_string = {"order_column": "template_name", "order_direction": "asc"}
        uri = f"api/v1/css_template/?q={prison.dumps(query_string)}"
        rv = self.get_assert_metric(uri, "get_list")
        assert rv.status_code == 200
        data = json.loads(rv.data.decode("utf-8"))
        assert data["count"] == len(css_templates)
        for i, query in enumerate(css_templates):
            assert query.template_name == data["result"][i]["template_name"]

    @pytest.mark.usefixtures("create_css_templates")
    def test_get_list_custom_filter_css_template(self):
        """
        CSS Template API: Test get list and custom filter
        """
        self.login(username="admin")

        all_css_templates = (
            db.session.query(CssTemplate).filter(CssTemplate.css.ilike("%css2%")).all()
        )
        query_string = {
            "filters": [
                {
                    "col": "template_name",
                    "opr": "css_template_all_text",
                    "value": "css2",
                }
            ],
        }
        uri = f"api/v1/css_template/?q={prison.dumps(query_string)}"
        rv = self.get_assert_metric(uri, "get_list")
        assert rv.status_code == 200
        data = json.loads(rv.data.decode("utf-8"))
        assert data["count"] == len(all_css_templates)

        all_css_templates = (
            db.session.query(CssTemplate)
            .filter(CssTemplate.template_name.ilike("%template_name3%"))
            .all()
        )
        query_string = {
            "filters": [
                {
                    "col": "template_name",
                    "opr": "css_template_all_text",
                    "value": "template_name3",
                }
            ],
        }
        uri = f"api/v1/css_template/?q={prison.dumps(query_string)}"
        rv = self.get_assert_metric(uri, "get_list")
        assert rv.status_code == 200
        data = json.loads(rv.data.decode("utf-8"))
        assert data["count"] == len(all_css_templates)

    def test_info_css_template(self):
        """
        CssTemplate API: Test info
        """
        self.login(username="admin")
        uri = f"api/v1/css_template/_info"
        rv = self.get_assert_metric(uri, "info")
        assert rv.status_code == 200

    def test_info_security_css_template(self):
        """
        CssTemplate API: Test info security
        """
        self.login(username="admin")
        params = {"keys": ["permissions"]}
        uri = f"api/v1/css_template/_info?q={prison.dumps(params)}"
        rv = self.get_assert_metric(uri, "info")
        data = json.loads(rv.data.decode("utf-8"))
        assert rv.status_code == 200
        assert "can_read" in data["permissions"]
        assert "can_write" in data["permissions"]
        assert len(data["permissions"]) == 2

    @pytest.mark.usefixtures("create_css_templates")
    def test_get_css_template(self):
        """
        CSS Template API: Test get CSS Template
        """
        css_template = (
            db.session.query(CssTemplate)
            .filter(CssTemplate.template_name == "template_name1")
            .one_or_none()
        )
        self.login(username="admin")
        uri = f"api/v1/css_template/{css_template.id}"
        rv = self.get_assert_metric(uri, "get")
        assert rv.status_code == 200

        expected_result = {
            "id": css_template.id,
            "template_name": "template_name1",
            "css": "css1",
            "created_by": {
                "first_name": css_template.created_by.first_name,
                "id": css_template.created_by.id,
                "last_name": css_template.created_by.last_name,
            },
        }
        data = json.loads(rv.data.decode("utf-8"))
        for key, value in data["result"].items():
            assert value == expected_result[key]

    @pytest.mark.usefixtures("create_css_templates")
    def test_get_css_template_not_found(self):
        """
        CSS Template API: Test get CSS Template not found
        """
        max_id = db.session.query(func.max(CssTemplate.id)).scalar()
        self.login(username="admin")
        uri = f"api/v1/css_template/{max_id + 1}"
        rv = self.get_assert_metric(uri, "get")
        assert rv.status_code == 404

    def test_create_css_template(self):
        """
        CSS Template API: Test create
        """
        post_data = {
            "template_name": "template_name_create",
            "css": "css_create",
        }

        self.login(username="admin")
        uri = f"api/v1/css_template/"
        rv = self.post_assert_metric(uri, post_data, "post")
        data = json.loads(rv.data.decode("utf-8"))
        assert rv.status_code == 201

        css_template_id = data.get("id")
        model = db.session.query(CssTemplate).get(css_template_id)
        for key in post_data:
            assert getattr(model, key) == data["result"][key]

        # Rollback changes
        db.session.delete(model)
        db.session.commit()

    @pytest.mark.usefixtures("create_css_templates")
    def test_update_css_template(self):
        """
        CSS Template API: Test update
        """
        css_template = (
            db.session.query(CssTemplate)
            .filter(CssTemplate.template_name == "template_name1")
            .all()[0]
        )

        put_data = {
            "template_name": "template_name_changed",
            "css": "css_changed",
        }

        self.login(username="admin")
        uri = f"api/v1/css_template/{css_template.id}"
        rv = self.put_assert_metric(uri, put_data, "put")
        assert rv.status_code == 200

        model = db.session.query(CssTemplate).get(css_template.id)
        assert model.template_name == "template_name_changed"
        assert model.css == "css_changed"

    @pytest.mark.usefixtures("create_css_templates")
    def test_update_css_template_not_found(self):
        """
        CSS Template API: Test update not found
        """
        max_id = db.session.query(func.max(CssTemplate.id)).scalar()
        self.login(username="admin")

        put_data = {
            "template_name": "template_name_changed",
            "css": "css_changed",
        }

        uri = f"api/v1/css_template/{max_id + 1}"
        rv = self.put_assert_metric(uri, put_data, "put")
        assert rv.status_code == 404

    @pytest.mark.usefixtures("create_css_templates")
    def test_delete_css_template(self):
        """
        CSS Template API: Test delete
        """
        css_template = (
            db.session.query(CssTemplate)
            .filter(CssTemplate.template_name == "template_name1")
            .one_or_none()
        )

        self.login(username="admin")
        uri = f"api/v1/css_template/{css_template.id}"
        rv = self.delete_assert_metric(uri, "delete")
        assert rv.status_code == 200

        model = db.session.query(CssTemplate).get(css_template.id)
        assert model is None

    @pytest.mark.usefixtures("create_css_templates")
    def test_delete_css_template_not_found(self):
        """
        CSS Template API: Test delete not found
        """
        max_id = db.session.query(func.max(CssTemplate.id)).scalar()
        self.login(username="admin")
        uri = f"api/v1/css_template/{max_id + 1}"
        rv = self.delete_assert_metric(uri, "delete")
        assert rv.status_code == 404

    @pytest.mark.usefixtures("create_css_templates")
    def test_delete_bulk_css_templates(self):
        """
        CSS Template API: Test delete bulk
        """
        css_templates = db.session.query(CssTemplate).all()
        css_template_ids = [css_template.id for css_template in css_templates]

        self.login(username="admin")
        uri = f"api/v1/css_template/?q={prison.dumps(css_template_ids)}"
        rv = self.delete_assert_metric(uri, "bulk_delete")
        assert rv.status_code == 200
        response = json.loads(rv.data.decode("utf-8"))
        expected_response = {
            "message": f"Deleted {len(css_template_ids)} css templates"
        }
        assert response == expected_response
        css_templates = db.session.query(CssTemplate).all()
        assert css_templates == []

    @pytest.mark.usefixtures("create_css_templates")
    def test_delete_one_bulk_css_templates(self):
        """
        CSS Template API: Test delete one in bulk
        """
        css_template = db.session.query(CssTemplate).first()
        css_template_ids = [css_template.id]

        self.login(username="admin")
        uri = f"api/v1/css_template/?q={prison.dumps(css_template_ids)}"
        rv = self.delete_assert_metric(uri, "bulk_delete")
        assert rv.status_code == 200
        response = json.loads(rv.data.decode("utf-8"))
        expected_response = {"message": f"Deleted {len(css_template_ids)} css template"}
        assert response == expected_response
        css_template_ = db.session.query(CssTemplate).get(css_template_ids[0])
        assert css_template_ is None

    def test_delete_bulk_css_template_bad_request(self):
        """
        CSS Template API: Test delete bulk bad request
        """
        css_template_ids = [1, "a"]
        self.login(username="admin")
        uri = f"api/v1/css_template/?q={prison.dumps(css_template_ids)}"
        rv = self.delete_assert_metric(uri, "bulk_delete")
        assert rv.status_code == 400

    @pytest.mark.usefixtures("create_css_templates")
    def test_delete_bulk_css_template_not_found(self):
        """
        CSS Template API: Test delete bulk not found
        """
        max_id = db.session.query(func.max(CssTemplate.id)).scalar()

        css_template_ids = [max_id + 1, max_id + 2]
        self.login(username="admin")
        uri = f"api/v1/css_template/?q={prison.dumps(css_template_ids)}"
        rv = self.delete_assert_metric(uri, "bulk_delete")
        assert rv.status_code == 404


text:
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from djblets.util.db import ConcurrencyManager
from djblets.util.fields import CounterField
from djblets.util.forms import TIMEZONE_CHOICES

from reviewboard.reviews.models import Group, ReviewRequest
from reviewboard.site.models import LocalSite

class ReviewRequestVisit(models.Model):
    """
    A recording of the last time a review request was visited by a user.

    Users have one ReviewRequestVisit entry in the database per review
    request they've visited. This is used to keep track of any updates
    to review requests they've already seen, so that we can intelligently
    inform them that new discussions have taken place.
    """
    user = models.ForeignKey(User, related_name="review_request_visits")
    review_request = models.ForeignKey(ReviewRequest, related_name="visits")
    timestamp = models.DateTimeField(_('last visited'), default=timezone.now)

    # Set this up with a ConcurrencyManager to help prevent race conditions.
    objects = ConcurrencyManager()

    def __unicode__(self):
        return u"Review request visit"

    class Meta:
        unique_together = ("user", "review_request")

class Profile(models.Model):
    """User profile.  Contains some basic configurable settings"""
    user = models.ForeignKey(User, unique=True)

    # This will redirect new users to the account settings page the first time
    # they log in (or immediately after creating an account).  This allows
    # people to fix their real name and join groups.
    first_time_setup_done = models.BooleanField(default=False,
        verbose_name=_("first time setup done"),
        help_text=_("Indicates whether the user has already gone through "
                    "the first time setup process by saving their user "
                    "preferences."))

    collapsed_diffs = models.BooleanField(default=True,
        verbose_name=_("collapsed diffs"),
        help_text=_("Indicates whether diffs should be shown in their "
                    "collapsed state by default."))
    wordwrapped_diffs = models.BooleanField(default=True,
        help_text=_("This field is unused and will be removed in a future "
                    "version."))
    syntax_highlighting = models.BooleanField(default=True,
        verbose_name=_("syntax highlighting"),
        help_text=_("Indicates whether the user wishes to see "
                    "syntax highlighting in the diffs."))
    is_private = models.BooleanField(default=False,
        verbose_name=_("profile private"),
        help_text=_("Indicates whether the user wishes to keep his/her profile "
                    "private."))
    open_an_issue = models.BooleanField(default=True,
        verbose_name=_("opens an issue"),
        help_text=_("Indicates whether the user wishes to default "
                    "to opening an issue or not."))

    # Indicate whether submitted review requests should appear in the
    # review request lists (excluding the dashboard).
    show_submitted = models.BooleanField(default=True)

    sort_review_request_columns = models.CharField(max_length=256, blank=True)
    sort_dashboard_columns = models.CharField(max_length=256, blank=True)
    sort_submitter_columns = models.CharField(max_length=256, blank=True)
    sort_group_columns = models.CharField(max_length=256, blank=True)

    review_request_columns = models.CharField(max_length=256, blank=True)
    dashboard_columns = models.CharField(max_length=256, blank=True)
    submitter_columns = models.CharField(max_length=256, blank=True)
    group_columns = models.CharField(max_length=256, blank=True)

    # A list of starred review requests. This allows users to monitor a
    # review request and receive e-mails on updates without actually being
    # on the reviewer list or commenting on the review. This is similar to
    # adding yourself to a CC list.
    starred_review_requests = models.ManyToManyField(ReviewRequest, blank=True,
                                                     related_name="starred_by")

    # A list of watched groups. This is so that users can monitor groups
    # without actually joining them, preventing e-mails being sent to the
    # user and review requests from entering the Incoming Reviews list.
    starred_groups = models.ManyToManyField(Group, blank=True,
                                            related_name="starred_by")

    # Allows per-user timezone settings
    timezone = models.CharField(choices=TIMEZONE_CHOICES, default='UTC',
                                max_length=20)

    def star_review_request(self, review_request):
        """Marks a review request as starred.

        This will mark a review request as starred for this user and
        immediately save to the database.
        """
        self.starred_review_requests.add(review_request)

        if (review_request.public and
            review_request.status == ReviewRequest.PENDING_REVIEW):
            site_profile, is_new = LocalSiteProfile.objects.get_or_create(
                user=self.user,
                local_site=review_request.local_site,
                profile=self.user.get_profile())

            if is_new:
                site_profile.save()

            site_profile.increment_starred_public_request_count()

        self.save()

    def unstar_review_request(self, review_request):
        """Marks a review request as unstarred.

        This will mark a review request as starred for this user and
        immediately save to the database.
        """
        q = self.starred_review_requests.filter(pk=review_request.pk)

        if q.count() > 0:
            self.starred_review_requests.remove(review_request)

        if (review_request.public and
            review_request.status == ReviewRequest.PENDING_REVIEW):
            site_profile, is_new = LocalSiteProfile.objects.get_or_create(
                user=self.user,
                local_site=review_request.local_site,
                profile=self.user.get_profile())

            if is_new:
                site_profile.save()

            site_profile.decrement_starred_public_request_count()

        self.save()

    def star_review_group(self, review_group):
        """Marks a review group as starred.

        This will mark a review group as starred for this user and
        immediately save to the database.
        """
        if self.starred_groups.filter(pk=review_group.pk).count() == 0:
            self.starred_groups.add(review_group)

    def unstar_review_group(self, review_group):
        """Marks a review group as unstarred.

        This will mark a review group as starred for this user and
        immediately save to the database.
        """
        if self.starred_groups.filter(pk=review_group.pk).count() > 0:
            self.starred_groups.remove(review_group)

    def __unicode__(self):
        return self.user.username

class LocalSiteProfile(models.Model):
    """User profile information specific to a LocalSite."""
    user = models.ForeignKey(User, related_name='site_profiles')
    profile = models.ForeignKey(Profile, related_name='site_profiles')
    local_site = models.ForeignKey(LocalSite, null=True, blank=True,
                                   related_name='site_profiles')

    # Counts for quickly knowing how many review requests are incoming
    # (both directly and total), outgoing (pending and total ever made),
    # and starred (public).
    direct_incoming_request_count = CounterField(
        _('direct incoming review request count'),
        initializer=
            lambda p: ReviewRequest.objects.to_user_directly(
                p.user, local_site=p.local_site).count())
    total_incoming_request_count = CounterField(
        _('total incoming review request count'),
        initializer=
            lambda p: ReviewRequest.objects.to_user(
                p.user, local_site=p.local_site).count())
    pending_outgoing_request_count = CounterField(
        _('pending outgoing review request count'),
        initializer=
            lambda p: ReviewRequest.objects.from_user(
                p.user, p.user, local_site=p.local_site).count())
    total_outgoing_request_count = CounterField(
        _('total outgoing review request count'),
        initializer=
            lambda p: ReviewRequest.objects.from_user(
                p.user, p.user, None, local_site=p.local_site).count())
    starred_public_request_count = CounterField(
        _('starred public review request count'),
        initializer=lambda p: \
            p.pk and
            (p.profile.starred_review_requests.public(
                None, local_site=p.local_site).count() or 0))

    class Meta:
        unique_together = (('user', 'local_site'),
                           ('profile', 'local_site'))

    def __unicode__(self):
        return '%s (%s)' % (self.user.username, self.local_site)

def _is_user_profile_visible(self, user=None):
    """Returns whether or not a user's profile is viewable by a given user.

    A profile is viewable if it's not marked as private, or the viewing
    user owns the profile, or the user is a staff member.
    """
    try:
        return ((user and (user == self or user.is_staff)) or
                not self.get_profile().is_private)
    except Profile.DoesNotExist:
        return True

User.is_profile_visible = _is_user_profile_visible


text:
# sbaas
from .lims_msMethod_postgresql_models import *
from SBaaS_base.postgresql_dataType_converter import postgresql_dataType_converter
from SBaaS_base.sbaas_base_query_update import sbaas_base_query_update
from SBaaS_base.sbaas_base_query_drop import sbaas_base_query_drop
from SBaaS_base.sbaas_base_query_initialize import sbaas_base_query_initialize
from SBaaS_base.sbaas_base_query_insert import sbaas_base_query_insert
from SBaaS_base.sbaas_base_query_select import sbaas_base_query_select
from SBaaS_base.sbaas_base_query_delete import sbaas_base_query_delete

from SBaaS_base.sbaas_template_query import sbaas_template_query

class lims_msMethod_query(sbaas_template_query):

    def initialize_supportedTables(self):
        '''Set the supported tables dict for
        '''
        tables_supported = {'ms_component_list':MS_component_list,
                'ms_components':MS_components,
                'ms_information':MS_information,
                'ms_method':MS_method,
                'ms_sourceparameters':MS_sourceParameters,
                        };
        self.set_supportedTables(tables_supported);

    def update_componentNames(self):
        '''update component names for quant and isotopomer methods'''
        return

    #table initializations:
    def drop_lims_msMethod(self):
        try:
            MS_components.__table__.drop(self.engine,True);
            MS_sourceParameters.__table__.drop(self.engine,True);
            MS_information.__table__.drop(self.engine,True);
            MS_method.__table__.drop(self.engine,True);
            MS_component_list.__table__.drop(self.engine,True);

        except SQLAlchemyError as e:
            print(e);
    def reset_lims_msMethod(self):
        try:
            reset = self.session.query(MS_components).delete(synchronize_session=False);
            reset = self.session.query(MS_sourceParameters).delete(synchronize_session=False);
            reset = self.session.query(MS_information).delete(synchronize_session=False);
            reset = self.session.query(MS_method).delete(synchronize_session=False);
            reset = self.session.query(MS_component_list).delete(synchronize_session=False);
            self.session.commit();
        except SQLAlchemyError as e:
            print(e);
    def initialize_lims_msMethod(self):
        try:
            MS_components.__table__.create(self.engine,True);
            MS_sourceParameters.__table__.create(self.engine,True);
            MS_information.__table__.create(self.engine,True);
            MS_method.__table__.create(self.engine,True);
            MS_component_list.__table__.create(self.engine,True);

        except SQLAlchemyError as e:
            print(e);

    def update_MSComponents_precursorFormulaAndMass(self,data_I):
        '''update rows of ms_components
        for columns of precursor_formula and precursor_exact_mass'''
        if data_I:
            for d in data_I:
                try:
                    data_update = self.session.query(MS_components).filter(
                           MS_components.met_id.like(d['met_id']),
                           MS_components.q1_mass == d['q1_mass'],
                           MS_components.q3_mass == d['q3_mass']).update(
                            {'precursor_formula':d['precursor_formula'],
                            'precursor_exactmass':d['precursor_exactmass']},
                            synchronize_session=False);
                except SQLAlchemyError as e:
                    print(e);
            self.session.commit();

    def add_MSComponents(self, data_I):
        '''add rows of ms_components'''
        pgdatatypeconverter = postgresql_dataType_converter();
        if data_I:
            for d in data_I:
                try:
                    data_add = MS_components(d
                        #d['q1_mass'],
                        #d['q3_mass'],
                        #d['ms3_mass'],
                        #d['met_name'],
                        #d['dp'],
                        #d['ep'],
                        #d['ce'],
                        #d['cxp'],
                        #d['af'],
                        #d['quantifier'],
                        #d['ms_mode'],
                        #d['ion_intensity_rank'],
                        #d['ion_abundance'],
                        #d['precursor_formula'],
                        #d['product_ion_reference'],
                        #d['product_formula'],
                        #d['production_ion_notes'],
                        #d['met_id'],
                        #d['external_reference'],
                        #d['q1_mass_units'],
                        #d['q3_mass_units'],
                        #d['ms3_mass_units'],
                        #d['threshold_units'],
                        #d['dp_units'],
                        #d['ep_units'],
                        #d['ce_units'],
                        #d['cxp_units'],
                        #d['af_units'],
                        #d['ms_group'],
                        #d['threshold'],
                        #d['dwell_weight'],
                        #d['component_name'],
                        #pgdatatypeconverter.convert_text2PostgresqlDataType(d['ms_include']),
                        #pgdatatypeconverter.convert_text2PostgresqlDataType(d['ms_is']),
                        #pgdatatypeconverter.convert_text2List(d['precursor_fragment']),
                        #pgdatatypeconverter.convert_text2List(d['product_fragment']),
                        #d['precursor_exactmass'],
                        #d['product_exactmass'],
                        #d['ms_methodtype'],
                        #pgdatatypeconverter.convert_text2List(d['precursor_fragment_elements']),
                        #pgdatatypeconverter.convert_text2List(d['product_fragment_elements'])
                        );
                    self.session.add(data_add);
                except SQLAlchemyError as e:
                    print(e);
            self.session.commit();

    def add_MSInformation(self, data_I):
        '''add rows of ms_information'''
        if data_I:
            for d in data_I:
                try:
                    data_add = MS_information(d
                        );
                    self.session.add(data_add);
                except SQLAlchemyError as e:
                    print(e);
            self.session.commit();

    def add_MSSourceParameters(self, data_I):
        '''add rows of ms_sourceparameters'''
        if data_I:
            for d in data_I:
                try:
                    data_add = MS_sourceParameters(d
                        );
                    self.session.add(data_add);
                except SQLAlchemyError as e:
                    print(e);
            self.session.commit();

    def add_MSComponentList(self, data_I):
        '''add rows of ms_component_list'''
        if data_I:
            for d in data_I:
                try:
                    data_add = MS_component_list(d
                        #d['ms_method_id'],
                        #d['q1_mass'],
                        #d['q3_mass'],
                        #d['met_id'],
                        #d['component_name'],
                        #d['ms_methodtype']
                        );
                    self.session.add(data_add);
                except SQLAlchemyError as e:
                    print(e);
            self.session.commit();

    def add_MSMethod(self, data_I):
        '''add rows of ms_method'''
        if data_I:
            for d in data_I:
                try:
                    data_add = MS_method(d
                        #d['id'],
                        #d['ms_sourceparameters_id'],
                        #d['ms_information_id'],
                        #d['ms_experiment_id']
                                         );
                    self.session.add(data_add);
                except SQLAlchemyError as e:
                    print(e);
            self.session.commit();

    def get_Q1AndQ3MassAndMode_MSComponents(self,met_id_I):
        '''Querry q1 mass, q3 mass, and ms_mode from ms_components'''
        try:
            mscomponents = self.session.query(MS_components.q1_mass,
                    MS_components.q3_mass,
                    MS_components.ms_mode).filter(
                    MS_components.met_id.like(met_id_I)).order_by(
                    MS_components.ms_mode.asc(),
                    MS_components.q1_mass.asc(),
                    MS_components.q3_mass.asc()).all();
            mscomponents_O = [];
            for msc in mscomponents:
                mscomponents_1 = {};
                mscomponents_1['met_id'] = met_id_I;
                mscomponents_1['q1_mass'] = msc.q1_mass;
                mscomponents_1['q3_mass'] = msc.q3_mass;
                mscomponents_1['ms_mode'] = msc.ms_mode;
                mscomponents_O.append(mscomponents_1);
            return mscomponents_O;
        except SQLAlchemyError as e:
            print(e);

    def get_row_MSComponents(self,met_id_I,ms_mode_I,ms_methodtype_I):
        '''Querry row from ms_components by met_id, ms_mode, and ms_methodtype'''
        try:
            mscomponents = self.session.query(MS_components.q1_mass,MS_components.q3_mass,
                    MS_components.ms3_mass,MS_components.met_name,MS_components.dp,
                    MS_components.ep,MS_components.ce,MS_components.cxp,MS_components.af,
                    MS_components.quantifier,MS_components.ms_mode,MS_components.ion_intensity_rank,
                    MS_components.ion_abundance,MS_components.precursor_formula,
                    MS_components.product_ion_reference,MS_components.product_formula,
                    MS_components.production_ion_notes,MS_components.met_id,
                    MS_components.external_reference,MS_components.q1_mass_units,
                    MS_components.q3_mass_units,MS_components.ms3_mass_units,
                    MS_components.threshold_units,MS_components.dp_units,
                    MS_components.ep_units,MS_components.ce_units,
                    MS_components.cxp_units,MS_components.af_units,
                    MS_components.ms_group,MS_components.threshold,
                    MS_components.dwell_weight,MS_components.component_name,
                    MS_components.ms_include,MS_components.ms_is,MS_components.precursor_fragment,
                    MS_components.product_fragment,MS_components.precursor_exactmass,
                    MS_components.product_exactmass,MS_components.ms_methodtype).filter(
                    MS_components.met_id.like(met_id_I),
                    MS_components.ms_mode.like(ms_mode_I),
                    MS_components.ms_methodtype.like(ms_methodtype_I)).all();
            mscomponents_O = [];
            if not mscomponents:
                print('bad query for row in ms_components: ')
                print('met_id: ' + met_id_I + ', ms_mode_I: ' + ms_mode_I + ', ms_methodtype_I: ' + ms_methodtype_I);
                exit(-1)
            for msc in mscomponents:
                mscomponents_1 = {};
                mscomponents_1["q1_mass"] = msc.q1_mass;
                mscomponents_1["q3_mass"] = msc.q3_mass;
                mscomponents_1["ms3_mass"] = msc.ms3_mass;
                mscomponents_1["met_name"] = msc.met_name;
                mscomponents_1["dp"] = msc.dp;
                mscomponents_1["ep"] = msc.ep;
                mscomponents_1["ce"] = msc.ce;
                mscomponents_1["cxp"] = msc.cxp;
                mscomponents_1["af"] = msc.af;
                mscomponents_1["quantifier"] = msc.quantifier;
                mscomponents_1["ms_mode"] = msc.ms_mode;
                mscomponents_1["ion_intensity_rank"] = msc.ion_intensity_rank;
                mscomponents_1["ion_abundance"] = msc.ion_abundance;
                mscomponents_1["precursor_formula"] = msc.precursor_formula;
                mscomponents_1["product_ion_reference"] = msc.product_ion_reference;
                mscomponents_1["product_formula"] = msc.product_formula;
                mscomponents_1["production_ion_notes"] = msc.production_ion_notes;
                mscomponents_1["met_id"] = msc.met_id;
                mscomponents_1["external_reference"] = msc.external_reference;
                mscomponents_1["q1_mass_units"] = msc.q1_mass_units;
                mscomponents_1["q3_mass_units"] = msc.q3_mass_units;
                mscomponents_1["ms3_mass_units"] = msc.ms3_mass_units;
                mscomponents_1["threshold_units"] = msc.threshold_units;
                mscomponents_1["dp_units"] = msc.dp_units;
                mscomponents_1["ep_units"] = msc.ep_units;
                mscomponents_1["ce_units"] = msc.ce_units;
                mscomponents_1["cxp_units"] = msc.cxp_units;
                mscomponents_1["af_units"] = msc.af_units;
                mscomponents_1["ms_group"] = msc.ms_group;
                mscomponents_1["threshold"] = msc.threshold;
                mscomponents_1["dwell_weight"] = msc.dwell_weight;
                mscomponents_1["component_name"] = msc.component_name;
                mscomponents_1["ms_include"] = msc.ms_include;
                mscomponents_1["ms_is"] = msc.ms_is;
                mscomponents_1["precursor_fragment"] = msc.precursor_fragment;
                mscomponents_1["product_fragment"] = msc.product_fragment;
                mscomponents_1["precursor_exactmass"] = msc.precursor_exactmass;
                mscomponents_1["product_exactmass"] = msc.product_exactmass;
                mscomponents_1["ms_methodtype"] = msc.ms_methodtype;
                mscomponents_O.append(mscomponents_1);
            return mscomponents_O;
        except SQLAlchemyError as e:
            print(e);

    def get_row_MSComponents_metIDAndFormula(self,met_id_I,precursor_formula_I,
                                             product_formula_I,ms_methodtype_I):
        '''Querry row from ms_components by met_id, precursor_formula, product_formula'''
        try:
            mscomponents = self.session.query(MS_components.q1_mass,MS_components.q3_mass,
                    MS_components.ms3_mass,MS_components.met_name,MS_components.dp,
                    MS_components.ep,MS_components.ce,MS_components.cxp,MS_components.af,
                    MS_components.quantifier,MS_components.ms_mode,MS_components.ion_intensity_rank,
                    MS_components.ion_abundance,MS_components.precursor_formula,
                    MS_components.product_ion_reference,MS_components.product_formula,
                    MS_components.production_ion_notes,MS_components.met_id,
                    MS_components.external_reference,MS_components.q1_mass_units,
                    MS_components.q3_mass_units,MS_components.ms3_mass_units,
                    MS_components.threshold_units,MS_components.dp_units,
                    MS_components.ep_units,MS_components.ce_units,
                    MS_components.cxp_units,MS_components.af_units,
                    MS_components.ms_group,MS_components.threshold,
                    MS_components.dwell_weight,MS_components.component_name,
                    MS_components.ms_include,MS_components.ms_is,MS_components.precursor_fragment,
                    MS_components.product_fragment,MS_components.precursor_exactmass,
                    MS_components.product_exactmass,MS_components.ms_methodtype).filter(
                    MS_components.met_id.like(met_id_I),
                    MS_components.precursor_formula.like(precursor_formula_I),
                    MS_components.product_formula.like(product_formula_I),
                    MS_components.ms_methodtype.like(ms_methodtype_I)).all();
            mscomponents_O = [];
            if not mscomponents:
                print('bad query for row in ms_components: ')
                print('met_id: ' + met_id_I + ', precursor_formula_I: ' + precursor_formula_I + ', product_formula_I: ' + product_formula_I + ', ms_methodtype_I: ' + ms_methodtype_I);
                exit(-1)
            for msc in mscomponents:
                mscomponents_1 = {};
                mscomponents_1["q1_mass"] = msc.q1_mass;
                mscomponents_1["q3_mass"] = msc.q3_mass;
                mscomponents_1["ms3_mass"] = msc.ms3_mass;
                mscomponents_1["met_name"] = msc.met_name;
                mscomponents_1["dp"] = msc.dp;
                mscomponents_1["ep"] = msc.ep;
                mscomponents_1["ce"] = msc.ce;
                mscomponents_1["cxp"] = msc.cxp;
                mscomponents_1["af"] = msc.af;
                mscomponents_1["quantifier"] = msc.quantifier;
                mscomponents_1["ms_mode"] = msc.ms_mode;
                mscomponents_1["ion_intensity_rank"] = msc.ion_intensity_rank;
                mscomponents_1["ion_abundance"] = msc.ion_abundance;
                mscomponents_1["precursor_formula"] = msc.precursor_formula;
                mscomponents_1["product_ion_reference"] = msc.product_ion_reference;
                mscomponents_1["product_formula"] = msc.product_formula;
                mscomponents_1["production_ion_notes"] = msc.production_ion_notes;
                mscomponents_1["met_id"] = msc.met_id;
                mscomponents_1["external_reference"] = msc.external_reference;
                mscomponents_1["q1_mass_units"] = msc.q1_mass_units;
                mscomponents_1["q3_mass_units"] = msc.q3_mass_units;
                mscomponents_1["ms3_mass_units"] = msc.ms3_mass_units;
                mscomponents_1["threshold_units"] = msc.threshold_units;
                mscomponents_1["dp_units"] = msc.dp_units;
                mscomponents_1["ep_units"] = msc.ep_units;
                mscomponents_1["ce_units"] = msc.ce_units;
                mscomponents_1["cxp_units"] = msc.cxp_units;
                mscomponents_1["af_units"] = msc.af_units;
                mscomponents_1["ms_group"] = msc.ms_group;
                mscomponents_1["threshold"] = msc.threshold;
                mscomponents_1["dwell_weight"] = msc.dwell_weight;
                mscomponents_1["component_name"] = msc.component_name;
                mscomponents_1["ms_include"] = msc.ms_include;
                mscomponents_1["ms_is"] = msc.ms_is;
                mscomponents_1["precursor_fragment"] = msc.precursor_fragment;
                mscomponents_1["product_fragment"] = msc.product_fragment;
                mscomponents_1["precursor_exactmass"] = msc.precursor_exactmass;
                mscomponents_1["product_exactmass"] = msc.product_exactmass;
                mscomponents_1["ms_methodtype"] = msc.ms_methodtype;
                mscomponents_O.append(mscomponents_1);
            return mscomponents_O[0];
        except SQLAlchemyError as e:
            print(e);
    def get_msGroup_componentName_MSComponents(self,component_name_I):
        '''Query component group names from the component name
        NOTE: intended to be used within a for loop'''
        try:
            component_group_name = self.session.query(MS_components.ms_group).filter(
                    MS_components.component_name.like(component_name_I)).group_by(
                    MS_components.ms_group).all();
            if len(component_group_name)>1:
                print('more than 1 component_group_name retrieved per component_name')
            component_group_name_O = component_group_name[0].ms_group;
            return component_group_name_O;
        except SQLAlchemyError as e:
            print(e);
    # Query data from ms_components
    def get_precursorFormulaAndProductFormulaAndCMapsAndPositions_metID(self,met_id_I,ms_mode_I,ms_methodtype_I):
        '''Querry precursor formulas for the ms_mode and ms_methodtype experiment'''
        try:
            component_names = self.session.query(MS_components.precursor_formula,
                    MS_components.product_formula,
                    MS_components.precursor_fragment,
                    MS_components.product_fragment,
                    MS_components.precursor_fragment_elements,
                    MS_components.product_fragment_elements).filter(
                    MS_components.met_id.like(met_id_I),
                    MS_components.ms_methodtype.like(ms_methodtype_I),
                    MS_components.ms_mode.like(ms_mode_I)).group_by(
                    MS_components.precursor_formula,
                    MS_components.product_formula,
                    MS_components.precursor_fragment,
                    MS_components.product_fragment,
                    MS_components.precursor_fragment_elements,
                    MS_components.product_fragment_elements).all();
            data_O = {};
            if not component_names: exit('bad query result: get_precursorFormulaAndProductFormulaAndCMaps_metID');
            for cn in component_names:
                data_O[cn.product_formula] = {'fragment':cn.product_fragment,
                                              'fragment_elements':cn.product_fragment_elements};
                data_O[cn.precursor_formula] = {'fragment':cn.precursor_fragment,
                                              'fragment_elements':cn.precursor_fragment_elements};
            return data_O;
        except SQLAlchemyError as e:
            print(e);

    # query precursor and product formulas from MS_components
    def get_precursorAndProductFormulas_metID(self,met_id_I,ms_mode_I,ms_methodtype_I):
        '''Querry precursor product formulas for the ms_mode and ms_methodtype experiment'''
        try:
            component_names = self.session.query(MS_components.precursor_formula,
                    MS_components.product_formula).filter(
                    MS_components.met_id.like(met_id_I),
                    MS_components.ms_methodtype.like(ms_methodtype_I),
                    MS_components.ms_mode.like(ms_mode_I)).group_by(
                    MS_components.precursor_formula,
                    MS_components.product_formula).order_by(
                    MS_components.precursor_formula.asc(),
                    MS_components.product_formula.asc()).all();
            precursor_formulas_O = [];
            product_formulas_O = [];
            if not component_names: exit('bad query result: get_productFormulas_metID');
            for cn in component_names:
                if cn.product_formula: # skip unknown fragments
                    precursor_formulas_O.append(cn.precursor_formula);
                    product_formulas_O.append(cn.product_formula);
            return precursor_formulas_O, product_formulas_O;
        except SQLAlchemyError as e:
            print(e);
    # query precursor formula from MS_components
    def get_precursorFormula_metID(self,met_id_I,ms_mode_I,ms_methodtype_I):
        '''Querry precursor formulas for the ms_mode and ms_methodtype experiment'''
        try:
            component_names = self.session.query(MS_components.precursor_formula).filter(
                    MS_components.met_id.like(met_id_I),
                    MS_components.ms_methodtype.like(ms_methodtype_I),
                    MS_components.ms_mode.like(ms_mode_I)).group_by(
                    MS_components.precursor_formula).all();
            precursor_formula_O = None;
            if not component_names: exit('bad query result: get_precursorFormula_metID');
            for cn in component_names:
                precursor_formula_O = cn[0];
            return precursor_formula_O;
        except SQLAlchemyError as e:
            print(e);
    def get_precursorFormulaAndProductFormulaAndCMaps_metID(self,met_id_I,ms_mode_I,ms_methodtype_I):
        '''Querry precursor/product formulas and fragments for the ms_mode and ms_methodtype experiment'''
        try:
            component_names = self.session.query(MS_components.precursor_formula,
                    MS_components.product_formula,
                    MS_components.precursor_fragment,
                    MS_components.product_fragment).filter(
                    MS_components.met_id.like(met_id_I),
                    MS_components.ms_methodtype.like(ms_methodtype_I),
                    MS_components.ms_mode.like(ms_mode_I)).group_by(
                    MS_components.precursor_formula,
                    MS_components.product_formula,
                    MS_components.precursor_fragment,
                    MS_components.product_fragment).all();
            data_O = {};
            if not component_names: exit('bad query result: get_precursorFormulaAndProductFormulaAndCMaps_metID');
            for cn in component_names:
                data_O[cn.product_formula] = cn.product_fragment;
                data_O[cn.precursor_formula] = cn.precursor_fragment;
            return data_O;
        except SQLAlchemyError as e:
            print(e);
    def get_precursorFormulaAndProductFormula_metID(self,met_id_I,ms_mode_I,ms_methodtype_I):
        '''Query the first precursor/product formula for the ms_mode and ms_methodtype experiment'''
        try:
            component_names = self.session.query(MS_components.precursor_formula,
                    MS_components.product_formula,
                    MS_components.q1_mass,
                    MS_components.q3_mass).filter(
                    MS_components.met_id.like(met_id_I),
                    MS_components.ms_methodtype.like(ms_methodtype_I),
                    MS_components.ms_mode.like(ms_mode_I)).group_by(
                    MS_components.precursor_formula,
                    MS_components.product_formula,
                    MS_components.q1_mass,
                    MS_components.q3_mass).order_by(
                    MS_components.q1_mass.asc(),
                    MS_components.q3_mass.asc(),
                    MS_components.precursor_formula.desc(),
                    MS_components.product_formula.desc()).all();
            data_O = {};
            product_formula_O = None;
            precursor_formula_O = None;
            if not component_names: exit('bad query result: get_precursorFormulaAndProductFormula');
            # only need the first precursor and product formulas (i.e. monoisotopic)
            product_formula_O = component_names[0].product_formula;
            precursor_formula_O = component_names[0].precursor_formula;
            for cn in component_names:
                data_O[cn.product_formula] = cn.q1_mass;
                data_O[cn.precursor_formula] = cn.q3_mass;
            return precursor_formula_O,product_formula_O;
        except SQLAlchemyError as e:
            print(e);
    def get_metIDs_msModeAndMsMethodType(self,ms_mode_I,ms_methodtype_I):
        '''Query met ids for the ms_mode and ms_methodtype experiment'''
        try:
            component_names = self.session.query(MS_components.met_id).filter(
                    MS_components.ms_methodtype.like(ms_methodtype_I),
                    MS_components.ms_mode.like(ms_mode_I)).group_by(
                    MS_components.met_id).order_by(
                    MS_components.met_id.asc()).all();
            met_id_O = [];
            if not component_names: exit('bad query result: get_metIDs_msModeAndMsMethodType');
            for cn in component_names:
                met_id_O.append(cn.met_id);
            return met_id_O;
        except SQLAlchemyError as e:
            print(e);


text:
<?php

namespace Drupal\Component\Plugin\Definition;

use Drupal\Component\Plugin\Context\ContextDefinitionInterface;
use Drupal\Component\Plugin\Exception\ContextException;

/**
 * Provides a trait for context-aware object-based plugin definitions.
 */
trait ContextAwarePluginDefinitionTrait {

  /**
   * The context definitions for this plugin definition.
   *
   * @var \Drupal\Component\Plugin\Context\ContextDefinitionInterface[]
   */
  protected $contextDefinitions = [];

  /**
   * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::hasContextDefinition().
   */
  public function hasContextDefinition($name) {
    return array_key_exists($name, $this->contextDefinitions);
  }

  /**
   * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::getContextDefinitions().
   */
  public function getContextDefinitions() {
    return $this->contextDefinitions;
  }

  /**
   * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::getContextDefinition().
   */
  public function getContextDefinition($name) {
    if ($this->hasContextDefinition($name)) {
      return $this->contextDefinitions[$name];
    }
    throw new ContextException($this->id() . " does not define a '$name' context");
  }

  /**
   * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::addContextDefinition().
   */
  public function addContextDefinition($name, ContextDefinitionInterface $definition) {
    $this->contextDefinitions[$name] = $definition;
    return $this;
  }

  /**
   * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::removeContextDefinition().
   */
  public function removeContextDefinition($name) {
    unset($this->contextDefinitions[$name]);
    return $this;
  }

}


text:
package org.teachingextensions.approvals.lite.namer;

public interface ApprovalNamer {
    String getApprovalName();

    String getSourceFilePath();
}


text:
"""Tests for floating_rate_note.py."""

from absl.testing import parameterized

import numpy as np
import tensorflow.compat.v2 as tf

import tf_quant_finance as tff
from tensorflow.python.framework import test_util  # pylint: disable=g-direct-tensorflow-import
dates = tff.datetime
instruments = tff.experimental.instruments

@test_util.run_all_in_graph_and_eager_modes
class FloatingRateNoteTest(tf.test.TestCase, parameterized.TestCase):

  @parameterized.named_parameters(
      ('DoublePrecision', np.float64),
  )
  def test_frn_correctness(self, dtype):
    settlement_date = dates.convert_to_date_tensor([(2021, 1, 15)])
    maturity_date = dates.convert_to_date_tensor([(2022, 1, 15)])
    valuation_date = dates.convert_to_date_tensor([(2021, 1, 15)])
    period_3m = dates.periods.months(3)
    flt_spec = instruments.FloatCouponSpecs(
        coupon_frequency=period_3m,
        reference_rate_term=period_3m,
        reset_frequency=period_3m,
        currency='usd',
        notional=100.,
        businessday_rule=dates.BusinessDayConvention.NONE,
        coupon_basis=0.,
        coupon_multiplier=1.,
        daycount_convention=instruments.DayCountConvention.ACTUAL_365)

    frn = instruments.FloatingRateNote(settlement_date, maturity_date,
                                       [flt_spec],
                                       dtype=dtype)

    curve_dates = valuation_date + dates.periods.months([0, 6, 12, 36])
    reference_curve = instruments.RateCurve(
        curve_dates,
        np.array([0.0, 0.005, 0.007, 0.015], dtype=dtype),
        valuation_date=valuation_date,
        dtype=dtype)
    market = instruments.InterestRateMarket(discount_curve=reference_curve,
                                            reference_curve=reference_curve)

    price = self.evaluate(frn.price(valuation_date, market))
    np.testing.assert_allclose(price, 100.0, atol=1e-6)

  @parameterized.named_parameters(
      ('DoublePrecision', np.float64),
  )
  def test_frn_correctness_fwd_start(self, dtype):
    settlement_date = dates.convert_to_date_tensor([(2021, 1, 15)])
    start_date = dates.convert_to_date_tensor([(2021, 4, 15)])
    maturity_date = dates.convert_to_date_tensor([(2022, 1, 15)])
    valuation_date = dates.convert_to_date_tensor([(2021, 1, 15)])
    period_3m = dates.periods.months(3)
    flt_spec = instruments.FloatCouponSpecs(
        coupon_frequency=period_3m,
        reference_rate_term=period_3m,
        reset_frequency=period_3m,
        currency='usd',
        notional=100.,
        businessday_rule=dates.BusinessDayConvention.NONE,
        coupon_basis=0.,
        coupon_multiplier=1.,
        daycount_convention=instruments.DayCountConvention.ACTUAL_365)

    frn = instruments.FloatingRateNote(settlement_date, maturity_date,
                                       [flt_spec],
                                       start_date=start_date,
                                       dtype=dtype)

    curve_dates = valuation_date + dates.periods.months([0, 6, 12, 36])
    reference_curve = instruments.RateCurve(
        curve_dates,
        np.array([0.0, 0.005, 0.007, 0.015], dtype=dtype),
        valuation_date=valuation_date,
        dtype=dtype)
    market = instruments.InterestRateMarket(discount_curve=reference_curve,
                                            reference_curve=reference_curve)

    price = self.evaluate(frn.price(valuation_date, market))
    np.testing.assert_allclose(price, 99.9387155246714656, atol=1e-6)

  @parameterized.named_parameters(
      ('DoublePrecision', np.float64),
  )
  def test_frn_many(self, dtype):
    settlement_date = dates.convert_to_date_tensor([(2021, 1, 15),
                                                    (2021, 1, 15)])
    maturity_date = dates.convert_to_date_tensor([(2022, 1, 15),
                                                  (2022, 1, 15)])
    valuation_date = dates.convert_to_date_tensor([(2021, 1, 15)])
    period_3m = dates.periods.months(3)
    flt_spec = instruments.FloatCouponSpecs(
        coupon_frequency=period_3m,
        reference_rate_term=period_3m,
        reset_frequency=period_3m,
        currency='usd',
        notional=100.,
        businessday_rule=dates.BusinessDayConvention.NONE,
        coupon_basis=0.,
        coupon_multiplier=1.,
        daycount_convention=instruments.DayCountConvention.ACTUAL_365)

    frn = instruments.FloatingRateNote(settlement_date, maturity_date,
                                       [flt_spec, flt_spec],
                                       dtype=dtype)

    curve_dates = valuation_date + dates.periods.months([0, 6, 12, 36])
    reference_curve = instruments.RateCurve(
        curve_dates,
        np.array([0.0, 0.005, 0.007, 0.015], dtype=dtype),
        valuation_date=valuation_date,
        dtype=dtype)
    market = instruments.InterestRateMarket(discount_curve=reference_curve,
                                            reference_curve=reference_curve)

    price = self.evaluate(frn.price(valuation_date, market))
    np.testing.assert_allclose(price, [100.0, 100.0], atol=1e-6)

  @parameterized.named_parameters(
      ('DoublePrecision', np.float64),
  )
  def test_frn_basis(self, dtype):
    settlement_date = dates.convert_to_date_tensor([(2021, 1, 1)])
    maturity_date = dates.convert_to_date_tensor([(2022, 1, 1)])
    valuation_date = dates.convert_to_date_tensor([(2021, 1, 1)])
    period_3m = dates.periods.months(3)
    flt_spec = instruments.FloatCouponSpecs(
        coupon_frequency=period_3m,
        reference_rate_term=period_3m,
        reset_frequency=period_3m,
        currency='usd',
        notional=100.,
        businessday_rule=dates.BusinessDayConvention.NONE,
        coupon_basis=0.01,
        coupon_multiplier=1.,
        daycount_convention=instruments.DayCountConvention.ACTUAL_365)

    frn = instruments.FloatingRateNote(settlement_date, maturity_date,
                                       [flt_spec],
                                       dtype=dtype)

    curve_dates = valuation_date + dates.periods.months([0, 6, 12, 36])
    reference_curve = instruments.RateCurve(
        curve_dates,
        np.array([0.001, 0.005, 0.007, 0.015], dtype=dtype),
        valuation_date=valuation_date,
        dtype=dtype)
    market = instruments.InterestRateMarket(discount_curve=reference_curve,
                                            reference_curve=reference_curve)

    price = self.evaluate(frn.price(valuation_date, market))
    np.testing.assert_allclose(price, 100.996314114175, atol=1e-7)

  @parameterized.named_parameters(
      ('DoublePrecision', np.float64),
  )
  def test_frn_stub_begin(self, dtype):
    settlement_date = dates.convert_to_date_tensor([(2021, 3, 1)])
    maturity_date = dates.convert_to_date_tensor([(2022, 1, 1)])
    valuation_date = dates.convert_to_date_tensor([(2021, 3, 1)])
    first_coupon_date = dates.convert_to_date_tensor([(2021, 4, 1)])
    period_3m = dates.periods.months(3)
    flt_spec = instruments.FloatCouponSpecs(
        coupon_frequency=period_3m,
        reference_rate_term=period_3m,
        reset_frequency=period_3m,
        currency='usd',
        notional=100.,
        businessday_rule=dates.BusinessDayConvention.NONE,
        coupon_basis=0.01,
        coupon_multiplier=1.,
        daycount_convention=instruments.DayCountConvention.ACTUAL_365)

    frn = instruments.FloatingRateNote(settlement_date, maturity_date,
                                       [flt_spec],
                                       first_coupon_date=first_coupon_date,
                                       dtype=dtype)

    curve_dates = valuation_date + dates.periods.months([0, 6, 12, 36])
    reference_curve = instruments.RateCurve(
        curve_dates,
        np.array([0.001, 0.005, 0.007, 0.015], dtype=dtype),
        valuation_date=valuation_date,
        dtype=dtype)
    market = instruments.InterestRateMarket(discount_curve=reference_curve,
                                            reference_curve=reference_curve)

    price = self.evaluate(frn.price(valuation_date, market))
    np.testing.assert_allclose(price, 100.83591541528823, atol=1e-7)

  @parameterized.named_parameters(
      ('DoublePrecision', np.float64),
  )
  def test_frn_stub_end(self, dtype):
    settlement_date = dates.convert_to_date_tensor([(2021, 1, 1)])
    maturity_date = dates.convert_to_date_tensor([(2022, 2, 1)])
    valuation_date = dates.convert_to_date_tensor([(2021, 1, 1)])
    penultimate_coupon_date = dates.convert_to_date_tensor([(2022, 1, 1)])
    period_3m = dates.periods.months(3)
    flt_spec = instruments.FloatCouponSpecs(
        coupon_frequency=period_3m,
        reference_rate_term=period_3m,
        reset_frequency=period_3m,
        currency='usd',
        notional=100.,
        businessday_rule=dates.BusinessDayConvention.NONE,
        coupon_basis=0.01,
        coupon_multiplier=1.,
        daycount_convention=instruments.DayCountConvention.ACTUAL_365)

    frn = instruments.FloatingRateNote(
        settlement_date,
        maturity_date, [flt_spec],
        penultimate_coupon_date=penultimate_coupon_date,
        dtype=dtype)

    curve_dates = valuation_date + dates.periods.months([0, 6, 12, 36])
    reference_curve = instruments.RateCurve(
        curve_dates,
        np.array([0.001, 0.005, 0.007, 0.015], dtype=dtype),
        valuation_date=valuation_date,
        dtype=dtype)
    market = instruments.InterestRateMarket(discount_curve=reference_curve,
                                            reference_curve=reference_curve)

    price = self.evaluate(frn.price(valuation_date, market))
    np.testing.assert_allclose(price, 101.08057198860133, atol=1e-7)

if __name__ == '__main__':
  tf.test.main()


text:
Build nodemcu from source
=========================

This project basically wraps [nodemcu-firmware](https://github.com/nodemcu/nodemcu-firmware) (included as a subtree) with a Makefile that makes creating a custom build and flashing it to
the nodemcu unit easy.

Use:
----

1. modify fw/nodemcu-firmware/app/include/user_config.h and fw/nodemcu-firmware/app/include/user_modules.h to specify the modules you want to be built in.

2. make build

3. make flash

If the esp8266 is connected to a device other than /dev/ttyUSB0, specify the device using the PORT environment variable:
```
PORT=/dev/ttyUSB1 make flash
```

By default DIO mode is used to flash the device. If you want to use the QIO mode, specify it using the FLASH_MODE environment variable:
```
FLASH_MODE=qio make flash
```