text:
<?php

declare(strict_types=1);

namespace PhpCodeInliner\Analyzer\Visitor;

use PhpParser\Node;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Stmt\Class_;
use PhpParser\NodeVisitor;

/**
 * Visitor that wraps around given visitors, and filters the traversal so that only the current scope
 * is considered in the traversal
 */
final class FunctionReferenceLocatorVisitor implements NodeVisitor
{
    /**
     * @var FunctionCall[]
     */
    private $functionCalls = [];

    /**
     * {@inheritDoc}
     */
    public function beforeTraverse(array $nodes)
    {
        $this->functionCalls = [];
    }

    /**
     * {@inheritDoc}
     */
    public function enterNode(Node $node)
    {
        if ($node instanceof Node\Expr\FuncCall) {
            $this->functionCalls[] = FunctionCall::fromFunctionCall($node);
        }

        if ($node instanceof Node\Expr\MethodCall) {
            $this->functionCalls[] = FunctionCall::fromInstanceCall($node);
        }

        if ($node instanceof Node\Expr\StaticCall) {
            $this->functionCalls[] = FunctionCall::fromStaticCall($node);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function leaveNode(Node $node)
    {
    }

    /**
     * {@inheritDoc}
     */
    public function afterTraverse(array $nodes)
    {
    }

    /**
     * @return FunctionCall[]
     */
    public function getCollectedFunctionCalls() : array
    {
        return $this->functionCalls;
    }
}


text:
package com.ibm.kdd.core;

import java.io.Serializable;
import java.util.Set;

public interface Event extends Serializable {

	double getDouble(String attrName);

	int getInt(String attrName);

	String getStr(String attrName);

	String getValue(String attrName);

	void setValue(String attrName, double value);

	void setValue(String attrName, int value);

	void setValue(String attrName, String value);

	Set<String> getAttrNames();

	boolean hasAttribute(String attrName);

	int hashCode();

	boolean equals(Object obj);

	Event clone();

	Event createNew();

}

redpajama_set_name: RedPajamaGithub


text:
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<entry>

click here

</entry>
</feed>


text:
package org.sagebionetworks.repo.model.dbo;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.sagebionetworks.repo.model.StorageLocationDAO;
import org.sagebionetworks.repo.model.backup.FileHandleBackup;
import org.sagebionetworks.repo.model.dao.FileHandleMetadataType;
import org.sagebionetworks.repo.model.dbo.persistence.DBOFileHandle;
import org.sagebionetworks.repo.model.file.ExternalFileHandle;
import org.sagebionetworks.repo.model.file.ExternalObjectStoreFileHandle;
import org.sagebionetworks.repo.model.file.FileHandle;
import org.sagebionetworks.repo.model.file.GoogleCloudFileHandle;
import org.sagebionetworks.repo.model.file.ProxyFileHandle;
import org.sagebionetworks.repo.model.file.S3FileHandle;

public class FileMetadataUtilsTest {

	@Test
	public void testExternalFileMetadataRoundTrip() {
		// External
		ExternalFileHandle meta = new ExternalFileHandle();
		meta.setCreatedBy("456");
		meta.setCreatedOn(new Date());
		meta.setExternalURL("http://google.com");
		meta.setId("987");
		meta.setEtag("etag");
		meta.setFileName("fileName");
		meta.setContentType("text/plain");
		// PLFM-3466
		meta.setContentSize(12345L);
		System.out.println(meta);
		// Convert to dbo
		DBOFileHandle dbo = FileMetadataUtils.createDBOFromDTO(meta);
		assertNotNull(dbo);
		FileHandle clone = FileMetadataUtils.createDTOFromDBO(dbo);
		assertEquals(meta, clone);
	}

	@Test
	public void testExternalFileMetadataRoundTripSizeNull() {
		// External
		ExternalFileHandle meta = new ExternalFileHandle();
		meta.setCreatedBy("456");
		meta.setCreatedOn(new Date());
		meta.setExternalURL("http://google.com");
		meta.setId("987");
		meta.setEtag("etag");
		meta.setFileName("fileName");
		meta.setContentType("text/plain");
		// PLFM-3466
		meta.setContentSize(null);
		System.out.println(meta);
		// Convert to dbo
		DBOFileHandle dbo = FileMetadataUtils.createDBOFromDTO(meta);
		assertNotNull(dbo);
		FileHandle clone = FileMetadataUtils.createDTOFromDBO(dbo);
		assertEquals(meta, clone);
	}

	@Test
	public void testExternalFileMalformedURL() {
		// External
		ExternalFileHandle meta = new ExternalFileHandle();
		meta.setCreatedBy("456");
		meta.setCreatedOn(new Date());
		// malformed URL
		meta.setExternalURL("F:/file");
		meta.setId("987");
		meta.setEtag("etag");
		System.out.println(meta);
		// Convert to dbo
		assertThrows(IllegalArgumentException.class, () -> FileMetadataUtils.createDBOFromDTO(meta));
	}

	@Test
	public void testS3FileMetadataRoundTrip() {
		S3FileHandle meta = new S3FileHandle();
		meta.setCreatedBy("456");
		meta.setCreatedOn(new Date());
		meta.setId("987");
		meta.setBucketName("bucketName");
		meta.setKey("key");
		meta.setContentMd5("md5");
		meta.setContentSize(123l);
		meta.setContentType("contentType");
		meta.setPreviewId("9999");
		meta.setEtag("etag");
		meta.setFileName("foo.txt");
		meta.setIsPreview(false);

		System.out.println(meta);
		// Convert to dbo
		DBOFileHandle dbo = FileMetadataUtils.createDBOFromDTO(meta);
		assertNotNull(dbo);
		FileHandle clone = FileMetadataUtils.createDTOFromDBO(dbo);
		assertEquals(meta, clone);
	}

	@Test
	public void testGoogleCloudFileMetadataRoundTrip() {
		GoogleCloudFileHandle meta = new GoogleCloudFileHandle();
		meta.setCreatedBy("456");
		meta.setCreatedOn(new Date());
		meta.setId("987");
		meta.setBucketName("bucketName");
		meta.setKey("key");
		meta.setContentMd5("md5");
		meta.setContentSize(123l);
		meta.setContentType("contentType");
		meta.setPreviewId("9999");
		meta.setEtag("etag");
		meta.setFileName("foo.txt");
		meta.setIsPreview(false);

		System.out.println(meta);
		// Convert to dbo
		DBOFileHandle dbo = FileMetadataUtils.createDBOFromDTO(meta);
		assertNotNull(dbo);
		FileHandle clone = FileMetadataUtils.createDTOFromDBO(dbo);
		assertEquals(meta, clone);
	}

	@Test
	public void isPreviewIsAlwaysSetToFalse() {
		S3FileHandle meta = new S3FileHandle();
		meta.setCreatedBy("456");
		meta.setCreatedOn(new Date());
		meta.setId("987");
		meta.setBucketName("bucketName");
		meta.setKey("key");
		meta.setContentMd5("md5");
		meta.setContentSize(123l);
		meta.setContentType("contentType");
		meta.setPreviewId("9999");
		meta.setEtag("etag");
		meta.setFileName("foo.txt");

		// Set to null
		meta.setIsPreview(null);
		System.out.println(meta);
		// Call under test
		DBOFileHandle dbo = FileMetadataUtils.createDBOFromDTO(meta);
		assertNotNull(dbo);
		assertFalse(dbo.getIsPreview());

		// Set to false
		meta.setIsPreview(false);
		System.out.println(meta);
		// Call under test
		dbo = FileMetadataUtils.createDBOFromDTO(meta);
		assertNotNull(dbo);
		assertFalse(dbo.getIsPreview());
	}

	@Test
	public void testCreateBackupFromDBOEmpty(){
		DBOFileHandle dbo = new DBOFileHandle();
		FileHandleBackup backup = FileMetadataUtils.createBackupFromDBO(dbo);
		assertNotNull(backup);
	}

	@Test
	public void testBackupRoundTrip(){
		DBOFileHandle dbo = new DBOFileHandle();
		dbo.setBucketName("bucket");
		dbo.setContentMD5("md5");
		dbo.setContentSize(123L);
		dbo.setContentType("contentType");
		dbo.setCreatedOn(new Timestamp(1L));
		dbo.setCreatedBy(9999L);
		dbo.setEtag("etag");
		dbo.setId(456L);
		dbo.setKey("key");
		dbo.setMetadataType(FileHandleMetadataType.S3);
		dbo.setName("name");
		dbo.setPreviewId(4444L);
		dbo.setIsPreview(false);

		// to Backup
		FileHandleBackup backup = FileMetadataUtils.createBackupFromDBO(dbo);
		assertNotNull(backup);
		// Clone from the backup
		DBOFileHandle clone = FileMetadataUtils.createDBOFromBackup(backup);
		assertNotNull(clone);
		assertEquals(dbo, clone);
	}

	@Test
	public void testProxyFileHandleRoundTrip(){
		ProxyFileHandle proxy = new ProxyFileHandle();
		proxy.setFilePath("/foo/bar/cat.txt");
		proxy.setCreatedBy("456");
		proxy.setCreatedOn(new Date());
		proxy.setId("987");
		proxy.setContentMd5("md5");
		proxy.setContentSize(123l);
		proxy.setContentType("contentType");
		proxy.setEtag("etag");
		proxy.setFileName("cat.txt");

		DBOFileHandle dbo = FileMetadataUtils.createDBOFromDTO(proxy);
		assertNotNull(dbo);
		FileHandle clone = FileMetadataUtils.createDTOFromDBO(dbo);
		assertEquals(proxy, clone);
	}

	@Test
	public void testExternalObjectStoreFileHandleRoundTrip(){
		ExternalObjectStoreFileHandle externalObjFH = new ExternalObjectStoreFileHandle();
		externalObjFH.setCreatedBy("456");
		externalObjFH.setCreatedOn(new Date());
		externalObjFH.setId("987");
		externalObjFH.setContentMd5("md5");
		externalObjFH.setContentSize(123l);
		externalObjFH.setContentType("contentType");
		externalObjFH.setEtag("etag");
		externalObjFH.setFileName("cat.txt");
		externalObjFH.setFileKey("filekey");
		externalObjFH.setEndpointUrl("https//s3.amazonaws.com");
		externalObjFH.setBucket("bucketName");

		DBOFileHandle dbo = FileMetadataUtils.createDBOFromDTO(externalObjFH);
		assertNotNull(dbo);
		FileHandle clone = FileMetadataUtils.createDTOFromDBO(dbo);
		assertEquals(externalObjFH, clone);
	}

	@Test
	public void testCreateDBOsFromDTOsWithNullList(){
		assertThrows(IllegalArgumentException.class, () -> FileMetadataUtils.createDBOsFromDTOs(null));
	}

	@Test
	public void testCreateDBOsFromDTOs() {
		ExternalFileHandle external = new ExternalFileHandle();
		external.setCreatedBy("456");
		external.setCreatedOn(new Date());
		external.setExternalURL("http://google.com");
		external.setId("987");
		external.setEtag("etag");
		external.setFileName("fileName");
		external.setContentType("text/plain");
		external.setContentSize(12345L);

		S3FileHandle s3 = new S3FileHandle();
		s3.setCreatedBy("456");
		s3.setCreatedOn(new Date());
		s3.setId("987");
		s3.setBucketName("bucketName");
		s3.setKey("key");
		s3.setContentMd5("md5");
		s3.setContentSize(123l);
		s3.setContentType("contentType");
		s3.setPreviewId("9999");
		s3.setEtag("etag");
		s3.setFileName("foo.txt");
		s3.setIsPreview(false);

		ProxyFileHandle proxy = new ProxyFileHandle();
		proxy.setFilePath("/foo/bar/cat.txt");
		proxy.setCreatedBy("456");
		proxy.setCreatedOn(new Date());
		proxy.setId("987");
		proxy.setContentMd5("md5");
		proxy.setContentSize(123l);
		proxy.setContentType("contentType");
		proxy.setFileName("cat.txt");

		List<FileHandle> list = new ArrayList<FileHandle>();
		list.addAll(Arrays.asList(external, s3, proxy));
		List<DBOFileHandle> dbos = FileMetadataUtils.createDBOsFromDTOs(list);

		for (int i = 0; i < list.size(); i++) {
			assertEquals(list.get(i), FileMetadataUtils.createDTOFromDBO(dbos.get(i)));
		}
	}

	// See PLFM-6637
	@Test
	public void testBackfillDefaultStorageLocation() {
		FileHandleBackup backup = new FileHandleBackup();
		backup.setMetadataType("S3");
		backup.setBucketName(FileMetadataUtils.DEFAULT_S3_BUCKET);
		backup.setStorageLocationId(null);

		DBOFileHandle expected = new DBOFileHandle();
		expected.setBucketName(FileMetadataUtils.DEFAULT_S3_BUCKET);
		expected.setMetadataType(FileHandleMetadataType.S3);
		expected.setStorageLocationId(StorageLocationDAO.DEFAULT_STORAGE_LOCATION_ID);
		expected.setIsPreview(false);

		DBOFileHandle result = FileMetadataUtils.createDBOFromBackup(backup);

		assertEquals(expected, result);
	}

	// See PLFM-6637
	@Test
	public void testBackfillDefaultStorageLocationWithDifferentBucket() {
		FileHandleBackup backup = new FileHandleBackup();
		backup.setMetadataType("S3");
		backup.setBucketName("anotherBucket");
		backup.setStorageLocationId(null);

		DBOFileHandle expected = new DBOFileHandle();
		expected.setBucketName("anotherBucket");
		expected.setMetadataType(FileHandleMetadataType.S3);
		expected.setStorageLocationId(null);
		expected.setIsPreview(false);

		DBOFileHandle result = FileMetadataUtils.createDBOFromBackup(backup);

		assertEquals(expected, result);
	}

	// See PLFM-6637
	@Test
	public void testBackfillDefaultStorageLocationWithPresent() {
		FileHandleBackup backup = new FileHandleBackup();
		backup.setMetadataType("S3");
		backup.setBucketName(FileMetadataUtils.DEFAULT_S3_BUCKET);
		backup.setStorageLocationId(123L);

		DBOFileHandle expected = new DBOFileHandle();
		expected.setBucketName(FileMetadataUtils.DEFAULT_S3_BUCKET);
		expected.setMetadataType(FileHandleMetadataType.S3);
		expected.setStorageLocationId(123L);
		expected.setIsPreview(false);

		DBOFileHandle result = FileMetadataUtils.createDBOFromBackup(backup);

		assertEquals(expected, result);
	}

	// See PLFM-6637
	@Test
	public void testBackfillDefaultStorageLocationWithNotS3() {
		FileHandleBackup backup = new FileHandleBackup();
		backup.setMetadataType("GOOGLE_CLOUD");
		backup.setBucketName(FileMetadataUtils.DEFAULT_S3_BUCKET);
		backup.setStorageLocationId(123L);

		DBOFileHandle expected = new DBOFileHandle();
		expected.setBucketName(FileMetadataUtils.DEFAULT_S3_BUCKET);
		expected.setMetadataType(FileHandleMetadataType.GOOGLE_CLOUD);
		expected.setStorageLocationId(123L);
		expected.setIsPreview(false);

		DBOFileHandle result = FileMetadataUtils.createDBOFromBackup(backup);

		assertEquals(expected, result);
	}

}


text:
package org.keycloak.models.sessions.infinispan.entities.wildfly;

import org.keycloak.models.cache.infinispan.authorization.events.ResourceUpdatedEvent;

public class ResourceUpdatedEventWFExternalizer extends InfinispanExternalizerAdapter<ResourceUpdatedEvent> {

    public ResourceUpdatedEventWFExternalizer() {
        super(ResourceUpdatedEvent.class, new ResourceUpdatedEvent.ExternalizerImpl());
    }
}


text:
package org.qfox.jestful.client.cache.impl.http.resolver;

import java.lang.annotation.Annotation;

/**
 * HTTP cache directive resolver for method's parameter which annotated with a cache directive annotation
 *
 * @param <A> cache directive annotation
 */
public interface HttpCacheDirectiveResolver<A extends Annotation> {

    /**
     * resolve a parameter value to a http cache directive value if returns {@code null} that indicated this directive will not be presented
     *
     * @param annotation the parameter cache directive annotation
     * @param value      the parameter value
     * @return http cache directive value
     */
    String resolve(A annotation, Object value);

}


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

namespace Sepia.Globalization.Numbers.Rules
{
    class MasterRule : Rule
    {
        public override void Fire(RbnfContext context)
        {
        }

        public override bool Matches(RbnfContext context)
        {
            throw new NotImplementedException();
        }
    }
}


text:
const React = require('react')

const ContactForm = React.createClass({
  render () {
    let formClass;
    this.props.submitted ? formClass = 'formSubmit' : formClass = ''
    return (
      <form className={'contactForm ' + formClass} onSubmit={ (e) => this.props.handleSubmit(e)} >
        <input className='contactInput'
          onChange={(email)=> this.props.handleEmailChange(email)}
          type="email"
          name="email"
          placeholder="Your email" />
        <input className='contactInput'
          onChange={(phone)=> this.props.handlePhoneChange(phone)}
          type="text"
          name="phone"
          placeholder="Your phone number" />

        <textarea className='contactTextarea'
          onChange={(message)=> this.props.handleMessageChange(message)}
          name="message"
          placeholder="Your message"></textarea>

        <button className='contactSubmit' type="submit">Submit</button>
      </form>
    )
  }
})

module.exports = ContactForm


text:
"""Tests for makani.avionics.motor.motor_client.

This module uses snake case for new function names so that test functions can be
consistent with cmd.Cmd methods without offending Lint.
"""

import copy
import re
import socket
import tempfile
import textwrap
import threading
import time
import unittest

from makani.avionics.common import actuator_types
from makani.avionics.common import cmd_client
from makani.avionics.common import pack_avionics_messages
from makani.avionics.motor import motor_client
from makani.avionics.motor.firmware import flags
from makani.avionics.network import aio_node
from makani.lib.python import test_util
import numpy

_TIMEOUT = 0.01
_EPS32 = numpy.finfo(numpy.float32).eps

class MulticastListener(cmd_client.AioThread):

  def __init__(self, set_state_callback, command_callback, param_callback):
    super(MulticastListener, self).__init__(
        ['kMessageTypeControllerCommand', 'kMessageTypeDynoCommand',
         'kMessageTypeMotorSetParam', 'kMessageTypeDynoMotorSetParam',
         'kMessageTypeMotorSetState', 'kMessageTypeDynoMotorSetState',
         'kMessageTypeMotorGetParam', 'kMessageTypeDynoMotorGetParam'],
        allowed_sources=['kAioNodeControllerA', 'kAioNodeOperator'],
        timeout=_TIMEOUT)
    self._set_state_callback = set_state_callback
    self._command_callback = command_callback
    self._param_callback = param_callback

  def _RunOnce(self):
    try:
      _, header, message = self._client.Recv()
      if header.source == aio_node.kAioNodeOperator:
        if isinstance(message, pack_avionics_messages.MotorSetStateMessage):
          self._set_state_callback(message)
        elif (isinstance(message, pack_avionics_messages.MotorSetParamMessage)
              or isinstance(
                  message, pack_avionics_messages.DynoMotorSetParamMessage)):
          self._param_callback(message)
        elif (isinstance(message, pack_avionics_messages.MotorGetParamMessage)
              or isinstance(
                  message, pack_avionics_messages.DynoMotorGetParamMessage)):
          self._param_callback(message)
        elif isinstance(message, pack_avionics_messages.DynoCommandMessage):
          self._command_callback(message)
      elif header.source == aio_node.kAioNodeControllerA:
        if isinstance(message, pack_avionics_messages.ControllerCommandMessage):
          self._command_callback(message)
    except socket.timeout:
      pass

class FakeMotor(cmd_client.AioThread):

  def __init__(self, nickname):
    self._node_string = motor_client.AioNodeNameFromMotorNickname(nickname)
    self._index = motor_client.MOTORS.index(nickname)
    self._bitmask = 1 << self._index

    self._status = pack_avionics_messages.MotorStatusMessage()
    self._status.motor_status = flags.kMotorStatusInit
    self._status_lock = threading.Lock()

    self.running = False
    self.params = {v: 0.0 for v in motor_client.MOTOR_PARAMS.itervalues()}
    self.torque = 0.0
    self.speed_lower = 0.0
    self.speed_upper = 0.0

    super(FakeMotor, self).__init__(['kMessageTypeMotorStatus',
                                     'kMessageTypeMotorAckParam'],
                                    allowed_sources=[self._node_string],
                                    timeout=_TIMEOUT)

    self._multicast_listener = MulticastListener(
        self._HandleMotorSetStateMessage, self._HandleControllerCommandMessage,
        self._HandleParamMessage)

  def GetParam(self, param_name):
    return self.params[motor_client.MOTOR_PARAMS[param_name]]

  def __enter__(self):
    self.start()
    self._multicast_listener.start()
    return self

  def __exit__(self, *args):
    self._multicast_listener.Exit()
    self._multicast_listener.join()
    self.Exit()
    self.join()

  def GetStatus(self):
    with self._status_lock:
      return copy.copy(self._status)

  def GetError(self):
    with self._status_lock:
      return self._status.motor_error

  def SetError(self, error):
    with self._status_lock:
      self._status.motor_error = error
      self._status.motor_status |= flags.kMotorStatusError

  def SetWarning(self, warning):
    with self._status_lock:
      self._status.motor_warning = warning
      self._status.motor_status |= flags.kMotorStatusError

  def ClearError(self):
    with self._status_lock:
      self._status.motor_error = flags.kMotorErrorNone
      self._status.motor_status &= ~flags.kMotorStatusError

  def _HandleMotorSetStateMessage(self, message):
    if (message.selected_motors & self._bitmask
        and message.command == actuator_types.kActuatorStateCommandArm):
      with self._status_lock:
        self._status.motor_status = flags.kMotorStatusArmed

  def _HandleControllerCommandMessage(self, message):
    self.torque = message.motor_torque[self._index]
    self.speed_lower = message.motor_speed_lower_limit[self._index]
    self.speed_upper = message.motor_speed_upper_limit[self._index]

    self.running = bool(message.motor_command & flags.kMotorCommandRun)

    if message.motor_command & flags.kMotorCommandClearError:
      self.ClearError()

    if message.motor_command & flags.kMotorCommandDisarm:
      with self._status_lock:
        self._status.motor_status &= ~flags.kMotorStatusArmed

  def _HandleParamMessage(self, message):
    if message.selected_motors & self._bitmask:
      if isinstance(message, pack_avionics_messages.MotorSetParamMessage):
        self.params[message.id] = message.value
      ack = pack_avionics_messages.MotorAckParamMessage()
      ack.id = message.id
      ack.value = self.params[message.id]
      self._client.Send(ack, 'kMessageTypeMotorAckParam',
                        self._node_string)

  def _RunOnce(self):
    with self._status_lock:
      self._client.Send(self._status, 'kMessageTypeMotorStatus',
                        self._node_string)
    time.sleep(0.1)

class MotorCommandClientTest(unittest.TestCase):

  def setUp(self):
    super(MotorCommandClientTest, self).setUp()
    self.client = motor_client.MotorCommandClient()
    self.stdout = test_util.StdoutPatch()

  def tearDown(self):
    super(MotorCommandClientTest, self).tearDown()
    with self.stdout:
      self.client.onecmd('quit')

  def assert_eventually_true(self, func):
    num_tries = 30
    for i in xrange(num_tries):
      if func():
        return True
      if i < num_tries - 1:
        time.sleep(0.1)

    self.assertTrue(False)  # pylint: disable=redundant-unittest-assert

  def test_do_set_targets(self):
    with self.stdout:
      self.client.onecmd('set_targets SBO')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*SBO.*')
      self.client.onecmd('quit')

    with self.stdout:
      self.client.onecmd('set_targets SBI PTO')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*SBI.*')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*PTO.*')

  def test_do_set_targets_dyno(self):
    with self.stdout:
      self.client.onecmd('set_targets_dyno SBO')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*SBO.*')
      self.client.onecmd('quit')

    with self.stdout:
      self.client.onecmd('set_targets_dyno SBI PTO')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*SBI.*')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*PTO.*')

  def test_do_arm_fail(self):
    with self.stdout, FakeMotor('SBO'):
      self.client.onecmd('arm')
      self.assertRegexpMatches(self.stdout.Read(),
                               '(?s).*Invalid set of targets.*')

    with self.stdout, FakeMotor('SBO'):
      self.client.onecmd('set_targets SBO')
      self.client.onecmd('arm SBO')
      self.assertRegexpMatches(self.stdout.Read(),
                               '(?s).*Wrong number of arguments.*')

  def test_do_arm_succeed(self):
    with self.stdout, FakeMotor('SBO') as motor:
      self.client.onecmd('set_targets SBO')
      self.client.onecmd('arm')
      self.assertEqual(motor.GetStatus().motor_status,
                       flags.kMotorStatusArmed)
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*Successfully armed.*')

  def test_do_arm_multiple_motors(self):
    with self.stdout, FakeMotor('SBI') as sbi, FakeMotor('PTO') as pto:
      self.client.onecmd('set_targets SBI PTO')
      self.client.onecmd('arm')
      self.assertEqual(sbi.GetStatus().motor_status,
                       flags.kMotorStatusArmed)
      self.assertEqual(pto.GetStatus().motor_status,
                       flags.kMotorStatusArmed)
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*Successfully armed.*')

  def test_do_disarm(self):
    with self.stdout, FakeMotor('SBO') as motor:
      self.client.onecmd('set_targets SBO')
      self.client.onecmd('arm')
      self.client.onecmd('disarm')
      self.assertEqual(motor.GetStatus().motor_status,
                       flags.kMotorStatusInit)

  def test_do_set_param(self):
    with self.stdout, FakeMotor('SBO') as motor:
      self.client.onecmd('set_param SBO i_kp 3.14')
      self.assertRegexpMatches(self.stdout.Read(),
                               '(?s).*Setting i_kp to 3.14 on SBO.*')
      self.assertAlmostEqual(motor.GetParam('i_kp'), 3.14, places=6)

  def test_do_get_param(self):
    with self.stdout, FakeMotor('SBO'):
      self.client.onecmd('get_param SBO i_kp')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*SBO i_kp: 0[^0-9]*')

  def test_do_run_fail(self):
    with self.stdout, FakeMotor('SBO'):
      self.client.onecmd('run 1 s')
      self.assertRegexpMatches(
          self.stdout.Read(), '(?s).*Invalid set of targets.*')

    with self.stdout, FakeMotor('SBO'):
      self.client.onecmd('set_targets SBO')
      self.client.onecmd('run 1 s')
      self.assertRegexpMatches(
          self.stdout.Read(), '(?s).*Invalid(?s).*status.*')

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_run_succeed(self):
    with self.stdout, FakeMotor('SBO') as motor:
      self.client.onecmd('set_targets SBO')
      self.client.onecmd('arm')
      self.client.onecmd('run 100 s')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*Running.*')
      self.assert_eventually_true(lambda: motor.running)

  def test_do_stop_fail(self):
    with self.stdout, FakeMotor('SBO'):
      self.client.onecmd('stop')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*Not running.*')

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_stop_succeed(self):
    with self.stdout, FakeMotor('SBO') as motor:
      self.client.onecmd('set_targets SBO')
      self.client.onecmd('arm')
      self.client.onecmd('run 100 s')
      self.assert_eventually_true(lambda: motor.running)
      self.client.onecmd('stop')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*Run stopped.*')
      self.assert_eventually_true(lambda: not motor.running)

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_set_torque(self):
    with self.stdout, FakeMotor('SBI'), FakeMotor('SBO') as motor:
      self.client.onecmd('set_targets SBI')
      self.client.onecmd('set_targets_dyno SBO')
      self.client.onecmd('set_speed_limits -3.14 3.14')
      self.client.onecmd('set_torque 3.14')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*Torque desired.*')
      self.assert_eventually_true(
          lambda: abs(motor.torque - 3.14) / 3.14 < _EPS32)
      self.assert_eventually_true(
          lambda: abs(motor.speed_lower + 3.14) / 3.14 < _EPS32)
      self.assert_eventually_true(
          lambda: abs(motor.speed_upper - 3.14) / 3.14 < _EPS32)

  def test_do_set_torque_fail(self):
    with self.stdout, FakeMotor('SBO'):
      self.client.onecmd('set_torque 3.14')
      self.assertRegexpMatches(
          self.stdout.Read(), 'No dynos selected. Use "set_targets_dyno".')
      self.client.onecmd('set_targets_dyno SBO')
      self.client.onecmd('set_torque abc')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*Invalid argument.*')
      self.client.onecmd('set_torque 3.14')
      self.assertRegexpMatches(
          self.stdout.Read(), 'Omega limits not set. Use "set_speed_limits".')

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_set_speed_limits(self):
    with self.stdout, FakeMotor('SBO') as motor:
      self.client.onecmd('set_targets_dyno SBO')
      self.client.onecmd('set_speed_limits -3.14 3.14')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*Omega limits set.*')
      self.assert_eventually_true(
          lambda: abs(motor.speed_lower + 3.14) / 3.14 < _EPS32)
      self.assert_eventually_true(
          lambda: abs(motor.speed_upper - 3.14) / 3.14 < _EPS32)

  def test_do_set_speed_limits_fail(self):
    with self.stdout, FakeMotor('SBO'):
      self.client.onecmd('set_targets_dyno SBO')
      self.client.onecmd('set_speed_limits abc 20')
      self.assertRegexpMatches(
          self.stdout.Read(), '(?s).*Invalid argument.*')
      self.client.onecmd('set_speed_limits 22 20')
      self.assertRegexpMatches(
          self.stdout.Read(), '(?s).*Invalid(?s).*i.e. min value.*')

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_set_omega(self):
    with self.stdout, FakeMotor('SBO') as motor:
      self.client.onecmd('set_targets SBO')
      self.client.onecmd('set_omega 3.14')
      self.assertRegexpMatches(self.stdout.Read(), 'Omega desired: 3.14')
      self.assert_eventually_true(
          lambda: abs(motor.speed_lower - motor.speed_upper) / 3.14 < _EPS32)
      self.assert_eventually_true(
          lambda: abs(motor.speed_lower - 3.14) / 3.14 < _EPS32)
      self.assert_eventually_true(
          lambda: abs(motor.speed_upper - 3.14) / 3.14 < _EPS32)

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_ramp_omega(self):
    with self.stdout, FakeMotor('SBO') as motor:
      self.client.onecmd('set_targets SBO')
      self.client.onecmd('ramp_omega 3.14 0.0')
      self.client.onecmd('arm')
      self.client.onecmd('run 5s')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*Ramping.*')
      self.assert_eventually_true(
          lambda: abs(motor.speed_lower - 3.14) / 3.14 < _EPS32)
      self.assert_eventually_true(
          lambda: abs(motor.speed_upper - 3.14) / 3.14 < _EPS32)

      self.client.onecmd('ramp_omega 6.28 0.5')
      self.assertRegexpMatches(self.stdout.Read(), '(?s).*Ramping.*')
      self.assert_eventually_true(
          lambda: abs(motor.speed_lower - 6.28) / 6.28 < _EPS32)
      self.assert_eventually_true(
          lambda: abs(motor.speed_upper - 6.28) / 6.28 < _EPS32)

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_set_command_function_python_succeed(self):
    with tempfile.NamedTemporaryFile(suffix='.py') as python_file:
      data_length = 3*len(motor_client.MOTORS)
      python_file.write(textwrap.dedent("""
          t_step = 0.1
          t_end = 1.0
          def Cmd(t):
            command = [0.0] * %d
            command[0] = 3.14
            command[8] = 3.14
            command[16] = 3.14
            return command""" % data_length))
      python_file.flush()

      with self.stdout, FakeMotor('SBO') as motor:
        self.client.onecmd('set_targets SBO')
        self.client.onecmd('set_command_function ' + python_file.name)
        self.assertRegexpMatches(self.stdout.Read(),
                                 r'(?s).*Using %s to generate command '
                                 r'profile.*' % python_file.name)
        self.client.onecmd('arm')
        self.client.onecmd('run 10s')
        self.assert_eventually_true(
            lambda: abs(motor.torque - 3.14) / 3.14 < _EPS32)
        self.assert_eventually_true(
            lambda: abs(motor.speed_lower - 3.14) / 3.14 < _EPS32)
        self.assert_eventually_true(
            lambda: abs(motor.speed_upper - 3.14) / 3.14 < _EPS32)

  def test_do_set_command_function_python_fail(self):
    with tempfile.NamedTemporaryFile(suffix='.py') as python_file:
      python_file.write('this will raise a syntax error')
      python_file.flush()

      with self.stdout:
        self.client.onecmd('set_targets SBO')
        self.client.onecmd('set_command_function ' + python_file.name)
        self.assertRegexpMatches(self.stdout.Read(),
                                 '(?s).*Generation of lookup table from %s '
                                 'failed.*' % python_file.name)

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_set_command_function_text_succeed(self):
    with tempfile.NamedTemporaryFile(suffix='.txt') as text_file:
      text_file.write(textwrap.dedent("""
          0.0 3.14 1 1 1 1 1 1 1 3.14 1 1 1 1 1 1 1 3.14 1 1 1 1 1 1 1
          100 3.14 1 1 1 1 1 1 1 3.14 1 1 1 1 1 1 1 3.14 1 1 1 1 1 1 1"""[1:]))
      text_file.flush()

      with self.stdout, FakeMotor('SBO') as motor:
        self.client.onecmd('set_targets SBO')
        self.client.onecmd('set_command_function ' + text_file.name)
        self.assertRegexpMatches(self.stdout.Read(),
                                 r'(?s).*Using interpolated values from %s '
                                 r'for command profile.*' % text_file.name)
        self.client.onecmd('arm')
        self.client.onecmd('run 10s')
        self.assert_eventually_true(
            lambda: abs(motor.torque - 3.14) / 3.14 < _EPS32)

  def test_do_set_command_function_text_fail(self):
    with tempfile.NamedTemporaryFile(suffix='.txt') as text_file:
      text_file.write('numpy.load will raise ValueError')
      text_file.flush()

      with self.stdout:
        self.client.onecmd('set_targets SBO')
        self.client.onecmd('set_command_function ' + text_file.name)
        self.assertRegexpMatches(self.stdout.Read(),
                                 '(?s).*Invalid input text file: %s.*' %
                                 text_file.name)

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_set_command_function_limit_fail(self):
    with tempfile.NamedTemporaryFile(suffix='.txt') as text_file:
      text_file.write(textwrap.dedent("""
          0.0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
          100 2000 1 1 1 1 1 1 1 2000 1 1 1 1 1 1 1 2000 1 1 1 1 1 1 1"""[1:]))
      text_file.flush()

      with self.stdout, FakeMotor('SBO') as motor:
        self.client.onecmd('set_command_function ' + text_file.name)
        self.assertRegexpMatches(self.stdout.Read(),
                                 r'(?s).*Extreme(?s).*outside of '
                                 r'limits \[%f, %f\] detected.*'
                                 % (motor_client.TORQUE_MIN_LIMIT,
                                    motor_client.TORQUE_MAX_LIMIT))
        self.client.onecmd('arm')
        self.client.onecmd('run 1s')
        self.assert_eventually_true(
            lambda: abs(motor.torque) < _EPS32)

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_print_new_errors_asynchronously(self):
    regex = re.compile('(?s).*SBO: kMotorErrorOverSpeed'
                       ' | kMotorErrorOverVoltage.*')

    with FakeMotor('SBO') as motor:
      motor.SetError(flags.kMotorErrorOverVoltage
                     | flags.kMotorErrorOverSpeed)
      with self.stdout:
        self.client.onecmd('set_targets SBO')
        self.assert_eventually_true(lambda: regex.match(self.stdout.Read()))
        other_motors = [m for m in motor_client.MOTORS if m != 'SBO']

        # Make sure we only print the motor with an error.
        self.assertFalse(re.match('(?s).*(%s).*' % '|'.join(other_motors),
                                  self.stdout.Read()))

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_print_new_warnings_asynchronously(self):
    regex = re.compile('(?s).*SBO: kMotorWarningOverTempBoard'
                       ' | kMotorWarningOverTempStatorCore.*')

    with FakeMotor('SBO') as motor:
      motor.SetWarning(flags.kMotorWarningOverTempBoard
                       | flags.kMotorWarningOverTempStatorCore)
      with self.stdout:
        self.client.onecmd('set_targets SBO')
        self.assert_eventually_true(lambda: regex.match(self.stdout.Read()))
        other_motors = [m for m in motor_client.MOTORS if m != 'SBO']

        # Make sure we only print the motor with an error.
        self.assertFalse(re.match('(?s).*(%s).*' % '|'.join(other_motors),
                                  self.stdout.Read()))

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_get_errors(self):
    regex = re.compile('(?s).*SBO: kMotorErrorOverSpeed'
                       ' | kMotorErrorOverVoltage.*')

    with FakeMotor('SBO') as motor:
      motor.SetError(flags.kMotorErrorOverVoltage
                     | flags.kMotorErrorOverSpeed)
      with self.stdout:
        self.client.onecmd('set_targets SBO')
        self.assert_eventually_true(lambda: regex.match(self.stdout.Read()))
      with self.stdout:  # Reset stdout contents.
        self.client.onecmd('get_errors')
        self.assertRegexpMatches(self.stdout.Read(), regex)

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_get_warnings(self):
    regex = re.compile('(?s).*SBO: kMotorWarningOverTempBoard'
                       ' | kMotorWarningOverTempStatorCore.*')

    with FakeMotor('SBO') as motor:
      motor.SetWarning(flags.kMotorWarningOverTempBoard
                       | flags.kMotorWarningOverTempStatorCore)
      with self.stdout:
        self.client.onecmd('set_targets SBO')
        self.assert_eventually_true(lambda: regex.match(self.stdout.Read()))
      with self.stdout:  # Reset stdout contents.
        self.client.onecmd('get_errors')
        self.assertRegexpMatches(self.stdout.Read(), regex)

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_do_clear_errors(self):
    regex = re.compile('(?s).*SBO: kMotorErrorOverVoltage.*')

    with self.stdout, FakeMotor('SBO') as motor:
      motor.SetError(flags.kMotorErrorOverVoltage)
      self.client.onecmd('set_targets SBO')
      self.assert_eventually_true(lambda: regex.match(self.stdout.Read()))
      self.client.onecmd('clear_errors')
      self.assert_eventually_true(
          lambda: motor.GetError() == flags.kMotorErrorNone)

  def test_do_source_fail(self):
    with tempfile.NamedTemporaryFile() as source_file:
      source_file.write(textwrap.dedent("""
          set_targets SBO
          arm
          run 100 s"""[1:]))
      source_file.flush()

      with self.stdout, FakeMotor('SBO'):
        self.client.onecmd('source ' + source_file.name)
        regex = re.compile(
            '(?s).*Only "set_param"-like commands.*')
        self.assertRegexpMatches(self.stdout.Read(), regex)

  def test_do_source_succeed(self):
    with tempfile.NamedTemporaryFile() as source_file:
      source_file.write(textwrap.dedent("""
          set_param SBO i_kp 3.14
          set_param SBO cos_offset 0.2

          # This is a comment.
          set_param SBO iq_lower_limit -1e-3
          set_param SBO iq_upper_limit 245""")[1:])
      source_file.flush()

      with self.stdout, FakeMotor('SBO') as motor:
        self.client.onecmd('source ' + source_file.name)
        self.assertAlmostEqual(motor.GetParam('i_kp'), 3.14, places=6)
        self.assertAlmostEqual(motor.GetParam('cos_offset'), 0.2, places=6)
        self.assertAlmostEqual(motor.GetParam('iq_lower_limit'),
                               -1e-3, places=6)
        self.assertAlmostEqual(motor.GetParam('iq_upper_limit'),
                               245, places=6)

  def test_do_source_track_errors(self):
    with tempfile.NamedTemporaryFile() as source_file:
      source_file.write(textwrap.dedent("""
          set_param SBO i_kp 3.14
          set_param SBO foo 0.2
          set_param SBO omega_kp 0.1
          set_param SBO bar 0.5""")[1:])
      source_file.flush()

      with self.stdout, FakeMotor('SBO'):
        self.client.onecmd('source ' + source_file.name)
        self.assertRegexpMatches(
            self.stdout.Read(),
            '(?s).*Errors encountered.*Line 2.*foo.*Line 4.*bar.*')

  @unittest.skipIf(socket.gethostname().startswith('jenkins-'),
                   'This test is flaky when run on GCE.')
  def test_stop_running_on_error(self):
    regex = re.compile('(?s).*SBO: kMotorErrorOverVoltage.*')

    with FakeMotor('SBO') as motor:
      with self.stdout:
        self.client.onecmd('set_targets SBO')
        self.client.onecmd('arm')
        self.client.onecmd('run 1000 s')

        motor.SetError(flags.kMotorErrorOverVoltage)
        self.assert_eventually_true(lambda: regex.match(self.stdout.Read()))
        self.assert_eventually_true(lambda: not motor.running)

if __name__ == '__main__':
  unittest.main()


text:
import 'async-listener';

import {noop} from 'lodash';

const listener = process.addAsyncListener({
  create: noop,
  error: noop
});

function enable (opts = {}) {
  listener.error = opts.onError || noop;
}

function run (func, context, ...args) {
  return func.apply(context, args);
}

function disable () {
  listener.error = listener.create = noop;
}

export {enable, run, disable};


text:
"""Utilities for generating OpenAPI Specification (fka Swagger) entities from
:class:`Fields <marshmallow.fields.Field>`.

.. warning::

    This module is treated as private API.
    Users should not need to use this module directly.
"""
import re
import functools
import operator
import typing
import warnings

import marshmallow
from marshmallow.orderedset import OrderedSet

from apispec.utils import OpenAPIVersion

RegexType = type(re.compile(""))

# marshmallow field => (JSON Schema type, format)
DEFAULT_FIELD_MAPPING = {
    marshmallow.fields.Integer: ("integer", None),
    marshmallow.fields.Number: ("number", None),
    marshmallow.fields.Float: ("number", None),
    marshmallow.fields.Decimal: ("number", None),
    marshmallow.fields.String: ("string", None),
    marshmallow.fields.Boolean: ("boolean", None),
    marshmallow.fields.UUID: ("string", "uuid"),
    marshmallow.fields.DateTime: ("string", "date-time"),
    marshmallow.fields.Date: ("string", "date"),
    marshmallow.fields.Time: ("string", None),
    marshmallow.fields.TimeDelta: ("integer", None),
    marshmallow.fields.Email: ("string", "email"),
    marshmallow.fields.URL: ("string", "url"),
    marshmallow.fields.Dict: ("object", None),
    marshmallow.fields.Field: (None, None),
    marshmallow.fields.Raw: (None, None),
    marshmallow.fields.List: ("array", None),
}

# Properties that may be defined in a field's metadata that will be added to the output
# of field2property
# https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject
_VALID_PROPERTIES = {
    "format",
    "title",
    "description",
    "default",
    "multipleOf",
    "maximum",
    "exclusiveMaximum",
    "minimum",
    "exclusiveMinimum",
    "maxLength",
    "minLength",
    "pattern",
    "maxItems",
    "minItems",
    "uniqueItems",
    "maxProperties",
    "minProperties",
    "required",
    "enum",
    "type",
    "items",
    "allOf",
    "oneOf",
    "anyOf",
    "not",
    "properties",
    "additionalProperties",
    "readOnly",
    "writeOnly",
    "xml",
    "externalDocs",
    "example",
    "nullable",
    "deprecated",
}

_VALID_PREFIX = "x-"

class FieldConverterMixin:
    """Adds methods for converting marshmallow fields to an OpenAPI properties."""

    field_mapping = DEFAULT_FIELD_MAPPING
    openapi_version: OpenAPIVersion

    def init_attribute_functions(self):
        self.attribute_functions = [
            # self.field2type_and_format should run first
            # as other functions may rely on its output
            self.field2type_and_format,
            self.field2default,
            self.field2choices,
            self.field2read_only,
            self.field2write_only,
            self.field2nullable,
            self.field2range,
            self.field2length,
            self.field2pattern,
            self.metadata2properties,
            self.nested2properties,
            self.pluck2properties,
            self.list2properties,
            self.dict2properties,
            self.timedelta2properties,
        ]

    def map_to_openapi_type(self, *args):
        """Decorator to set mapping for custom fields.

        ``*args`` can be:

        - a pair of the form ``(type, format)``
        - a core marshmallow field type (in which case we reuse that type's mapping)
        """
        if len(args) == 1 and args[0] in self.field_mapping:
            openapi_type_field = self.field_mapping[args[0]]
        elif len(args) == 2:
            openapi_type_field = args
        else:
            raise TypeError("Pass core marshmallow field type or (type, fmt) pair.")

        def inner(field_type):
            self.field_mapping[field_type] = openapi_type_field
            return field_type

        return inner

    def add_attribute_function(self, func):
        """Method to add an attribute function to the list of attribute functions
        that will be called on a field to convert it from a field to an OpenAPI
        property.

        :param func func: the attribute function to add
            The attribute function will be bound to the
            `OpenAPIConverter <apispec.ext.marshmallow.openapi.OpenAPIConverter>`
            instance.
            It will be called for each field in a schema with
            `self <apispec.ext.marshmallow.openapi.OpenAPIConverter>` and a
            `field <marshmallow.fields.Field>` instance
            positional arguments and `ret <dict>` keyword argument.
            Must return a dictionary of OpenAPI properties that will be shallow
            merged with the return values of all other attribute functions called on the field.
            User added attribute functions will be called after all built-in attribute
            functions in the order they were added. The merged results of all
            previously called attribute functions are accessable via the `ret`
            argument.
        """
        bound_func = func.__get__(self)
        setattr(self, func.__name__, bound_func)
        self.attribute_functions.append(bound_func)

    def field2property(self, field: marshmallow.fields.Field) -> dict:
        """Return the JSON Schema property definition given a marshmallow
        :class:`Field <marshmallow.fields.Field>`.

        Will include field metadata that are valid properties of OpenAPI schema objects
        (e.g. "description", "enum", "example").

        https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject

        :param Field field: A marshmallow field.
        :rtype: dict, a Property Object
        """
        ret: dict = {}

        for attr_func in self.attribute_functions:
            ret.update(attr_func(field, ret=ret))

        return ret

    def field2type_and_format(
        self, field: marshmallow.fields.Field, **kwargs: typing.Any
    ) -> dict:
        """Return the dictionary of OpenAPI type and format based on the field type.

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        # If this type isn't directly in the field mapping then check the
        # hierarchy until we find something that does.
        for field_class in type(field).__mro__:
            if field_class in self.field_mapping:
                type_, fmt = self.field_mapping[field_class]
                break
        else:
            warnings.warn(
                "Field of type {} does not inherit from marshmallow.Field.".format(
                    type(field)
                ),
                UserWarning,
            )
            type_, fmt = "string", None

        ret = {}
        if type_:
            ret["type"] = type_
        if fmt:
            ret["format"] = fmt

        return ret

    def field2default(
        self, field: marshmallow.fields.Field, **kwargs: typing.Any
    ) -> dict:
        """Return the dictionary containing the field's default value.

        Will first look for a `default` key in the field's metadata and then
        fall back on the field's `missing` parameter. A callable passed to the
        field's missing parameter will be ignored.

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        ret = {}
        if "default" in field.metadata:
            ret["default"] = field.metadata["default"]
        else:
            default = field.load_default
            if default is not marshmallow.missing and not callable(default):
                default = field._serialize(default, None, None)  # type:ignore
                ret["default"] = default
        return ret

    def field2choices(
        self, field: marshmallow.fields.Field, **kwargs: typing.Any
    ) -> dict:
        """Return the dictionary of OpenAPI field attributes for valid choices definition.

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        attributes = {}

        comparable = [
            validator.comparable  # type:ignore
            for validator in field.validators
            if hasattr(validator, "comparable")
        ]
        if comparable:
            attributes["enum"] = comparable
        else:
            choices = [
                OrderedSet(validator.choices)  # type:ignore
                for validator in field.validators
                if hasattr(validator, "choices")
            ]
            if choices:
                attributes["enum"] = list(functools.reduce(operator.and_, choices))

        return attributes

    def field2read_only(
        self, field: marshmallow.fields.Field, **kwargs: typing.Any
    ) -> dict:
        """Return the dictionary of OpenAPI field attributes for a dump_only field.

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        attributes = {}
        if field.dump_only:
            attributes["readOnly"] = True
        return attributes

    def field2write_only(
        self, field: marshmallow.fields.Field, **kwargs: typing.Any
    ) -> dict:
        """Return the dictionary of OpenAPI field attributes for a load_only field.

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        attributes = {}
        if field.load_only and self.openapi_version.major >= 3:
            attributes["writeOnly"] = True
        return attributes

    def field2nullable(self, field: marshmallow.fields.Field, ret) -> dict:
        """Return the dictionary of OpenAPI field attributes for a nullable field.

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        attributes: dict = {}
        if field.allow_none:
            if self.openapi_version.major < 3:
                attributes["x-nullable"] = True
            elif self.openapi_version.minor < 1:
                attributes["nullable"] = True
            else:
                attributes["type"] = [*make_type_list(ret.get("type")), "null"]
        return attributes

    def field2range(self, field: marshmallow.fields.Field, ret) -> dict:
        """Return the dictionary of OpenAPI field attributes for a set of
        :class:`Range <marshmallow.validators.Range>` validators.

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        validators = [
            validator
            for validator in field.validators
            if (
                hasattr(validator, "min")
                and hasattr(validator, "max")
                and not hasattr(validator, "equal")
            )
        ]

        min_attr, max_attr = (
            ("minimum", "maximum")
            if set(make_type_list(ret.get("type"))) & {"number", "integer"}
            else ("x-minimum", "x-maximum")
        )
        return make_min_max_attributes(validators, min_attr, max_attr)

    def field2length(
        self, field: marshmallow.fields.Field, **kwargs: typing.Any
    ) -> dict:
        """Return the dictionary of OpenAPI field attributes for a set of
        :class:`Length <marshmallow.validators.Length>` validators.

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        validators = [
            validator
            for validator in field.validators
            if (
                hasattr(validator, "min")
                and hasattr(validator, "max")
                and hasattr(validator, "equal")
            )
        ]

        is_array = isinstance(
            field, (marshmallow.fields.Nested, marshmallow.fields.List)
        )
        min_attr = "minItems" if is_array else "minLength"
        max_attr = "maxItems" if is_array else "maxLength"

        equal_list = [
            validator.equal  # type:ignore
            for validator in validators
            if validator.equal is not None  # type:ignore
        ]
        if equal_list:
            return {min_attr: equal_list[0], max_attr: equal_list[0]}

        return make_min_max_attributes(validators, min_attr, max_attr)

    def field2pattern(
        self, field: marshmallow.fields.Field, **kwargs: typing.Any
    ) -> dict:
        """Return the dictionary of OpenAPI field attributes for a
        :class:`Regexp <marshmallow.validators.Regexp>` validator.

        If there is more than one such validator, only the first
        is used in the output spec.

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        regex_validators = (
            v
            for v in field.validators
            if isinstance(getattr(v, "regex", None), RegexType)
        )
        v = next(regex_validators, None)
        attributes = {} if v is None else {"pattern": v.regex.pattern}  # type:ignore

        if next(regex_validators, None) is not None:
            warnings.warn(
                "More than one regex validator defined on {} field. Only the "
                "first one will be used in the output spec.".format(type(field)),
                UserWarning,
            )

        return attributes

    def metadata2properties(
        self, field: marshmallow.fields.Field, **kwargs: typing.Any
    ) -> dict:
        """Return a dictionary of properties extracted from field metadata.

        Will include field metadata that are valid properties of `OpenAPI schema
        objects
        <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject>`_
        (e.g. "description", "enum", "example").

        In addition, `specification extensions
        <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions>`_
        are supported.  Prefix `x_` to the desired extension when passing the
        keyword argument to the field constructor. apispec will convert `x_` to
        `x-` to comply with OpenAPI.

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        # Dasherize metadata that starts with x_
        metadata = {
            key.replace("_", "-") if key.startswith("x_") else key: value
            for key, value in field.metadata.items()
            if isinstance(key, str)
        }

        # Avoid validation error with "Additional properties not allowed"
        ret = {
            key: value
            for key, value in metadata.items()
            if key in _VALID_PROPERTIES or key.startswith(_VALID_PREFIX)
        }
        return ret

    def nested2properties(self, field: marshmallow.fields.Field, ret) -> dict:
        """Return a dictionary of properties from :class:`Nested <marshmallow.fields.Nested` fields.

        Typically provides a reference object and will add the schema to the spec
        if it is not already present
        If a custom `schema_name_resolver` function returns `None` for the nested
        schema a JSON schema object will be returned

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        # Pluck is a subclass of Nested but is in essence a single field; it
        # is treated separately by pluck2properties.
        if isinstance(field, marshmallow.fields.Nested) and not isinstance(
            field, marshmallow.fields.Pluck
        ):
            schema_dict = self.resolve_nested_schema(field.schema)  # type:ignore
            if ret and "$ref" in schema_dict:
                ret.update({"allOf": [schema_dict]})
            else:
                ret.update(schema_dict)
        return ret

    def pluck2properties(self, field, **kwargs: typing.Any) -> dict:
        """Return a dictionary of properties from :class:`Pluck <marshmallow.fields.Pluck` fields.

        Pluck effectively trans-includes a field from another schema into this,
        possibly wrapped in an array (`many=True`).

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        if isinstance(field, marshmallow.fields.Pluck):
            plucked_field = field.schema.fields[field.field_name]
            ret = self.field2property(plucked_field)
            return {"type": "array", "items": ret} if field.many else ret
        return {}

    def list2properties(self, field, **kwargs: typing.Any) -> dict:
        """Return a dictionary of properties from :class:`List <marshmallow.fields.List>` fields.

        Will provide an `items` property based on the field's `inner` attribute

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        ret = {}
        if isinstance(field, marshmallow.fields.List):
            ret["items"] = self.field2property(field.inner)
        return ret

    def dict2properties(self, field, **kwargs: typing.Any) -> dict:
        """Return a dictionary of properties from :class:`Dict <marshmallow.fields.Dict>` fields.

        Only applicable for Marshmallow versions greater than 3. Will provide an
        `additionalProperties` property based on the field's `value_field` attribute

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        ret = {}
        if isinstance(field, marshmallow.fields.Dict):
            value_field = field.value_field
            if value_field:
                ret["additionalProperties"] = self.field2property(value_field)
        return ret

    def timedelta2properties(self, field, **kwargs: typing.Any) -> dict:
        """Return a dictionary of properties from :class:`TimeDelta <marshmallow.fields.TimeDelta>` fields.

        Adds a `x-unit` vendor property based on the field's `precision` attribute

        :param Field field: A marshmallow field.
        :rtype: dict
        """
        ret = {}
        if isinstance(field, marshmallow.fields.TimeDelta):
            ret["x-unit"] = field.precision
        return ret

def make_type_list(types):
    """Return a list of types from a type attribute

    Since OpenAPI 3.1.0, "type" can be a single type as string or a list of
    types, including 'null'. This function takes a "type" attribute as input
    and returns it as a list, be it an empty or single-element list.
    This is useful to factorize type-conditional code or code adding a type.
    """
    if types is None:
        return []
    if isinstance(types, str):
        return [types]
    return types

def make_min_max_attributes(validators, min_attr, max_attr) -> dict:
    """Return a dictionary of minimum and maximum attributes based on a list
    of validators. If either minimum or maximum values are not present in any
    of the validator objects that attribute will be omitted.

    :param validators list: A list of `Marshmallow` validator objects. Each
        objct is inspected for a minimum and maximum values
    :param min_attr string: The OpenAPI attribute for the minimum value
    :param max_attr string: The OpenAPI attribute for the maximum value
    """
    attributes = {}
    min_list = [validator.min for validator in validators if validator.min is not None]
    max_list = [validator.max for validator in validators if validator.max is not None]
    if min_list:
        attributes[min_attr] = max(min_list)
    if max_list:
        attributes[max_attr] = min(max_list)
    return attributes


text:
namespace GraphLib
{
    partial class PlotterGraphSelectCurvesForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.splitContainer1 = new System.Windows.Forms.SplitContainer();
            this.lb_Graphs = new System.Windows.Forms.CheckedListBox();
            this.gB_SelectedGraph = new System.Windows.Forms.GroupBox();
            this.cb_X_AutoScale = new System.Windows.Forms.CheckBox();
            this.tb_GraphName = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.cbDownSampling = new System.Windows.Forms.ComboBox();
            this.label2 = new System.Windows.Forms.Label();
            this.btn_GraphColor = new System.Windows.Forms.Button();
            this.cb_Y_AutoScale = new System.Windows.Forms.CheckBox();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.label7 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.bt_MinorGridColor = new System.Windows.Forms.Button();
            this.bt_bg_col_bot = new System.Windows.Forms.Button();
            this.label6 = new System.Windows.Forms.Label();
            this.bt_MajorGridColor = new System.Windows.Forms.Button();
            this.label4 = new System.Windows.Forms.Label();
            this.bt_bg_col_top = new System.Windows.Forms.Button();
            this.btn_AutoScaleAll = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.cb_Layout = new System.Windows.Forms.ComboBox();
            this.button1 = new System.Windows.Forms.Button();
            this.splitContainer1.Panel1.SuspendLayout();
            this.splitContainer1.Panel2.SuspendLayout();
            this.splitContainer1.SuspendLayout();
            this.gB_SelectedGraph.SuspendLayout();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            //
            // splitContainer1
            //
            this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
            this.splitContainer1.Location = new System.Drawing.Point(0, 0);
            this.splitContainer1.Name = "splitContainer1";
            //
            // splitContainer1.Panel1
            //
            this.splitContainer1.Panel1.Controls.Add(this.lb_Graphs);
            //
            // splitContainer1.Panel2
            //
            this.splitContainer1.Panel2.Controls.Add(this.gB_SelectedGraph);
            this.splitContainer1.Panel2.Controls.Add(this.groupBox1);
            this.splitContainer1.Panel2.Controls.Add(this.button1);
            this.splitContainer1.Size = new System.Drawing.Size(395, 431);
            this.splitContainer1.SplitterDistance = 171;
            this.splitContainer1.TabIndex = 0;
            //
            // lb_Graphs
            //
            this.lb_Graphs.Dock = System.Windows.Forms.DockStyle.Fill;
            this.lb_Graphs.FormattingEnabled = true;
            this.lb_Graphs.Location = new System.Drawing.Point(0, 0);
            this.lb_Graphs.Name = "lb_Graphs";
            this.lb_Graphs.Size = new System.Drawing.Size(171, 424);
            this.lb_Graphs.TabIndex = 0;
            this.lb_Graphs.SelectedIndexChanged += new System.EventHandler(this.checkedListBox1_SelectedIndexChanged_1);
            //
            // gB_SelectedGraph
            //
            this.gB_SelectedGraph.Controls.Add(this.cb_X_AutoScale);
            this.gB_SelectedGraph.Controls.Add(this.tb_GraphName);
            this.gB_SelectedGraph.Controls.Add(this.label3);
            this.gB_SelectedGraph.Controls.Add(this.cbDownSampling);
            this.gB_SelectedGraph.Controls.Add(this.label2);
            this.gB_SelectedGraph.Controls.Add(this.btn_GraphColor);
            this.gB_SelectedGraph.Controls.Add(this.cb_Y_AutoScale);
            this.gB_SelectedGraph.Location = new System.Drawing.Point(6, 232);
            this.gB_SelectedGraph.Name = "gB_SelectedGraph";
            this.gB_SelectedGraph.Size = new System.Drawing.Size(206, 158);
            this.gB_SelectedGraph.TabIndex = 6;
            this.gB_SelectedGraph.TabStop = false;
            this.gB_SelectedGraph.Text = "Selected Graph Options";
            this.gB_SelectedGraph.Visible = false;
            //
            // cb_X_AutoScale
            //
            this.cb_X_AutoScale.AutoSize = true;
            this.cb_X_AutoScale.Location = new System.Drawing.Point(12, 102);
            this.cb_X_AutoScale.Name = "cb_X_AutoScale";
            this.cb_X_AutoScale.Size = new System.Drawing.Size(93, 17);
            this.cb_X_AutoScale.TabIndex = 8;
            this.cb_X_AutoScale.Text = "X AutoScaling";
            this.cb_X_AutoScale.UseVisualStyleBackColor = true;
            this.cb_X_AutoScale.CheckedChanged += new System.EventHandler(this.cb_X_AutoScale_CheckedChanged);
            //
            // tb_GraphName
            //
            this.tb_GraphName.Location = new System.Drawing.Point(12, 24);
            this.tb_GraphName.Name = "tb_GraphName";
            this.tb_GraphName.Size = new System.Drawing.Size(167, 20);
            this.tb_GraphName.TabIndex = 7;
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(52, 133);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(76, 13);
            this.label3.TabIndex = 6;
            this.label3.Text = "Downsampling";
            //
            // cbDownSampling
            //
            this.cbDownSampling.FormattingEnabled = true;
            this.cbDownSampling.Items.AddRange(new object[] {
            "1",
            "2",
            "3",
            "4",
            "5",
            "6"});
            this.cbDownSampling.Location = new System.Drawing.Point(7, 130);
            this.cbDownSampling.Name = "cbDownSampling";
            this.cbDownSampling.Size = new System.Drawing.Size(39, 21);
            this.cbDownSampling.TabIndex = 5;
            this.cbDownSampling.Text = "1";
            this.cbDownSampling.SelectedIndexChanged += new System.EventHandler(this.OnDownsamplingChanged);
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(57, 55);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(63, 13);
            this.label2.TabIndex = 4;
            this.label2.Text = "Graph Color";
            //
            // btn_GraphColor
            //
            this.btn_GraphColor.Location = new System.Drawing.Point(11, 50);
            this.btn_GraphColor.Name = "btn_GraphColor";
            this.btn_GraphColor.Size = new System.Drawing.Size(26, 23);
            this.btn_GraphColor.TabIndex = 3;
            this.btn_GraphColor.UseVisualStyleBackColor = true;
            this.btn_GraphColor.Click += new System.EventHandler(this.btn_GraphColor_Click);
            //
            // cb_Y_AutoScale
            //
            this.cb_Y_AutoScale.AutoSize = true;
            this.cb_Y_AutoScale.Location = new System.Drawing.Point(12, 79);
            this.cb_Y_AutoScale.Name = "cb_Y_AutoScale";
            this.cb_Y_AutoScale.Size = new System.Drawing.Size(93, 17);
            this.cb_Y_AutoScale.TabIndex = 2;
            this.cb_Y_AutoScale.Text = "Y AutoScaling";
            this.cb_Y_AutoScale.UseVisualStyleBackColor = true;
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.label7);
            this.groupBox1.Controls.Add(this.label5);
            this.groupBox1.Controls.Add(this.bt_MinorGridColor);
            this.groupBox1.Controls.Add(this.bt_bg_col_bot);
            this.groupBox1.Controls.Add(this.label6);
            this.groupBox1.Controls.Add(this.bt_MajorGridColor);
            this.groupBox1.Controls.Add(this.label4);
            this.groupBox1.Controls.Add(this.bt_bg_col_top);
            this.groupBox1.Controls.Add(this.btn_AutoScaleAll);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.Controls.Add(this.cb_Layout);
            this.groupBox1.Location = new System.Drawing.Point(6, 5);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(206, 221);
            this.groupBox1.TabIndex = 4;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "General Options";
            //
            // label7
            //
            this.label7.AutoSize = true;
            this.label7.Location = new System.Drawing.Point(57, 194);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(82, 13);
            this.label7.TabIndex = 10;
            this.label7.Text = "Minor Grid Color";
            //
            // label5
            //
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(57, 136);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(128, 13);
            this.label5.TabIndex = 8;
            this.label5.Text = "Background Color Bottom";
            //
            // bt_MinorGridColor
            //
            this.bt_MinorGridColor.Location = new System.Drawing.Point(11, 189);
            this.bt_MinorGridColor.Name = "bt_MinorGridColor";
            this.bt_MinorGridColor.Size = new System.Drawing.Size(26, 23);
            this.bt_MinorGridColor.TabIndex = 9;
            this.bt_MinorGridColor.UseVisualStyleBackColor = true;
            this.bt_MinorGridColor.Click += new System.EventHandler(this.bt_MinorGridColor_Click);
            //
            // bt_bg_col_bot
            //
            this.bt_bg_col_bot.Location = new System.Drawing.Point(11, 131);
            this.bt_bg_col_bot.Name = "bt_bg_col_bot";
            this.bt_bg_col_bot.Size = new System.Drawing.Size(26, 23);
            this.bt_bg_col_bot.TabIndex = 7;
            this.bt_bg_col_bot.UseVisualStyleBackColor = true;
            this.bt_bg_col_bot.Click += new System.EventHandler(this.bt_bg_col_bot_Click);
            //
            // label6
            //
            this.label6.AutoSize = true;
            this.label6.Location = new System.Drawing.Point(57, 165);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(82, 13);
            this.label6.TabIndex = 8;
            this.label6.Text = "Major Grid Color";
            //
            // bt_MajorGridColor
            //
            this.bt_MajorGridColor.Location = new System.Drawing.Point(11, 160);
            this.bt_MajorGridColor.Name = "bt_MajorGridColor";
            this.bt_MajorGridColor.Size = new System.Drawing.Size(26, 23);
            this.bt_MajorGridColor.TabIndex = 7;
            this.bt_MajorGridColor.UseVisualStyleBackColor = true;
            this.bt_MajorGridColor.Click += new System.EventHandler(this.bt_MajorGridColor_Click);
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(57, 107);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(114, 13);
            this.label4.TabIndex = 6;
            this.label4.Text = "Background Color Top";
            //
            // bt_bg_col_top
            //
            this.bt_bg_col_top.Location = new System.Drawing.Point(11, 102);
            this.bt_bg_col_top.Name = "bt_bg_col_top";
            this.bt_bg_col_top.Size = new System.Drawing.Size(26, 23);
            this.bt_bg_col_top.TabIndex = 5;
            this.bt_bg_col_top.UseVisualStyleBackColor = true;
            this.bt_bg_col_top.Click += new System.EventHandler(this.bt_bg_col_top_Click);
            //
            // btn_AutoScaleAll
            //
            this.btn_AutoScaleAll.Location = new System.Drawing.Point(11, 69);
            this.btn_AutoScaleAll.Name = "btn_AutoScaleAll";
            this.btn_AutoScaleAll.Size = new System.Drawing.Size(167, 25);
            this.btn_AutoScaleAll.TabIndex = 4;
            this.btn_AutoScaleAll.Text = "Auto Scale All";
            this.btn_AutoScaleAll.UseVisualStyleBackColor = true;
            this.btn_AutoScaleAll.Click += new System.EventHandler(this.OnButtonAutoScallOnClicked);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(9, 26);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(39, 13);
            this.label1.TabIndex = 3;
            this.label1.Text = "Layout";
            //
            // cb_Layout
            //
            this.cb_Layout.FormattingEnabled = true;
            this.cb_Layout.Items.AddRange(new object[] {
            "Normal",
            "Stacked",
            "Tiles - Fill Vertical",
            "Tiles - Fill Horizontal",
            "Vertically"});
            this.cb_Layout.Location = new System.Drawing.Point(11, 42);
            this.cb_Layout.Name = "cb_Layout";
            this.cb_Layout.Size = new System.Drawing.Size(168, 21);
            this.cb_Layout.TabIndex = 2;
            this.cb_Layout.Text = "Select";
            this.cb_Layout.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(66, 396);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(68, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "Exit";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // PlotterGraphSelectCurvesForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(395, 431);
            this.Controls.Add(this.splitContainer1);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.MinimumSize = new System.Drawing.Size(16, 246);
            this.Name = "PlotterGraphSelectCurvesForm";
            this.Text = "Graph Properties";
            this.splitContainer1.Panel1.ResumeLayout(false);
            this.splitContainer1.Panel2.ResumeLayout(false);
            this.splitContainer1.ResumeLayout(false);
            this.gB_SelectedGraph.ResumeLayout(false);
            this.gB_SelectedGraph.PerformLayout();
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.SplitContainer splitContainer1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.CheckedListBox lb_Graphs;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.ComboBox cb_Layout;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button btn_GraphColor;
        private System.Windows.Forms.CheckBox cb_Y_AutoScale;
        private System.Windows.Forms.Button btn_AutoScaleAll;
        private System.Windows.Forms.GroupBox gB_SelectedGraph;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.ComboBox cbDownSampling;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Button bt_bg_col_top;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Button bt_bg_col_bot;
        private System.Windows.Forms.Label label7;
        private System.Windows.Forms.Button bt_MinorGridColor;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Button bt_MajorGridColor;
        private System.Windows.Forms.TextBox tb_GraphName;
        private System.Windows.Forms.CheckBox cb_X_AutoScale;
    }
}


text:
![](https://badge.fury.io/js/%40keyframes%2Fcore.svg)

Keyframes allows dynamic generation of CSS keyframes with callback events and other niceness.

## Overview

CSS3 introduced fancy features like transformations, translations, rotations and scaling.
Keyframes allows you to manage and execute animations using Javascript.

## Installation

Install from npm:
```
npm install @keyframes/core --save
```

Import into your project using the following line:
```javascript
import Keyframes from '@keyframes/core';
```

Be sure to define and play animations after the page has loaded by including your script tag at the bottom of the document or using `window.onload`.

## Usage

**Detecting CSS animation support**

```javascript
var supportedFlag = Keyframes.isSupported();
```

## Defining

Defining keyframes happens before any any animation logic takes place. The CSS is stored and indexed in a single style tag in the header with the id `keyframesjs-stylesheet`.

**Adding a new animation sequence (keyframe)**

```javascript
Keyframes.define([{
    name: 'trapdoor-sequence',
    '0%': {height: 70},
    '30%': {height: 10},
    '60%': {height: 30},
    '100%': {height: 10}
}]);
```

**Adding a single frame style**

```javascript
Keyframes.define({
    name: 'ball-roll',
    from: {
        transform: 'rotate(0deg)'
    },
    to: {
        transform: 'rotate(360deg)'
    }
});
```

**Adding multiple frame styles**

```javascript
Keyframes.define([{
	name: 'roll-clockwise',
	'0%': {
	    marginLeft: 0,
	    backgroundColor: 'red',
	    transform: 'rotate(0deg)'
	},
	'100%': {
	    marginLeft: 600,
	    transform: 'rotate(360deg)'
	}
    },{
	name: 'roll-anti-clockwise',
	'0%': {
	    marginLeft: 0,
	    backgroundColor: 'red',
	    transform: 'rotate(0deg)'
	},
	'100%': {
	    marginLeft: 600,
	    transform: 'rotate(-360deg)'
	}
    }
]);
```

**Adding styles and properties in array fashion**

*Gives resemblance to CSS styling definitions*

```javascript
var shake_start = {transform: 'translate(0px)'};
var shake_odd1 = {transform: 'translate(-10px, -10px)'};
var shake_even1 = {transform: 'translate(10px, 10px)'};
var shake_odd2 = {transform: 'translate(10px, -10px)'};
var shake_even2 = {transform: 'translate(-10px, 10px)'};

Keyframes.define([{
	name: 'crazy',
	'0%': shake_start,
	'10%': shake_odd2,
	'20%': shake_even1,
	'30%': shake_odd2,
	'40%': shake_even2,
	'50%': shake_odd2,
	'60%': shake_even1,
	'70%': shake_odd1,
	'80%': shake_even2,
	'90%': shake_odd1
    }
]);
```

*Please note, you can add as many properties to the array as you want to*

**Responsive animations**

```javascript
Keyframes.define([{
    name: 'roll-clockwise',
    media: 'screen and (max-width: 700px)',
    from: {
        marginLeft: 0
    },
    to: {
        marginLeft: 600
    }
    }
]);
```

## Playing

After the keyframes have been defined (see above), they can now be used on any element in the dom.
First we must create an instance of Keyframejs using our chosen element.

```javascript
const ball = new Keyframes(document.getElementById('ball'));
```

The css3 animation methods available are better documented here: http://www.w3schools.com/css/css3_animations.asp

```javascript
ball.play({
    name: 'trapdoor-sequence', // [required] name of the keyframe you want to bind to the selected element
    duration: '1s', // [optional, default: '0s'] how long you want it to last in milliseconds
    timingFunction: 'linear', // [optional, default: 'ease'] specifies the speed curve of the animation
    delay: '0s', //[optional, default: '0s']  how long you want to wait before the animation starts
    iterationCount: 'infinite', //[optional, default: 1]  how many times you want the animation to repeat
    direction: 'normal', //[optional, default: 'normal']  which direction you want the frames to flow
    fillMode: 'forwards', //[optional, default: 'forward']  how to apply the styles outside the animation time, default value is forwards
},
{ // Callbacks
    onBeforeStart, // Optional: Fired before the animation starts.
    onStart, // Optional: Fired after the animation started.
    onIteration, // Optional: If your animation has multiple iterations, this function will fire after each one.
    onEnd, // Optional: Fired at the end of the animation but if using a `queue`, it will fire after the queue has completed.
});
```

**Playing an animation (shorthand)**

```javascript
ball.play(
    'trapdoor-sequence 1s linear 0s infinite normal forwards',
    callbacks
);
```

**Playing multiple animations simultaneously (at the same time)**

```javascript
ball.play([
    'trapdoor-sequence 1s linear 0s infinite',
    {
      name: 'ball-roll',
      duration: "3s",
      timingFunction: 'ease',
      iterationCount: 1
    }
], callbacks);
```

**Playing multiple animations sequentially on a loop**
```javascript
ball.loop([
    'trapdoor-sequence 1s',
    ['crazy 2s', 'crazy-alt 2s'], // These animations are played simultaneously.
], callbacks);
```

**Use a queue which can be added to whenever**
If the queue was previously empty, the queue will start executing immediately.
```javascript
ball.queue('trapdoor-sequence 1s', callbacks) // Setting callbacks overrides previous callbacks so you only need to set it on the first call.
    .queue('crazy 3s'); // Run crazy after the trapdoor-sequence is complete.
setTimeout(() => ball.queue('crazy 3s'), 1000); // Add crazy to the queue again, so it will be run twice.
```

**Reset the animation**
Resets styling, animations and removes callbacks.
```javascript
ball.reset().then(doSomething);
```

**Reset the queue**
Resets styling, animations, removes callbacks and clears the queue.
```javascript
ball.resetQueue().then(doSomething);
```

**Pause keyframe animation**

```javascript
ball.pause();
```

**Resume keyframe animation**

```javascript
ball.resume();
```

## Want more control?

Handy functions to let you handle the styling yourself...

**Generate the defined keyframes css**

```javascript
let css = Keyframes.defineCSS({
    name: 'ball-spin',
    from: {
        transform: 'rotate(90deg)',
    },
    to: {
        transform: 'rotate(450deg)',
    },
}); // "@keyframes ball-spin {from {transform:rotate(90deg);}to {transform:rotate(450deg);}"
```

**Generate the "animation" rule's value (play)**

```javascript
const css = Keyframes.playCSS({
    name: 'ball-spin',
    duration: '1s',
    iterationCount: 1
}); // "ball-spin 1s ease 0s 1 normal forwards"
```

## Plugins!

Installing a plugin is simple...
```javascript
import Pathfinder from '@keyframes/pathfinder';
Keyframes.plugin(Pathfinder); // You can also pass an array of plugins for convenience.
```

See other plugins that allow for spritesheets & more complex movement paths: https://github.com/Keyframes

Changelog
---------

**2.0.6**
* Deprecate chain
* Fixed a bug where queue would not actually queue animations

**2.0.5**
* Added `loop` method
* Bug fixes
* Added freeze and unfreeze

**2.0.0**
* https://github.com/Keyframes/Keyframes/issues/1 Queue
* https://github.com/Keyframes/Keyframes/issues/9 Js Style keys

**1.1.1**
* Reset now uses `requestAnimationFrame` instead of timeouts.
* Allow an array of plugins to be added
* Code reduction.

**1.1.0**
* Use `insertRule` to add keyframes to a single style tag in the header.

**1.0.7**
* Add playCSS and defineCSS generation functions

**1.0.3**
* Make it a module
* Add plugin function

**1.0.0**
* Vanilla project initiated


text:
/* eslint-env browser */
import { createStore, applyMiddleware, compose } from 'redux';
import reducer from './reducers';
import saveAsync from './middlewares/saveAsync';

const nextReducer = require('./reducers');

export function configureStore(initialState) {
  const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
  const store = createStore(
    reducer,
    // currentNodeIdは最初のnodeにしておく
    initialState.setIn(['runtime', 'currentNodeId'], initialState.getSurvey().getNodes().get(0).getId()),
    composeEnhancers(
      applyMiddleware(saveAsync),
    ),
  );
  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('./reducers', () => {
      store.replaceReducer(nextReducer);
    });
  }

  return store;
}


text:
NSString *const kTYMSlideAuthorKey = @"author";
NSString *const kTYMSlideNoteKey = @"note";
NSString *const kTYMSlideRevisionKey = @"revision";
NSString *const kTYMSlideNextSlideNameKey = @"next";
NSString *const kTYMSlidePreviousSlideNameKey = @"previous";

@implementation TYMSlide

#pragma mark - Accessors

@synthesize note = _note;
@synthesize author = _author;
@synthesize revision = _revision;
@synthesize nextSlideName = _nextSlideName;
@synthesize previousSlideName = _previousSlideName;

#pragma mark - TYMDescriptor

+ (NSString *)descriptorTypeName {
    return @"slide";
}

- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
    if ((self = [super initWithDictionary:dictionary])) {
        _author = [dictionary tym_objectForKey:kTYMSlideAuthorKey];
        _note = [dictionary tym_objectForKey:kTYMSlideNoteKey];
        _revision = [dictionary tym_objectForKey:kTYMSlideRevisionKey];
        _nextSlideName = [dictionary tym_objectForKey:kTYMSlideNextSlideNameKey];
        _previousSlideName = [dictionary tym_objectForKey:kTYMSlidePreviousSlideNameKey];
    }
    return self;
}

- (NSDictionary *)customDescriptorInfo {
    return @{
        kTYMSlideAuthorKey: self.author,
        kTYMSlideRevisionKey: self.revision,
        kTYMSlideNoteKey: self.note,
        kTYMSlidePreviousSlideNameKey: self.previousSlideName ? : [NSNull null],
        kTYMSlideNextSlideNameKey: self.nextSlideName ? : [NSNull null],
    };
}

- (Class)rendererClass {
    return [TYMSlideRenderer class];
}

#pragma mark - Public

- (TYMSlide *)nextSlide {
    return [TYMSlide descriptorNamed:self.nextSlideName];
}

- (TYMSlide *)previousSlide {
    return [TYMSlide descriptorNamed:self.previousSlideName];
}

@end


text:
class RBGLox::Shader < RBGLox::Resource
  include Gl

  attr_reader :filename, :vertex, :fragment, :uniforms

  # Constructor
  def initialize(filename)
    @filename = filename
    @id = glCreateProgram

		@vertex = glCreateShader GL_VERTEX_SHADER
    glAttachShader id, vertex

    @fragment = glCreateShader GL_FRAGMENT_SHADER
    glAttachShader id, fragment

    @uniforms = []

    reload
  end

  # Set internal GLSL uniforms
  def []=(name, value)
    loc = glGetUniformLocation id, name
    if value.is_a? Float
      glUniform1f loc, value
    elsif value.is_a? Integer
      glUniform1i loc, value
    elsif value.is_a? Array
      l = value.size
    	if l == 2
				glUniform2fv loc, value
			elsif l == 3
				glUniform3fv loc, value
			elsif l == 4
				glUniform4fv loc, value
      end
    else
      raise TypeError.new('Uniform type not supported')
    end
  end

  # Bind the Shader
  def bind
    glUseProgram id

    uniforms.each do |k, v|
      self[k] = v
    end
  end

  # Release the Shader
  def release
    glUseProgram 0
  end

  # Reload the Shader
  def reload
    content = File.read filename
    vert, frag, unis = parse content

    glShaderSource vertex, vert
    glCompileShader vertex
    log = glGetShaderInfoLog vertex
    puts log

    return if log =~ /error/i

    glShaderSource fragment, frag
    glCompileShader fragment
    log = glGetShaderInfoLog fragment
    puts log

    return if log =~ /error/i

		glLinkProgram id
    log = glGetProgramInfoLog id
    puts log

    return if log =~ /error/i

    @uniforms = unis
  end

  # Free the Shader
  def free
    glDetachShader id, vertex
    glDeleteShader vertex

    glDetachShader id, fragment
    glDeleteShader fragment

    glDeleteProgram id
  end

  protected

  # Parse the Shader file and extract the Vertex and Fragment shaders
  def parse(content)
    source = []

    matches = content.scan(/\[(vertex|fragment|uniforms)\]\s?(.*?\s?)\s?\[end\]/m)
    matches.each do |m|
      if ["vertex", "fragment"].include?(m[0])
        source.push(m[1])
      elsif m[0] == "uniforms"
        source.push(YAML.load(m[1]))
      end
    end

    source
  end

end


text:
package com.tle.core.freetext.filters;

import com.dytech.edge.queries.FreeTextQuery;
import com.tle.beans.Institution;
import com.tle.common.institution.CurrentInstitution;
import java.io.IOException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermDocs;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.OpenBitSet;

public class InstitutionFilter extends Filter {
  private static final long serialVersionUID = 1L;

  @Override
  public DocIdSet getDocIdSet(IndexReader reader) throws IOException {
    int max = reader.maxDoc();
    OpenBitSet good = new OpenBitSet(max);
    Institution institution = CurrentInstitution.get();
    Term term = new Term(FreeTextQuery.FIELD_INSTITUTION, Long.toString(institution.getUniqueId()));
    TermDocs docs = reader.termDocs(term);
    while (docs.next()) {
      good.set(docs.doc());
    }
    docs.close();
    return good;
  }
}


text:
#pragma once
#ifndef EL_LQ_SOLVEAFTER_HPP
#define EL_LQ_SOLVEAFTER_HPP

// TODO: Extend for BusingerGolub support

namespace El {
namespace lq {

template<typename F>
void SolveAfter
( Orientation orientation,
  const Matrix<F>& A, const Matrix<F>& t,
  const Matrix<Base<F>>& d, const Matrix<F>& B,
        Matrix<F>& X )
{
    DEBUG_ONLY(CallStackEntry cse("lq::SolveAfter"))
    const Int m = A.Height();
    const Int n = A.Width();
    if( m > n )
        LogicError("Must have full row rank");

    // TODO: Add scaling
    auto AL = A( IR(0,m), IR(0,m) );
    if( orientation == NORMAL )
    {
        if( m != B.Height() )
            LogicError("A and B do not conform");

        // Copy B into X
        X.Resize( n, B.Width() );
        Matrix<F> XT, XB;
        PartitionDown( X, XT, XB, m );
        XT = B;
        Zero( XB );

        // Solve against L (checking for singularities)
        Trsm( LEFT, LOWER, NORMAL, NON_UNIT, F(1), AL, XT, true );

        // Apply Q' to X
        lq::ApplyQ( LEFT, ADJOINT, A, t, d, X );
    }
    else // orientation in {TRANSPOSE,ADJOINT}
    {
        if( n != B.Height() )
            LogicError("A and B do not conform");

        // Copy B into X
        X = B;

        if( orientation == TRANSPOSE )
            Conjugate( X );

        // Apply Q to X
        lq::ApplyQ( LEFT, NORMAL, A, t, d, X );

        // Shrink X to its new height
        X.Resize( m, X.Width() );

        // Solve against L' (check for singularities)
        Trsm( LEFT, LOWER, ADJOINT, NON_UNIT, F(1), AL, X, true );

        if( orientation == TRANSPOSE )
            Conjugate( X );
    }
}

template<typename F>
void SolveAfter
( Orientation orientation,
  const AbstractDistMatrix<F      >& APre, const AbstractDistMatrix<F>& t,
  const AbstractDistMatrix<Base<F>>& d,    const AbstractDistMatrix<F>& B,
        AbstractDistMatrix<F      >& XPre )
{
    DEBUG_ONLY(CallStackEntry cse("lq::SolveAfter"))
    const Int m = APre.Height();
    const Int n = APre.Width();
    const Grid& g = APre.Grid();
    if( m > n )
        LogicError("Must have full row rank");

    auto APtr = ReadProxy<F,MC,MR>( &APre );  auto& A = *APtr;
    auto XPtr = WriteProxy<F,MC,MR>( &XPre ); auto& X = *XPtr;

    X.Resize( n, B.Width() );
    // TODO: Add scaling

    auto AL = A( IR(0,m), IR(0,m) );
    if( orientation == NORMAL )
    {
        if( m != B.Height() )
            LogicError("A and B do not conform");

        // Copy B into X
        DistMatrix<F> XT(g), XB(g);
        PartitionDown( X, XT, XB, m );
        XT = B;
        Zero( XB );

        if( orientation == TRANSPOSE )
            Conjugate( XT );

        // Solve against L (checking for singularities)
        Trsm( LEFT, LOWER, NORMAL, NON_UNIT, F(1), AL, XT, true );

        // Apply Q' to X
        lq::ApplyQ( LEFT, ADJOINT, A, t, d, X );

        if( orientation == TRANSPOSE )
            Conjugate( X );
    }
    else
    {
        // Copy B into X
        X = B;

        if( orientation == TRANSPOSE )
            Conjugate( X );

        // Apply Q to X
        lq::ApplyQ( LEFT, NORMAL, A, t, d, X );

        // Shrink X to its new height
        X.Resize( m, X.Width() );

        // Solve against L' (check for singularities)
        Trsm( LEFT, LOWER, ADJOINT, NON_UNIT, F(1), AL, X, true );

        if( orientation == TRANSPOSE )
            Conjugate( X );
    }
}

} // namespace lq
} // namespace El

#endif // ifndef EL_LQ_SOLVEAFTER_HPP