text:
package org.apache.spark.sql.execution.datasources

import java.lang.{Double => JDouble, Long => JLong}
import java.math.{BigDecimal => JBigDecimal}

import scala.collection.mutable.ArrayBuffer
import scala.util.Try

import org.apache.hadoop.fs.Path
import org.apache.hadoop.util.Shell

import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.{Cast, Literal}
import org.apache.spark.sql.types._

private[sql] case class Partition(values: InternalRow, path: String)

private[sql] case class PartitionSpec(partitionColumns: StructType, partitions: Seq[Partition])

private[sql] object PartitionSpec {
  val emptySpec = PartitionSpec(StructType(Seq.empty[StructField]), Seq.empty[Partition])
}

private[sql] object PartitioningUtils {
  // This duplicates default value of Hive `ConfVars.DEFAULTPARTITIONNAME`, since sql/core doesn't
  // depend on Hive.
  private[sql] val DEFAULT_PARTITION_NAME = "__HIVE_DEFAULT_PARTITION__"

  private[sql] case class PartitionValues(columnNames: Seq[String], literals: Seq[Literal]) {
    require(columnNames.size == literals.size)
  }

  /**
   * Given a group of qualified paths, tries to parse them and returns a partition specification.
   * For example, given:
   * {{{
   *   hdfs://<host>:<port>/path/to/partition/a=1/b=hello/c=3.14
   *   hdfs://<host>:<port>/path/to/partition/a=2/b=world/c=6.28
   * }}}
   * it returns:
   * {{{
   *   PartitionSpec(
   *     partitionColumns = StructType(
   *       StructField(name = "a", dataType = IntegerType, nullable = true),
   *       StructField(name = "b", dataType = StringType, nullable = true),
   *       StructField(name = "c", dataType = DoubleType, nullable = true)),
   *     partitions = Seq(
   *       Partition(
   *         values = Row(1, "hello", 3.14),
   *         path = "hdfs://<host>:<port>/path/to/partition/a=1/b=hello/c=3.14"),
   *       Partition(
   *         values = Row(2, "world", 6.28),
   *         path = "hdfs://<host>:<port>/path/to/partition/a=2/b=world/c=6.28")))
   * }}}
   */
  private[sql] def parsePartitions(
      paths: Seq[Path],
      defaultPartitionName: String,
      typeInference: Boolean): PartitionSpec = {
    // First, we need to parse every partition's path and see if we can find partition values.
    val pathsWithPartitionValues = paths.flatMap { path =>
      parsePartition(path, defaultPartitionName, typeInference).map(path -> _)
    }

    if (pathsWithPartitionValues.isEmpty) {
      // This dataset is not partitioned.
      PartitionSpec.emptySpec
    } else {
      // This dataset is partitioned. We need to check whether all partitions have the same
      // partition columns and resolve potential type conflicts.
      val resolvedPartitionValues = resolvePartitions(pathsWithPartitionValues)

      // Creates the StructType which represents the partition columns.
      val fields = {
        val PartitionValues(columnNames, literals) = resolvedPartitionValues.head
        columnNames.zip(literals).map { case (name, Literal(_, dataType)) =>
          // We always assume partition columns are nullable since we've no idea whether null values
          // will be appended in the future.
          StructField(name, dataType, nullable = true)
        }
      }

      // Finally, we create `Partition`s based on paths and resolved partition values.
      val partitions = resolvedPartitionValues.zip(pathsWithPartitionValues).map {
        case (PartitionValues(_, literals), (path, _)) =>
          Partition(InternalRow.fromSeq(literals.map(_.value)), path.toString)
      }

      PartitionSpec(StructType(fields), partitions)
    }
  }

  /**
   * Parses a single partition, returns column names and values of each partition column.  For
   * example, given:
   * {{{
   *   path = hdfs://<host>:<port>/path/to/partition/a=42/b=hello/c=3.14
   * }}}
   * it returns:
   * {{{
   *   PartitionValues(
   *     Seq("a", "b", "c"),
   *     Seq(
   *       Literal.create(42, IntegerType),
   *       Literal.create("hello", StringType),
   *       Literal.create(3.14, FloatType)))
   * }}}
   */
  private[sql] def parsePartition(
      path: Path,
      defaultPartitionName: String,
      typeInference: Boolean): Option[PartitionValues] = {
    val columns = ArrayBuffer.empty[(String, Literal)]
    // Old Hadoop versions don't have `Path.isRoot`
    var finished = path.getParent == null
    var chopped = path

    while (!finished) {
      // Sometimes (e.g., when speculative task is enabled), temporary directories may be left
      // uncleaned.  Here we simply ignore them.
      if (chopped.getName.toLowerCase == "_temporary") {
        return None
      }

      val maybeColumn = parsePartitionColumn(chopped.getName, defaultPartitionName, typeInference)
      maybeColumn.foreach(columns += _)
      chopped = chopped.getParent
      finished = maybeColumn.isEmpty || chopped.getParent == null
    }

    if (columns.isEmpty) {
      None
    } else {
      val (columnNames, values) = columns.reverse.unzip
      Some(PartitionValues(columnNames, values))
    }
  }

  private def parsePartitionColumn(
      columnSpec: String,
      defaultPartitionName: String,
      typeInference: Boolean): Option[(String, Literal)] = {
    val equalSignIndex = columnSpec.indexOf('=')
    if (equalSignIndex == -1) {
      None
    } else {
      val columnName = columnSpec.take(equalSignIndex)
      assert(columnName.nonEmpty, s"Empty partition column name in '$columnSpec'")

      val rawColumnValue = columnSpec.drop(equalSignIndex + 1)
      assert(rawColumnValue.nonEmpty, s"Empty partition column value in '$columnSpec'")

      val literal = inferPartitionColumnValue(rawColumnValue, defaultPartitionName, typeInference)
      Some(columnName -> literal)
    }
  }

  /**
   * Resolves possible type conflicts between partitions by up-casting "lower" types.  The up-
   * casting order is:
   * {{{
   *   NullType ->
   *   IntegerType -> LongType ->
   *   DoubleType -> StringType
   * }}}
   */
  private[sql] def resolvePartitions(
      pathsWithPartitionValues: Seq[(Path, PartitionValues)]): Seq[PartitionValues] = {
    if (pathsWithPartitionValues.isEmpty) {
      Seq.empty
    } else {
      val distinctPartColNames = pathsWithPartitionValues.map(_._2.columnNames).distinct
      assert(
        distinctPartColNames.size == 1,
        listConflictingPartitionColumns(pathsWithPartitionValues))

      // Resolves possible type conflicts for each column
      val values = pathsWithPartitionValues.map(_._2)
      val columnCount = values.head.columnNames.size
      val resolvedValues = (0 until columnCount).map { i =>
        resolveTypeConflicts(values.map(_.literals(i)))
      }

      // Fills resolved literals back to each partition
      values.zipWithIndex.map { case (d, index) =>
        d.copy(literals = resolvedValues.map(_(index)))
      }
    }
  }

  private[sql] def listConflictingPartitionColumns(
      pathWithPartitionValues: Seq[(Path, PartitionValues)]): String = {
    val distinctPartColNames = pathWithPartitionValues.map(_._2.columnNames).distinct

    def groupByKey[K, V](seq: Seq[(K, V)]): Map[K, Iterable[V]] =
      seq.groupBy { case (key, _) => key }.mapValues(_.map { case (_, value) => value })

    val partColNamesToPaths = groupByKey(pathWithPartitionValues.map {
      case (path, partValues) => partValues.columnNames -> path
    })

    val distinctPartColLists = distinctPartColNames.map(_.mkString(", ")).zipWithIndex.map {
      case (names, index) =>
        s"Partition column name list #$index: $names"
    }

    // Lists out those non-leaf partition directories that also contain files
    val suspiciousPaths = distinctPartColNames.sortBy(_.length).flatMap(partColNamesToPaths)

    s"Conflicting partition column names detected:\n" +
      distinctPartColLists.mkString("\n\t", "\n\t", "\n\n") +
      "For partitioned table directories, data files should only live in leaf directories.\n" +
      "And directories at the same level should have the same partition column name.\n" +
      "Please check the following directories for unexpected files or " +
      "inconsistent partition column names:\n" +
      suspiciousPaths.map("\t" + _).mkString("\n", "\n", "")
  }

  /**
   * Converts a string to a [[Literal]] with automatic type inference.  Currently only supports
   * [[IntegerType]], [[LongType]], [[DoubleType]], [[DecimalType.SYSTEM_DEFAULT]], and
   * [[StringType]].
   */
  private[sql] def inferPartitionColumnValue(
      raw: String,
      defaultPartitionName: String,
      typeInference: Boolean): Literal = {
    if (typeInference) {
      // First tries integral types
      Try(Literal.create(Integer.parseInt(raw), IntegerType))
        .orElse(Try(Literal.create(JLong.parseLong(raw), LongType)))
        // Then falls back to fractional types
        .orElse(Try(Literal.create(JDouble.parseDouble(raw), DoubleType)))
        .orElse(Try(Literal(new JBigDecimal(raw))))
        // Then falls back to string
        .getOrElse {
          if (raw == defaultPartitionName) {
            Literal.create(null, NullType)
          } else {
            Literal.create(unescapePathName(raw), StringType)
          }
        }
    } else {
      if (raw == defaultPartitionName) {
        Literal.create(null, NullType)
      } else {
        Literal.create(unescapePathName(raw), StringType)
      }
    }
  }

  private val upCastingOrder: Seq[DataType] =
    Seq(NullType, IntegerType, LongType, FloatType, DoubleType, StringType)

  def validatePartitionColumnDataTypes(
      schema: StructType,
      partitionColumns: Array[String]): Unit = {

    ResolvedDataSource.partitionColumnsSchema(schema, partitionColumns).foreach { field =>
      field.dataType match {
        case _: AtomicType => // OK
        case _ => throw new AnalysisException(s"Cannot use ${field.dataType} for partition column")
      }
    }
  }

  /**
   * Given a collection of [[Literal]]s, resolves possible type conflicts by up-casting "lower"
   * types.
   */
  private def resolveTypeConflicts(literals: Seq[Literal]): Seq[Literal] = {
    val desiredType = {
      val topType = literals.map(_.dataType).maxBy(upCastingOrder.indexOf(_))
      // Falls back to string if all values of this column are null or empty string
      if (topType == NullType) StringType else topType
    }

    literals.map { case l @ Literal(_, dataType) =>
      Literal.create(Cast(l, desiredType).eval(), desiredType)
    }
  }

  //////////////////////////////////////////////////////////////////////////////////////////////////
  // The following string escaping code is mainly copied from Hive (o.a.h.h.common.FileUtils).
  //////////////////////////////////////////////////////////////////////////////////////////////////

  val charToEscape = {
    val bitSet = new java.util.BitSet(128)

    /**
     * ASCII 01-1F are HTTP control characters that need to be escaped.
     * \u000A and \u000D are \n and \r, respectively.
     */
    val clist = Array(
      '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009',
      '\n', '\u000B', '\u000C', '\r', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013',
      '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001A', '\u001B', '\u001C',
      '\u001D', '\u001E', '\u001F', '"', '#', '%', '\'', '*', '/', ':', '=', '?', '\\', '\u007F',
      '{', '[', ']', '^')

    clist.foreach(bitSet.set(_))

    if (Shell.WINDOWS) {
      Array(' ', '<', '>', '|').foreach(bitSet.set(_))
    }

    bitSet
  }

  def needsEscaping(c: Char): Boolean = {
    c >= 0 && c < charToEscape.size() && charToEscape.get(c)
  }

  def escapePathName(path: String): String = {
    val builder = new StringBuilder()
    path.foreach { c =>
      if (needsEscaping(c)) {
        builder.append('%')
        builder.append(f"${c.asInstanceOf[Int]}%02x")
      } else {
        builder.append(c)
      }
    }

    builder.toString()
  }

  def unescapePathName(path: String): String = {
    val sb = new StringBuilder
    var i = 0

    while (i < path.length) {
      val c = path.charAt(i)
      if (c == '%' && i + 2 < path.length) {
        val code: Int = try {
          Integer.valueOf(path.substring(i + 1, i + 3), 16)
        } catch { case e: Exception =>
          -1: Integer
        }
        if (code >= 0) {
          sb.append(code.asInstanceOf[Char])
          i += 3
        } else {
          sb.append(c)
          i += 1
        }
      } else {
        sb.append(c)
        i += 1
      }
    }

    sb.toString()
  }
}


text:
using UnityEngine;
using System.Collections;

[System.Serializable]
public class Graphics
{
	void Start()
	{
        //Load saved settings from File
	}

	public void increaseQualityLevel()
	{
		QualitySettings.IncreaseLevel ();
	}

	public void decreaseQualityLevel()
	{
		QualitySettings.DecreaseLevel ();
	}

	public void setQualityLevel(float level)
	{
		QualitySettings.SetQualityLevel ((int)level);
	}

    public void setAntiAliasing(int level)
    {
        QualitySettings.antiAliasing = level;
    }

    public void setShadows(ShadowResolution res)
    {
        QualitySettings.shadowResolution = res;
    }

    public void setVSync(bool b)
    {
        if (b)
            QualitySettings.vSyncCount = 1;
        else
            QualitySettings.vSyncCount = 0;
    }

    public void setTripleBuffering(bool b)
    {
        if (b)
            QualitySettings.maxQueuedFrames = 3;
        else
            QualitySettings.maxQueuedFrames = 0;
    }

    public void setScreenResolution(int values)
    {
        //Screen.SetResolution();
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Atata
{
    /// <summary>
    /// Represents the link control (<c><a></c>).
    /// Default search is performed by the content.
    /// </summary>
    /// <typeparam name="TNavigateTo">The type of the page object to navigate to.</typeparam>
    /// <typeparam name="TOwner">The type of the owner page object.</typeparam>
    /// <seealso cref="Link{TOwner}" />
    public class Link<TNavigateTo, TOwner> : Link<TOwner>, INavigable<TNavigateTo, TOwner>
        where TNavigateTo : PageObject<TNavigateTo>
        where TOwner : PageObject<TOwner>
    {
    }
}


text:
package com.github.binding;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

import org.junit.Test;

import com.github.binding.PropertyExtractor.CouldNotGetFieldException;

public class PropertyExtractorTest {
    class MyTest {
        public Property<Integer> x = new Property<Integer>(10);
        public Integer y = new Integer(5);
        @SuppressWarnings("unused")
        private Property<Integer> x2 = new Property<Integer>(20);
        Integer y2 = new Integer(5);
    }

    private PropertyExtractor extractor = new PropertyExtractor();
    private MyTest test = new MyTest();

    @Test public void testGetProperty() {
        @SuppressWarnings("unchecked")
        Property<Integer> p =
            (Property<Integer>)extractor.unsafeGetNamedProperty(test, "x");

        assertThat(p.get(), equalTo(10));
    }

    @Test(expected=CouldNotGetFieldException.class)
    public void testGetInvalidProperty1() {
        extractor.unsafeGetNamedProperty(test, "y");
    }

    @Test(expected=CouldNotGetFieldException.class)
    public void testGetInvalidProperty2() {
        extractor.unsafeGetNamedProperty(test, "x2");
    }

    @Test(expected=CouldNotGetFieldException.class)
    public void testGetInvalidProperty3() {
        extractor.unsafeGetNamedProperty(test, "y2");
    }
}


text:
package com.alibaba.otter.manager.biz.monitor;

import com.alibaba.otter.manager.biz.common.alarm.AlarmMessage;
import com.alibaba.otter.shared.common.model.config.alarm.AlarmRule;

/**
 * @author zebin.xuzb
 * @version 4.1.0
 */
public interface AlarmController {

    public AlarmMessage control(AlarmRule rule, String message, AlarmMessage data);

}


text:
from sqlalchemy import create_engine
import sqlalchemy as sa
from dynd import nd
import unittest

from blaze.data.sql import SQL, discover
from blaze.utils import raises
from datashape import dshape, var
import datashape

class SingleTestClass(unittest.TestCase):
    def setUp(self):
        self.engine = create_engine('sqlite:///:memory:', echo=False)

    def tearDown(self):
        pass
        # How do I clean up an engine?

    def test_setup_with_uri(self):
        dd = SQL('sqlite:///:memory:',
                 'accounts',
                 schema='{name: string, amount: int}')

    def test_can_connect(self):
        with self.engine.connect() as conn:
            assert not conn.closed
        assert conn.closed

    def test_table_creation(self):
        dd = SQL(self.engine, 'testtable',
                              schema='{name: string, amount: int}',
                              primary_key='name')
        assert self.engine.has_table('testtable')

        assert dd.table.columns.get('name').primary_key
        assert not dd.table.columns.get('amount').primary_key
        assert dd.dshape == dshape('var * {name: string, amount: int}')

        assert raises(ValueError, lambda: SQL(self.engine, 'testtable2'))

    def test_extension(self):
        dd = SQL(self.engine, 'testtable2',
                               schema='{name: string, amount: int32}',
                               primary_key='name')

        data_list = [('Alice', 100), ('Bob', 50)]
        data_dict = [{'name': name, 'amount': amount} for name, amount in data_list]

        dd.extend(data_dict)

        with self.engine.connect() as conn:
            results = conn.execute('select * from testtable2')
            self.assertEquals(list(results), data_list)

        assert list(iter(dd)) == data_list or list(iter(dd)) == data_dict
        assert (dd.as_py() == tuple(map(tuple, data_list)) or
                dd.as_py() == data_dict)

    def test_chunks(self):
        schema = '{name: string, amount: int32}'
        dd = SQL(self.engine, 'testtable3',
                              schema=schema,
                              primary_key='name')

        data_list = [('Alice', 100), ('Bob', 50), ('Charlie', 200)]
        data_dict = [{'name': name, 'amount': amount} for name, amount in data_list]
        chunk = nd.array(data_list, dtype=str(dd.dshape))

        dd.extend_chunks([chunk])

        assert list(iter(dd)) == data_list or list(iter(dd)) == data_dict

        self.assertEquals(len(list(dd.chunks(blen=2))), 2)

    def test_indexing(self):
        dd = SQL(self.engine, 'testtable',
                 schema='{name: string, amount: int, id: int}',
                 primary_key='id')

        data = [('Alice', 100, 1), ('Bob', 50, 2), ('Charlie', 200, 3)]
        dd.extend(data)

        self.assertEqual(set(dd.py[:, ['id', 'name']]),
                        set(((1, 'Alice'), (2, 'Bob'), (3, 'Charlie'))))
        self.assertEqual(set(dd.py[:, 'name']), set(('Alice', 'Bob', 'Charlie')))
        assert dd.py[0, 'name'] in ('Alice', 'Bob', 'Charlie')
        self.assertEqual(set(dd.py[:, 0]), set(dd.py[:, 'name']))
        self.assertEqual(set(dd.py[:, [1, 0]]), set(dd.py[:, ['amount', 'name']]))
        self.assertEqual(len(list(dd.py[:2, 'name'])), 2)
        self.assertEqual(set(dd.py[:, :]), set(data))
        self.assertEqual(set(dd.py[:, :2]), set(dd.py[:, ['name', 'amount']]))
        self.assertEqual(set(dd.py[:]), set(dd.py[:, :]))
        assert dd.py[0] in data

def test_discovery():
    assert discover(sa.String()) == datashape.string
    metadata = sa.MetaData()
    s = sa.Table('accounts', metadata,
                 sa.Column('name', sa.String),
                 sa.Column('amount', sa.Integer),
                 sa.Column('timestamp', sa.DateTime, primary_key=True))

    assert discover(s) == \
            dshape('var * {name: string, amount: int32, timestamp: datetime}')

def test_discovery_engine():
    dd = SQL('sqlite:///:memory:',
             'accounts',
             schema='{name: string, amount: int}')

    dshape = discover(dd.engine, 'accounts')

    assert dshape == dd.dshape

def test_schema_detection():
    dd = SQL('sqlite:///my.db',
             'accounts',
             schema='{name: string, amount: int32}')

    dd.extend([['Alice', 100], ['Bob', 200]])

    dd2 = SQL('sqlite:///my.db', 'accounts')

    assert dd.schema == dd2.schema


text:
package com.stulsoft.graphx

import org.apache.spark._
import org.apache.spark.graphx.{Edge, Graph}

/** Demonstrates creation of Graph
  *
  * Each vertex is tuple of  vertex ID and a property. In this case property is Person class.
  * Edge attribute is string.
  *
  * @author Yuriy Stul
  */
object ConstructGraph1 extends App {
  val conf = new SparkConf().setAppName("ConstructGraph1").setMaster("local[*]")
  val sc = new SparkContext(conf)
  val vertices = sc.parallelize(Array((1L, Person("Homer", 39)),
    (2L, Person("Marge", 39)), (3L, Person("Bart", 12)),
    (4L, Person("Milhouse", 12))))
  val edges = sc.parallelize(Array(Edge(4L, 3L, "friend"),
    Edge(3L, 1L, "father"), Edge(3L, 2L, "mother"),
    Edge(1L, 2L, "marriedTo")))

  val graph = Graph(vertices, edges)

  println(s"Graph has ${graph.vertices.count} vertices and ${graph.edges.count} edges.")

  println("Vertices:")
  graph.vertices
    .sortBy({ case (i, _) => i })
    .collect
    .foreach({ case (i, p) => println(s"$i $p") })

  println("Edges:")
  graph.edges
    .sortBy(e => e.srcId)
    .collect
    .foreach({ case Edge(s, d, r) => r match {
      case "marriedTo" => println(s"$s $r $d")
      case _ => println(s"$s  is $r of $d")
    }
    })

  sc.stop()
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<aim:ImageAnnotation xmlns:aim="http://www.radiology.northwestern.edu/aim/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.radiology.northwestern.edu/aim/1 AIMv1_06.xsd">

  <aim:id>0</aim:id>

  <aim:aimVersion>AIM.1.0</aim:aimVersion>

  <aim:comment />

  <aim:dateTime>0001-01-01</aim:dateTime>

  <aim:name>0020-3</aim:name>

  <aim:uid>1.2.288.3.1220941281.3804.1194801849.169</aim:uid>

  <aim:anatomicEntityCollection>
    <aim:AnatomicEntity>
      <aim:id>0</aim:id>
      <aim:codeMeaning>LUNG</aim:codeMeaning>
      <aim:codingSchemeDesignator>RADLEX</aim:codingSchemeDesignator>
      <aim:codeValue>REX0001</aim:codeValue>
      <aim:relationship />
      <aim:relatedAnatomicEntity>
        <aim:AnatomicEntity>
          <aim:id>0</aim:id>
          <aim:codeMeaning>RIGHT LOWER LOBE</aim:codeMeaning>
          <aim:codingSchemeDesignator>RADLEX</aim:codingSchemeDesignator>
          <aim:codeValue>REX10006</aim:codeValue>
          <aim:relationship>PART OF</aim:relationship>
          <aim:relatedAnatomicEntity />
        </aim:AnatomicEntity>
      </aim:relatedAnatomicEntity>
    </aim:AnatomicEntity>
  </aim:anatomicEntityCollection>

  <aim:imagingObservationCollection>
    <aim:ImagingObservation>
      <aim:id>0</aim:id>
      <aim:codeMeaning>Conspicuity</aim:codeMeaning>
      <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
      <aim:codeValue>REX4001</aim:codeValue>
      <aim:comment />
      <aim:imagingObservationCharacteristicCollection>
        <aim:ImagingObservationCharacteristic>
          <aim:id>0</aim:id>
          <aim:codeMeaning>Very Obvious</aim:codeMeaning>
          <aim:codingSchemeDesignator>RADLEX</aim:codingSchemeDesignator>
          <aim:codeValue>REX4006</aim:codeValue>
          <aim:comment />
        </aim:ImagingObservationCharacteristic>
      </aim:imagingObservationCharacteristicCollection>
    </aim:ImagingObservation>
    <aim:ImagingObservation>
      <aim:id>0</aim:id>
      <aim:codeMeaning>Internal Structure</aim:codeMeaning>
      <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
      <aim:codeValue>REX4002</aim:codeValue>
      <aim:comment />
      <aim:imagingObservationCharacteristicCollection>
        <aim:ImagingObservationCharacteristic>
          <aim:id>0</aim:id>
          <aim:codeMeaning>LIDC Soft Tissue</aim:codeMeaning>
          <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
          <aim:codeValue>REX4010</aim:codeValue>
          <aim:comment />
        </aim:ImagingObservationCharacteristic>
      </aim:imagingObservationCharacteristicCollection>
    </aim:ImagingObservation>
    <aim:ImagingObservation>
      <aim:id>0</aim:id>
      <aim:codeMeaning>Calcification</aim:codeMeaning>
      <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
      <aim:codeValue>REX4010</aim:codeValue>
      <aim:comment />
      <aim:imagingObservationCharacteristicCollection>
        <aim:ImagingObservationCharacteristic>
          <aim:id>0</aim:id>
          <aim:codeMeaning>LIDC Calcification 1</aim:codeMeaning>
          <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
          <aim:codeValue>REX4020</aim:codeValue>
          <aim:comment />
        </aim:ImagingObservationCharacteristic>
      </aim:imagingObservationCharacteristicCollection>
    </aim:ImagingObservation>
    <aim:ImagingObservation>
      <aim:id>0</aim:id>
      <aim:codeMeaning>Sphericity </aim:codeMeaning>
      <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
      <aim:codeValue>REX4015</aim:codeValue>
      <aim:comment />
      <aim:imagingObservationCharacteristicCollection>
        <aim:ImagingObservationCharacteristic>
          <aim:id>0</aim:id>
          <aim:codeMeaning>LIDC Sphericity 5</aim:codeMeaning>
          <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
          <aim:codeValue>REX4036</aim:codeValue>
          <aim:comment />
        </aim:ImagingObservationCharacteristic>
      </aim:imagingObservationCharacteristicCollection>
    </aim:ImagingObservation>
    <aim:ImagingObservation>
      <aim:id>0</aim:id>
      <aim:codeMeaning>Margin</aim:codeMeaning>
      <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
      <aim:codeValue>REX4019</aim:codeValue>
      <aim:comment />
      <aim:imagingObservationCharacteristicCollection>
        <aim:ImagingObservationCharacteristic>
          <aim:id>0</aim:id>
          <aim:codeMeaning>LIDC Margin 4</aim:codeMeaning>
          <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
          <aim:codeValue>REX4043</aim:codeValue>
          <aim:comment />
        </aim:ImagingObservationCharacteristic>
      </aim:imagingObservationCharacteristicCollection>
    </aim:ImagingObservation>
    <aim:ImagingObservation>
      <aim:id>0</aim:id>
      <aim:codeMeaning>Texture</aim:codeMeaning>
      <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
      <aim:codeValue>REX4025</aim:codeValue>
      <aim:comment />
      <aim:imagingObservationCharacteristicCollection>
        <aim:ImagingObservationCharacteristic>
          <aim:id>0</aim:id>
          <aim:codeMeaning>LIDC Texture 5</aim:codeMeaning>
          <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
          <aim:codeValue>REX4064</aim:codeValue>
          <aim:comment />
        </aim:ImagingObservationCharacteristic>
        <aim:ImagingObservationCharacteristic>
          <aim:id>0</aim:id>
          <aim:codeMeaning>LIDC Texture 1</aim:codeMeaning>
          <aim:codingSchemeDesignator>RADREX</aim:codingSchemeDesignator>
          <aim:codeValue>REX4060</aim:codeValue>
          <aim:comment />
        </aim:ImagingObservationCharacteristic>
      </aim:imagingObservationCharacteristicCollection>
    </aim:ImagingObservation>
  </aim:imagingObservationCollection>

  <aim:calculationCollection>
    <aim:Calculation>
      <aim:id>0</aim:id>
      <aim:uid>0</aim:uid>
      <aim:description>Linear Measurement</aim:description>
      <aim:mathML />
      <aim:type>Long Axis</aim:type>
      <aim:calculationResultCollection>
        <aim:CalculationResult>
          <aim:id>0</aim:id>
          <aim:type>Scalar</aim:type>
          <aim:numberOfDimensions>1</aim:numberOfDimensions>
          <aim:unitOfMeasure>mm</aim:unitOfMeasure>
          <aim:dimensionCollection>
            <aim:Dimension>
              <aim:id>0</aim:id>
              <aim:index>0</aim:index>
              <aim:size>1</aim:size>
              <aim:label>Length</aim:label>
            </aim:Dimension>
          </aim:dimensionCollection>
          <aim:dataCollection>
            <aim:Data>
              <aim:id>0</aim:id>
              <aim:value>12.2726860046387</aim:value>
              <aim:coordinateCollection>
                <aim:Coordinate>
                  <aim:id>0</aim:id>
                  <aim:dimensionIndex>0</aim:dimensionIndex>
                  <aim:position>0</aim:position>
                </aim:Coordinate>
              </aim:coordinateCollection>
            </aim:Data>
          </aim:dataCollection>
        </aim:CalculationResult>
      </aim:calculationResultCollection>
      <aim:referencedCalculationCollection />
    </aim:Calculation>
  </aim:calculationCollection>

  <aim:user>
    <aim:User>
      <aim:id>0</aim:id>
      <aim:authorName>scd3</aim:authorName>
      <aim:loginName>NWU</aim:loginName>
      <aim:roleInTrial>Recording</aim:roleInTrial>
      <aim:numberWithinRoleOfClinicalTrial>3</aim:numberWithinRoleOfClinicalTrial>
    </aim:User>
  </aim:user>

  <aim:imageAnnotationType />

  <aim:textAnnotationCollection />

  <aim:geometricShapeCollection>
    <aim:GeometricShape xsi:type="aim:Polyline">
      <aim:id>0</aim:id>
      <aim:lineColor />
      <aim:lineOpacity />
      <aim:lineStyle />
      <aim:lineThickness />
      <aim:includeFlag>false</aim:includeFlag>
      <aim:shapeId>-1</aim:shapeId>
      <aim:spatialCoordinateCollection>
        <aim:SpatialCoordinate>
          <aim:id>0</aim:id>
          <aim:x>82</aim:x>
          <aim:y>357</aim:y>
          <aim:z>0</aim:z>
          <aim:imageReferenceUID>1.3.6.1.4.1.9328.50.1.9339</aim:imageReferenceUID>
          <aim:referencedFrameNumber>0</aim:referencedFrameNumber>
        </aim:SpatialCoordinate>
        <aim:SpatialCoordinate>
          <aim:id>0</aim:id>
          <aim:x>104</aim:x>
          <aim:y>354</aim:y>
          <aim:z>0</aim:z>
          <aim:imageReferenceUID>1.3.6.1.4.1.9328.50.1.9339</aim:imageReferenceUID>
          <aim:referencedFrameNumber>0</aim:referencedFrameNumber>
        </aim:SpatialCoordinate>
      </aim:spatialCoordinateCollection>
    </aim:GeometricShape>
  </aim:geometricShapeCollection>

  <aim:imageReferenceCollection>
    <aim:ImageReference xsi:type="aim:DICOMImageReference">
      <aim:id>0</aim:id>
      <aim:institutionName />
      <aim:dicomSeriesUID>1.3.6.1.4.1.9328.50.1.9325</aim:dicomSeriesUID>
      <aim:dicomSOPInstanceUID>1.3.6.1.4.1.9328.50.1.9339</aim:dicomSOPInstanceUID>
      <aim:dicomStudyUID>1.3.6.1.4.1.9328.50.1.9258</aim:dicomStudyUID>
      <aim:dicomSOPClassUID>1.2.840.10008.5.1.4.1.1.2</aim:dicomSOPClassUID>
    </aim:ImageReference>
  </aim:imageReferenceCollection>

  <aim:probabilityMapCollection />

</aim:ImageAnnotation>


text:
package com.matter.tv.server.tvapp;

import android.util.Log;

public class WakeOnLanManagerStub implements WakeOnLanManager {

  private final String TAG = WakeOnLanManagerStub.class.getSimpleName();

  private int endpoint;

  public WakeOnLanManagerStub(int endpoint) {
    this.endpoint = endpoint;
  }

  @Override
  public String getMac() {
    Log.d(TAG, "getMac for endpoint=" + endpoint);
    return "AA:BB:CC:DD:EE";
  }
}


text:
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createRenderer, screen, fireEvent } from 'test/utils';
import createCssVarsProvider, { DISABLE_CSS_TRANSITION } from './createCssVarsProvider';
import { DEFAULT_ATTRIBUTE, DEFAULT_MODE_STORAGE_KEY } from './getInitColorSchemeScript';
import useTheme from '../useTheme';

describe('createCssVarsProvider', () => {
  const { clock, render } = createRenderer();
  let originalMatchmedia;
  let storage = {};
  const createMatchMedia = (matches) => () => ({
    matches,
    addListener: () => {},
    removeListener: () => {},
  });
  let shouldSupportColorScheme;

  beforeEach(() => {
    originalMatchmedia = window.matchMedia;

    // Create mocks of localStorage getItem and setItem functions
    Object.defineProperty(global, 'localStorage', {
      value: {
        getItem: spy((key) => storage[key]),
        setItem: spy((key, value) => {
          storage[key] = value;
        }),
      },
      configurable: true,
    });

    // clear the localstorage
    storage = {};
    window.matchMedia = createMatchMedia(false);

    // Currently supported Firefox does not support `color-scheme`.
    // Instead of skipping relevant tests entirely we assert that they work differently in Firefox.
    // This ensures that we're automatically notified once we remove older Firefox versions from the support matrix.
    shouldSupportColorScheme = !/Firefox/.test(navigator.userAgent);
  });
  afterEach(() => {
    window.matchMedia = originalMatchmedia;
  });

  describe('[Design System] CssVarsProvider', () => {
    it('display error if `defaultColorScheme` does not exist in theme.colorSchemes', () => {
      expect(() =>
        createCssVarsProvider({
          theme: {},
          defaultColorScheme: 'light',
        }),
      ).toErrorDev('MUI: `light` does not exist in `theme.colorSchemes`.');
    });

    it('has specified default colorScheme', () => {
      const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: {} },
        },
        defaultColorScheme: 'light',
      });
      const Consumer = () => {
        const { colorScheme } = useColorScheme();
        return
{colorScheme}
;
      };
      render(
        <CssVarsProvider>
          <Consumer />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('current-color-scheme').textContent).to.equal('light');
    });

    it('has CSS variable prefix', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: { fontSize: 16 } },
        },
        defaultColorScheme: 'light',
        prefix: 'mui',
      });
      const Text = () => {
        const theme = useTheme();
        return <div data-testid={`text`}>{theme.vars.fontSize}
;
      };
      render(
        <CssVarsProvider>
          <Text />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('text').textContent).to.equal('var(--mui-fontSize)');
    });

    it('provide getCssVar util', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: { palette: { primary: { 500: '#ff5252' } } } },
        },
        defaultColorScheme: 'light',
        prefix: 'mui',
      });
      const Text = () => {
        const theme = useTheme();
        return <div data-testid={`text`}>{theme.getCssVar('palette-primary-500')}
;
      };
      render(
        <CssVarsProvider>
          <Text />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('text').textContent).to.equal('var(--mui-palette-primary-500)');
    });

    it('provide getColorSchemeSelector util', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: { palette: { primary: { 500: '#ff5252' } } } },
        },
        defaultColorScheme: 'light',
      });
      const Text = () => {
        const theme = useTheme();
        return <div data-testid={`text`}>{theme.getColorSchemeSelector('light')}
;
      };
      render(
        <CssVarsProvider attribute="data-custom-color-scheme">
          <Text />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('text').textContent).to.equal(
        '[data-custom-color-scheme="light"] &',
      );
    });

    it('can access to allColorSchemes', () => {
      const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
        theme: {
          colorSchemes: {
            light: {},
            dark: {},
          },
        },
        defaultColorScheme: 'light',
      });
      const Consumer = () => {
        const { allColorSchemes } = useColorScheme();
        return
{allColorSchemes.join(',')}
;
      };
      const { rerender } = render(
        <CssVarsProvider>
          <Consumer />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('all-colorSchemes').textContent).to.equal('light,dark');

      rerender(
        <CssVarsProvider
          theme={{
            colorSchemes: { light: {}, dark: {}, comfort: { palette: { color: '#e5e5e5' } } },
          }}
        >
          <Consumer />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('all-colorSchemes').textContent).to.equal('light,dark,comfort');
    });

    it('can set new colorScheme', () => {
      const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: {}, dark: {} },
        },
        defaultColorScheme: 'light',
      });
      const Consumer = () => {
        const { colorScheme, setColorScheme } = useColorScheme();
        return (

{colorScheme}

            <button onClick={() => setColorScheme('dark')}>change to dark</button>

        );
      };
      render(
        <CssVarsProvider>
          <Consumer />
        </CssVarsProvider>,
      );

      fireEvent.click(screen.getByRole('button', { name: 'change to dark' }));

      expect(screen.getByTestId('current-color-scheme').textContent).to.equal('dark');
      expect(document.documentElement.getAttribute(DEFAULT_ATTRIBUTE)).to.equal('dark');
    });

    it('display error if non-existed colorScheme is set', () => {
      const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: {} },
        },
        defaultColorScheme: 'light',
      });
      const Consumer = () => {
        const { setColorScheme } = useColorScheme();
        return <button onClick={() => setColorScheme('foo')}>change to dark</button>;
      };

      render(
        <CssVarsProvider>
          <Consumer />
        </CssVarsProvider>,
      );

      expect(() =>
        fireEvent.click(screen.getByRole('button', { name: 'change to dark' })),
      ).toErrorDev('`foo` does not exist in `theme.colorSchemes`.');
    });

    it('does not create css var if shouldSkipGeneratingVar return true', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: {
            light: {
              typography: {
                htmlFontSize: '16px',
                h1: {
                  fontSize: '1rem',
                  fontWeight: 500,
                },
              },
            },
          },
        },
        defaultColorScheme: 'light',
        shouldSkipGeneratingVar: (keys) => keys[0] === 'typography' && keys[1] === 'h1',
      });
      const Consumer = () => {
        const theme = useTheme();
        return
{theme.vars.typography.h1 || ''}
;
      };
      expect(() =>
        render(
          <CssVarsProvider>
            <Consumer />
          </CssVarsProvider>,
        ),
      ).not.toErrorDev(); // if `h1` is skipped, there will be no error.
    });

    it('vars are merged from all colorSchemes regardless of selected color scheme', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: {
            light: {
              palette: {
                primary: '#000',
              },
            },
            dark: {
              palette: {
                grey: '#888',
              },
            },
          },
        },
        defaultColorScheme: 'light',
      });
      const Consumer = () => {
        const theme = useTheme();
        return (

{theme.vars.palette.primary || ''}

{theme.vars.palette.grey || ''}

        );
      };
      render(
        <CssVarsProvider>
          <Consumer />
        </CssVarsProvider>,
      );
      expect(screen.getByText('var(--palette-primary)')).not.to.equal(null);
      expect(screen.getByText('var(--palette-grey)')).not.to.equal(null);
    });

    describe('[option]: `enableColorScheme`', () => {
      it('set `color-scheme` property on  with correct mode, given `enableColorScheme` is true and `mode` is `light` or `dark`', () => {
        const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
          theme: {
            colorSchemes: { light: {}, dark: {} },
          },
          defaultColorScheme: 'light',
          enableColorScheme: true,
        });
        const Consumer = () => {
          const { setMode } = useColorScheme();
          return <button onClick={() => setMode('dark')}>change to dark</button>;
        };
        render(
          <CssVarsProvider>
            <Consumer />
          </CssVarsProvider>,
        );
        expect(document.documentElement).toHaveComputedStyle({
          colorScheme: shouldSupportColorScheme ? 'light' : '',
        });

        fireEvent.click(screen.getByRole('button', { name: 'change to dark' }));

        expect(document.documentElement).toHaveComputedStyle({
          colorScheme: shouldSupportColorScheme ? 'dark' : '',
        });
      });

      it('set `color-scheme` property on  with correct mode, given `enableColorScheme` is true and mode is `system`', () => {
        window.matchMedia = createMatchMedia(true); // system matches 'prefers-color-scheme: dark'

        const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
          theme: {
            colorSchemes: { light: {}, dark: {} },
          },
          defaultColorScheme: 'light',
          enableColorScheme: true,
        });
        const Consumer = () => {
          const { setMode } = useColorScheme();
          return <button onClick={() => setMode('system')}>change to system</button>;
        };
        render(
          <CssVarsProvider>
            <Consumer />
          </CssVarsProvider>,
        );
        expect(document.documentElement).toHaveComputedStyle({
          colorScheme: shouldSupportColorScheme ? 'light' : '',
        });

        fireEvent.click(screen.getByRole('button', { name: 'change to system' }));

        expect(document.documentElement).toHaveComputedStyle({
          colorScheme: shouldSupportColorScheme ? 'dark' : '',
        });
      });

      it('does not set `color-scheme` property on  with correct mode, given`enableColorScheme` is false', () => {
        const currentColorScheme = window
          .getComputedStyle(document.documentElement)
          .getPropertyValue('color-scheme');
        const { CssVarsProvider } = createCssVarsProvider({
          theme: {
            colorSchemes: { light: {}, dark: {} },
          },
          defaultColorScheme: 'light',
          enableColorScheme: false,
        });
        const Consumer = () =>
;

        render(
          <CssVarsProvider>
            <Consumer />
          </CssVarsProvider>,
        );
        expect(document.documentElement).toHaveComputedStyle({
          colorScheme: shouldSupportColorScheme ? currentColorScheme : '',
        });
      });

      it('cleans up `color-scheme` property on , given`enableColorScheme` is true', () => {
        const previousColorScheme = window
          .getComputedStyle(document.documentElement)
          .getPropertyValue('color-scheme');
        const { CssVarsProvider } = createCssVarsProvider({
          theme: {
            colorSchemes: { light: {}, dark: {} },
          },
          defaultColorScheme: 'light',
          enableColorScheme: true,
        });
        const { unmount } = render(<CssVarsProvider />);

        unmount();

        expect(document.documentElement).toHaveComputedStyle({
          colorScheme: previousColorScheme,
        });
      });
    });

    describe('[option]: `disableTransitionOnChange`', () => {
      clock.withFakeTimers();
      it('disable all css transitions when switching bewteen modes, given `disableTransitionOnChange` is true', () => {
        const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
          theme: {
            colorSchemes: { light: {}, dark: {} },
          },
          defaultColorScheme: {
            light: 'light',
            dark: 'dark',
          },
          disableTransitionOnChange: true,
        });
        const Consumer = () => {
          const { mode, setMode } = useColorScheme();
          return (

{mode}

              <button onClick={() => setMode('dark')}>change to dark</button>;

          );
        };
        render(
          <CssVarsProvider>
            <Consumer />
          </CssVarsProvider>,
        );

        expect(document.head.children[document.head.children.length - 1].textContent).not.to.equal(
          DISABLE_CSS_TRANSITION,
        );
        fireEvent.click(screen.getByRole('button', { name: 'change to dark' }));
        expect(document.head.children[document.head.children.length - 1].textContent).to.equal(
          DISABLE_CSS_TRANSITION,
        );
        expect(screen.getByTestId('current-mode').textContent).to.equal('dark');

        clock.runToLast();
        expect(document.head.children[document.head.children.length - 1].textContent).not.to.equal(
          DISABLE_CSS_TRANSITION,
        );
      });

      it('disable all css transitions when switching bewteen color schemes, given `disableTransitionOnChange` is true', () => {
        const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
          theme: {
            colorSchemes: { light: {}, dark: {} },
          },
          defaultColorScheme: {
            light: 'light',
            dark: 'dark',
          },
          disableTransitionOnChange: true,
        });
        const Consumer = () => {
          const { colorScheme, setColorScheme } = useColorScheme();
          return (

{colorScheme}

              <button onClick={() => setColorScheme('dark')}>change to dark</button>;

          );
        };
        render(
          <CssVarsProvider>
            <Consumer />
          </CssVarsProvider>,
        );

        expect(document.head.children[document.head.children.length - 1].textContent).not.to.equal(
          DISABLE_CSS_TRANSITION,
        );
        fireEvent.click(screen.getByRole('button', { name: 'change to dark' }));
        expect(document.head.children[document.head.children.length - 1].textContent).to.equal(
          DISABLE_CSS_TRANSITION,
        );
        expect(screen.getByTestId('current-color-scheme').textContent).to.equal('dark');

        clock.runToLast();
        expect(document.head.children[document.head.children.length - 1].textContent).not.to.equal(
          DISABLE_CSS_TRANSITION,
        );
      });

      it('do not disable all css transitions when switching bewteen modes, given `disableTransitionOnChange` is false', () => {
        const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
          theme: {
            colorSchemes: { light: {}, dark: {} },
          },
          defaultColorScheme: 'light',
          disableTransitionOnChange: false,
        });
        const Consumer = () => {
          const { mode, setMode } = useColorScheme();
          return (

{mode}

              <button onClick={() => setMode('dark')}>change to dark</button>;

          );
        };
        render(
          <CssVarsProvider>
            <Consumer />
          </CssVarsProvider>,
        );

        expect(document.head.children[document.head.children.length - 1].textContent).not.to.equal(
          DISABLE_CSS_TRANSITION,
        );
        fireEvent.click(screen.getByRole('button', { name: 'change to dark' }));
        expect(document.head.children[document.head.children.length - 1].textContent).not.to.equal(
          DISABLE_CSS_TRANSITION,
        );
        expect(screen.getByTestId('current-mode').textContent).to.equal('dark');
      });

      it('do not disable all css transitions when switching bewteen color schemes, given `disableTransitionOnChange` is false', () => {
        const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
          theme: {
            colorSchemes: { light: {}, dark: {} },
          },
          defaultColorScheme: 'light',
          disableTransitionOnChange: false,
        });
        const Consumer = () => {
          const { colorScheme, setColorScheme } = useColorScheme();
          return (

{colorScheme}

              <button onClick={() => setColorScheme('dark')}>change to dark</button>;

          );
        };
        render(
          <CssVarsProvider>
            <Consumer />
          </CssVarsProvider>,
        );

        expect(document.head.children[document.head.children.length - 1].textContent).not.to.equal(
          DISABLE_CSS_TRANSITION,
        );
        fireEvent.click(screen.getByRole('button', { name: 'change to dark' }));
        expect(document.head.children[document.head.children.length - 1].textContent).not.to.equal(
          DISABLE_CSS_TRANSITION,
        );
        expect(screen.getByTestId('current-color-scheme').textContent).to.equal('dark');
      });
    });
  });

  describe('DOM', () => {
    it('attach default dataset on html', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: {} },
        },
        defaultColorScheme: 'light',
      });
      render(<CssVarsProvider />);

      expect(document.documentElement.getAttribute(DEFAULT_ATTRIBUTE)).to.equal('light');
    });

    it('use custom attribute', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: {} },
        },
        defaultColorScheme: 'light',
      });
      const customAttribute = 'data-foo-bar';

      render(<CssVarsProvider attribute={customAttribute} />);

      expect(document.documentElement.getAttribute('data-foo-bar')).to.equal('light');
    });

    it('does not crash if documentNode is null', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: {} },
        },
        defaultColorScheme: 'light',
      });

      expect(() => render(<CssVarsProvider documentNode={null} />)).not.to.throw();
    });

    it('does not crash if colorSchemeNode is null', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: {} },
        },
        defaultColorScheme: 'light',
      });

      expect(() => render(<CssVarsProvider colorSchemeNode={null} />)).not.to.throw();
    });
  });

  describe('Storage', () => {
    const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
      theme: {
        colorSchemes: { light: {}, dark: {} },
      },
      defaultColorScheme: 'light',
    });
    const Consumer = () => {
      const { mode, setMode } = useColorScheme();
      return (

{mode}

          <button onClick={() => setMode('dark')}>change to dark</button>

      );
    };
    it('should save mode to localStorage', () => {
      render(
        <CssVarsProvider>
          <Consumer />
        </CssVarsProvider>,
      );

      expect(global.localStorage.setItem.calledWith(DEFAULT_MODE_STORAGE_KEY, 'light')).to.equal(
        true,
      );

      fireEvent.click(screen.getByRole('button', { name: 'change to dark' }));

      expect(global.localStorage.setItem.calledWith(DEFAULT_MODE_STORAGE_KEY, 'dark')).to.equal(
        true,
      );
    });

    it('should use mode from localStorage if exists', () => {
      storage[DEFAULT_MODE_STORAGE_KEY] = 'dark';

      render(
        <CssVarsProvider>
          <Consumer />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('current-mode').textContent).to.equal('dark');
    });

    it('use custom modeStorageKey', () => {
      const customModeStorageKey = 'foo-mode';
      storage[customModeStorageKey] = 'dark';

      render(
        <CssVarsProvider modeStorageKey={customModeStorageKey}>
          <Consumer />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('current-mode').textContent).to.equal('dark');
      expect(global.localStorage.setItem.calledWith(customModeStorageKey, 'dark')).to.equal(true);
    });

    it('support custom storage window', () => {
      const storageWindow = {
        addEventListener: (key, handler) => {
          if (key === 'storage') {
            handler({ key: DEFAULT_MODE_STORAGE_KEY, newValue: 'dark' });
          }
        },
        removeEventListener: () => {},
      };
      render(
        <CssVarsProvider storageWindow={storageWindow}>
          <Consumer />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('current-mode')).to.have.text('dark');
    });
  });

  /**
   * This can occur if two application use default storage key
   * App I: supported color scheme ['light', 'dark', 'purple']
   * App II: supported color scheme ['light', 'dark', 'orange']
   *
   * If you are one App I with color scheme 'purple', when open App II it should fallback
   * to default color scheme of App II because App II does not support 'purple'
   */
  describe('Unsupported color scheme', () => {
    const { CssVarsProvider } = createCssVarsProvider({
      theme: {
        colorSchemes: {
          light: {
            color: 'light',
          },
          dark: {
            color: 'dark',
          },
        },
      },
      defaultColorScheme: 'light',
    });
    const Color = () => {
      const theme = useTheme();
      return
{theme.vars.color}
;
    };
    it('use default color scheme if the storage value does not exist', () => {
      storage[DEFAULT_MODE_STORAGE_KEY] = 'unknown';

      render(
        <CssVarsProvider>
          <Color />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('color').textContent).to.equal('var(--color)');
    });
  });

  describe('[Application] Customization', () => {
    it('custom theme replace the default theme', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          fontSize: { md: '1rem', sm: null },
          colorSchemes: {
            light: {},
          },
        },
        defaultColorScheme: 'light',
      });
      const Text = ({ scale = 'md' }) => {
        const theme = useTheme();
        return <div data-testid={`text-${scale}`}>{theme.vars.fontSize[scale]}
;
      };
      render(
        <CssVarsProvider theme={{ fontSize: { sm: '0.75rem' } }}>
          <Text scale="md" />
          <Text scale="sm" />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('text-md').textContent).to.equal('');
      expect(screen.getByTestId('text-sm').textContent).to.equal('var(--fontSize-sm)');
    });

    it('merge custom colorSchemes', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: {
            light: {
              palette: {
                color: '#000000',
              },
            },
          },
        },
        defaultColorScheme: 'light',
      });
      const Swatch = () => {
        const theme = useTheme();
        return (

{theme.vars.palette.color}

{theme.palette.color}

        );
      };
      const comfortColor = '#007FFF';
      render(
        <CssVarsProvider
          defaultColorScheme="comfort"
          theme={{
            colorSchemes: {
              comfort: {
                palette: {
                  color: comfortColor,
                },
              },
            },
          }}
        >
          <Swatch />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('swatch-color').textContent).to.equal('var(--palette-color)');
      expect(screen.getByTestId('swatch-color-value').textContent).to.equal(comfortColor);
    });

    it('extend palette property in colorSchemes', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: {
            light: {
              palette: {
                color: '#000000',
              },
            },
          },
        },
        defaultColorScheme: 'light',
      });
      const Swatch = () => {
        const theme = useTheme();
        return (

{theme.vars.palette.color}

{theme.vars.palette.bgcolor}

        );
      };
      render(
        <CssVarsProvider
          theme={{ colorSchemes: { light: { palette: { color: '#000000', bgcolor: '#ffffff' } } } }}
        >
          <Swatch />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('swatch-color').textContent).to.equal('var(--palette-color)');
      expect(screen.getByTestId('swatch-bgcolor').textContent).to.equal('var(--palette-bgcolor)');
    });

    /**
     * `colorSchemes` are useful for creating toggle UI.
     * In some cases, developers might want to use the color defined in colorSchemes.
     */
    it('All `colorSchemes` is available in theme', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: {
            light: {},
            dark: {},
          },
        },
        defaultColorScheme: 'light',
      });
      const Consumer = () => {
        const theme = useTheme();
        return
{Object.keys(theme.colorSchemes).join(', ')}
;
      };
      const { container } = render(
        <CssVarsProvider theme={{ colorSchemes: { light: {}, dark: {}, dim: {} } }}>
          <Consumer />
        </CssVarsProvider>,
      );

      expect(container.firstChild.textContent).to.equal('light, dark, dim');
    });

    it('able to override css variable prefix', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: { fontSize: 16 } },
        },
        defaultColorScheme: 'light',
        prefix: 'mui',
      });
      const Text = () => {
        const theme = useTheme();
        return <div data-testid={`text`}>{theme.vars.fontSize}
;
      };
      render(
        <CssVarsProvider prefix="foo-bar">
          <Text />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('text').textContent).to.equal('var(--foo-bar-fontSize)');
    });

    it('does not take `theme.components` into account', () => {
      const { CssVarsProvider } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: { fontSize: 16 } },
          components: 'any',
        },
        defaultColorScheme: 'light',
      });
      const Text = () => {
        const theme = useTheme();

        return <div data-testid={`text`}>{theme.vars.components}
;
      };
      render(
        <CssVarsProvider>
          <Text />
        </CssVarsProvider>,
      );

      expect(screen.getByTestId('text').textContent).not.to.equal('var(--components)');
    });

    it('`defaultMode` is specified', () => {
      const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: {}, dark: {} },
        },
        defaultColorScheme: 'light',
      });
      const Text = () => {
        const { mode } = useColorScheme();
        return
{mode}
;
      };
      const { container } = render(
        <CssVarsProvider defaultMode="dark">
          <Text />
        </CssVarsProvider>,
      );
      expect(container.firstChild.textContent).to.equal('dark');
    });

    it('`defaultColorScheme` is specified as string', () => {
      const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: {} },
        },
        defaultColorScheme: 'light',
      });
      const Text = () => {
        const { colorScheme } = useColorScheme();
        return
{colorScheme}
;
      };
      const { container } = render(
        <CssVarsProvider theme={{ colorSchemes: { paper: {} } }} defaultColorScheme="paper">
          <Text />
        </CssVarsProvider>,
      );
      expect(container.firstChild.textContent).to.equal('paper');
    });

    it('`defaultColorScheme` is specified as object', () => {
      const { CssVarsProvider, useColorScheme } = createCssVarsProvider({
        theme: {
          colorSchemes: { light: {} },
        },
        defaultColorScheme: 'light',
      });
      const Text = () => {
        const { colorScheme } = useColorScheme();
        return
{colorScheme}
;
      };
      const { container } = render(
        <CssVarsProvider
          theme={{ colorSchemes: { paper: {} } }}
          defaultColorScheme={{ light: 'paper' }}
        >
          <Text />
        </CssVarsProvider>,
      );
      expect(container.firstChild.textContent).to.equal('paper');
    });
  });
});