text:
package org.apache.solr.cloud;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.SolrParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CloudInspectUtil {
  static Logger log = LoggerFactory.getLogger(CloudInspectUtil.class);

  /**
   * When a and b are known to be different, this method tells if the difference
   * is legal given the adds and deletes that failed from b.
   *
   * @param a first list of docs
   * @param b second list of docs
   * @param aName label for first list of docs
   * @param bName  label for second list of docs
   * @param bAddFails null or list of the ids of adds that failed for b
   * @param bDeleteFails null or list of the ids of deletes that failed for b
   * @return true if the difference in a and b is legal
   */
  public static boolean checkIfDiffIsLegal(SolrDocumentList a,
      SolrDocumentList b, String aName, String bName, Set<String> bAddFails,
      Set<String> bDeleteFails) {
    boolean legal = true;

    Set<Map> setA = new HashSet<>();
    for (SolrDocument sdoc : a) {
      setA.add(new HashMap(sdoc));
    }

    Set<Map> setB = new HashSet<>();
    for (SolrDocument sdoc : b) {
      setB.add(new HashMap(sdoc));
    }

    Set<Map> onlyInA = new HashSet<>(setA);
    onlyInA.removeAll(setB);
    Set<Map> onlyInB = new HashSet<>(setB);
    onlyInB.removeAll(setA);

    if (onlyInA.size() == 0 && onlyInB.size() == 0) {
      throw new IllegalArgumentException("No difference between list a and b");
    }

    System.err.println("###### Only in " + aName + ": " + onlyInA);
    System.err.println("###### Only in " + bName + ": " + onlyInB);

    for (Map doc : onlyInA) {
      if (bAddFails == null || !bAddFails.contains(doc.get("id"))) {
        legal = false;
        // System.err.println("###### Only in " + aName + ": " + doc.get("id"));
      } else {
        System.err.println("###### Only in " + aName + ": " + doc.get("id")
            + ", but this is expected because we found an add fail for "
            + doc.get("id"));
      }
    }

    for (Map doc : onlyInB) {
      if (bDeleteFails == null || !bDeleteFails.contains(doc.get("id"))) {
        legal = false;
        // System.err.println("###### Only in " + bName + ": " + doc.get("id"));
      } else {
        System.err.println("###### Only in " + bName + ": " + doc.get("id")
            + ", but this is expected because we found a delete fail for "
            + doc.get("id"));
      }
    }

    return legal;
  }

  /**
   * Shows the difference between two lists of documents.
   *
   * @param a the first list
   * @param b the second list
   * @param aName label for the first list
   * @param bName label for the second list
   * @return the documents only in list a
   */
  public static Set<Map> showDiff(SolrDocumentList a, SolrDocumentList b,
      String aName, String bName) {
    System.err.println("######" + aName + ": " + toStr(a, 10));
    System.err.println("######" + bName + ": " + toStr(b, 10));
    System.err.println("###### sizes=" + a.size() + "," + b.size());

    Set<Map> setA = new HashSet<>();
    for (SolrDocument sdoc : a) {
      setA.add(new HashMap(sdoc));
    }

    Set<Map> setB = new HashSet<>();
    for (SolrDocument sdoc : b) {
      setB.add(new HashMap(sdoc));
    }

    Set<Map> onlyInA = new HashSet<>(setA);
    onlyInA.removeAll(setB);
    Set<Map> onlyInB = new HashSet<>(setB);
    onlyInB.removeAll(setA);

    if (onlyInA.size() > 0) {
      System.err.println("###### Only in " + aName + ": " + onlyInA);
    }
    if (onlyInB.size() > 0) {
      System.err.println("###### Only in " + bName + ": " + onlyInB);
    }

    onlyInA.addAll(onlyInB);
    return onlyInA;
  }

  private static String toStr(SolrDocumentList lst, int maxSz) {
    if (lst.size() <= maxSz) return lst.toString();

    StringBuilder sb = new StringBuilder("SolrDocumentList[sz=" + lst.size());
    if (lst.size() != lst.getNumFound()) {
      sb.append(" numFound=" + lst.getNumFound());
    }
    sb.append("]=");
    sb.append(lst.subList(0, maxSz / 2).toString());
    sb.append(" , [...] , ");
    sb.append(lst.subList(lst.size() - maxSz / 2, lst.size()).toString());

    return sb.toString();
  }

  /**
   * Compares the results of the control and cloud clients.
   *
   * @return true if the compared results are illegal.
   */
  public static boolean compareResults(SolrServer controlServer, SolrServer cloudServer)
      throws SolrServerException {
    return compareResults(controlServer, cloudServer, null, null);
  }

  /**
   * Compares the results of the control and cloud clients.
   *
   * @return true if the compared results are illegal.
   */
  public static boolean compareResults(SolrServer controlServer, SolrServer cloudServer, Set<String> addFails, Set<String> deleteFails)
      throws SolrServerException {

    SolrParams q = SolrTestCaseJ4.params("q","*:*","rows","0", "tests","checkShardConsistency(vsControl)");    // add a tag to aid in debugging via logs

    SolrDocumentList controlDocList = controlServer.query(q).getResults();
    long controlDocs = controlDocList.getNumFound();

    SolrDocumentList cloudDocList = cloudServer.query(q).getResults();
    long cloudClientDocs = cloudDocList.getNumFound();

    // re-execute the query getting ids
    q = SolrTestCaseJ4.params("q","*:*","rows","100000", "fl","id", "tests","checkShardConsistency(vsControl)/getIds");    // add a tag to aid in debugging via logs
    controlDocList = controlServer.query(q).getResults();
    if (controlDocs != controlDocList.getNumFound()) {
      log.error("Something changed! control now " + controlDocList.getNumFound());
    };

    cloudDocList = cloudServer.query(q).getResults();
    if (cloudClientDocs != cloudDocList.getNumFound()) {
      log.error("Something changed! cloudClient now " + cloudDocList.getNumFound());
    };

    if (controlDocs != cloudClientDocs && (addFails != null || deleteFails != null)) {
      boolean legal = CloudInspectUtil.checkIfDiffIsLegal(controlDocList, cloudDocList,
          "controlDocList", "cloudDocList", addFails, deleteFails);
      if (legal) {
        return false;
      }
    }

    Set<Map> differences = CloudInspectUtil.showDiff(controlDocList, cloudDocList,
        "controlDocList", "cloudDocList");

    // get versions for the mismatched ids
    boolean foundId = false;
    StringBuilder ids = new StringBuilder("id:(");
    for (Map doc : differences) {
      ids.append(" "+doc.get("id"));
      foundId = true;
    }
    ids.append(")");

    if (foundId) {
      // get versions for those ids that don't match
      q = SolrTestCaseJ4.params("q", ids.toString(), "rows", "100000", "fl", "id,_version_",
          "sort", "id asc", "tests",
          "checkShardConsistency(vsControl)/getVers"); // add a tag to aid in
                                                       // debugging via logs

      SolrDocumentList a = controlServer.query(q).getResults();
      SolrDocumentList b = cloudServer.query(q).getResults();

      log.error("controlClient :" + a + "\n\tcloudClient :" + b);
    }

    return true;
  }
}


text:
require 'spec_helper'

RSpec.describe 'Vindax integration specs' do
  let(:client) { Cryptoexchange::Client.new }
  let(:bnb_eth_pair) { Cryptoexchange::Models::MarketPair.new(base: 'BNB', target: 'ETH', market: 'vindax') }

  it 'fetch pairs' do
    pairs = client.pairs('vindax')
    expect(pairs).not_to be_empty

    pair = pairs.first
    expect(pair.base).to_not be nil
    expect(pair.target).to_not be nil
    expect(pair.market).to eq 'vindax'
  end

  it 'give trade url' do
    trade_page_url = client.trade_page_url bnb_eth_pair.market, base: bnb_eth_pair.base, target: bnb_eth_pair.target
    expect(trade_page_url).to eq "https://vindax.com/exchange-base.html?symbol=BNB_ETH"
  end

  it 'fetch ticker' do
    ticker = client.ticker(bnb_eth_pair)

    expect(ticker.base).to eq 'BNB'
    expect(ticker.target).to eq 'ETH'
    expect(ticker.market).to eq 'vindax'
    expect(ticker.last).to be_a Numeric
    expect(ticker.bid).to be_a Numeric
    expect(ticker.ask).to be_a Numeric
    expect(ticker.low).to be_a Numeric
    expect(ticker.high).to be_a Numeric
    expect(ticker.volume).to be_a Numeric
    expect(ticker.timestamp).to be nil
    expect(ticker.payload).to_not be nil
  end

  it 'fetch order book' do
    order_book = client.order_book(bnb_eth_pair)

    expect(order_book.base).to eq 'BNB'
    expect(order_book.target).to eq 'ETH'
    expect(order_book.market).to eq 'vindax'
    expect(order_book.asks).to_not be_empty
    expect(order_book.bids).to_not be_empty
    expect(order_book.asks.first.price).to_not be_nil
    expect(order_book.bids.first.amount).to_not be_nil
    expect(order_book.bids.first.timestamp).to be_nil
    expect(order_book.asks.count).to be > 0
    expect(order_book.bids.count).to be > 0
    expect(order_book.timestamp).to be_a Numeric
    expect(2000..Date.today.year).to include(Time.at(order_book.timestamp).year)
    expect(order_book.payload).to_not be nil
  end
end

redpajama_set_name: RedPajamaGithub


text:
package nl.esciencecenter.neon.examples.colormap;

import javax.swing.JFrame;

import nl.esciencecenter.neon.NeonNewtWindow;

/**
 * Example implementation of the main class for an Neon application. This
 * example focuses on the colormap substructure, using generated Perlin noise as
 * a randomized dataset.
 *
 * @author Maarten van Meersbergen <m.van.meersbergen@esciencecenter.nl>
 *
 */
public class ColormapExample {
    // This static definition (singleton) of a settings class ensures that these
    // global settings are useable throughout the application. This settings
    // class reads from a file named "settings.properties" to allow default
    // settings to be changed by the user.
    private final static ColormapExampleSettings settings = ColormapExampleSettings.getInstance();

    // This is an implementation of a 'loose' interface window. This is done to
    // allow java swing components as user interface elements. It is in a
    // seperate window because of MacOSX limitations in the JOGL library.
    private static ColormapExampleInterfaceWindow examplePanel;

    // An example implementation of a GLEventlistener. These listeners are the
    // backbone of any OpenGL application, and provide the display cycle needed
    // for continuous updates of the screen.
    private static ColormapExampleGLEventListener exampleGLEventListener;

    // In this simple example, we only call the constructor. This is enough to
    // keep the program running, since the constructor will create new threads
    // for animation etc. Therefore, even though we do not use the new Object,
    // the program will not terminate.
    public static void main(String[] args) {
        new ColormapExample();
    }

    public ColormapExample() {
        // Create the Swing interface elements
        examplePanel = new ColormapExampleInterfaceWindow();

        // Create the custom GLEventListener
        exampleGLEventListener = new ColormapExampleGLEventListener();

        // Create the default Neon OpenGL window.
        new NeonNewtWindow(true, ColormapExampleInputHandler.getInstance(), exampleGLEventListener,
                settings.getDefaultScreenWidth(), settings.getDefaultScreenHeight(),
                "NeonExample - example Visualization Tool");

        // Create the interface frame
        final JFrame frame = new JFrame("- - - -");
        frame.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            // Override the close method to exit the program instead of the
            // default do-nothing.
            public void windowClosing(java.awt.event.WindowEvent arg0) {
                System.exit(0);
            }
        });

        // Set the interface size according to the settings.
        frame.setSize(settings.getInterfaceWidth(), settings.getInterfaceHeight());

        // Lock the interface size.
        frame.setResizable(false);

        // Do the addition of the interface panel with the swing (non)threading
        // model.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    frame.getContentPane().add(examplePanel);
                } catch (final Exception e) {
                    e.printStackTrace(System.err);
                    System.exit(1);
                }
            }
        });

        frame.setVisible(true);
    }
}


text:
<?php

namespace Oro\Component\Action\Tests\Unit\Action;

use Doctrine\Common\Collections\Collection;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;
use Oro\Bundle\OrganizationBundle\Entity\Organization;
use Oro\Bundle\TagBundle\Entity\Taggable;
use Oro\Bundle\TagBundle\Entity\TagManager;
use Oro\Bundle\TagBundle\Helper\TaggableHelper;
use Oro\Bundle\TagBundle\Workflow\Action\CopyTagging;
use Oro\Bundle\TagBundle\Workflow\Action\CopyTaggingToNewEntity;
use Oro\Component\Action\Action\ActionInterface;
use Oro\Component\Action\Exception\InvalidParameterException;
use Oro\Component\Action\Tests\Unit\Action\Stub\StubStorage;
use Oro\Component\ConfigExpression\ContextAccessor;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\PropertyAccess\PropertyPathInterface;

class CopyTaggingTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @var TagManager|\PHPUnit\Framework\MockObject\MockObject
     */
    private $tagManager;

    /**
     * @var TaggableHelper|\PHPUnit\Framework\MockObject\MockObject
     */
    private $taggableHelper;

    /**
     * @var CopyTaggingToNewEntity
     */
    private $action;

    protected function setUp()
    {
        $this->tagManager = $this->createMock(TagManager::class);
        $this->taggableHelper = $this->createMock(TaggableHelper::class);
        $this->doctrineHelper = $this->createMock(DoctrineHelper::class);

        $this->action = new CopyTagging(
            new ContextAccessor(),
            $this->tagManager,
            $this->taggableHelper
        );

        /** @var EventDispatcherInterface $dispatcher */
        $dispatcher = $this->createMock(EventDispatcherInterface::class);

        $this->action->setDispatcher($dispatcher);
    }

    public function testInitialize()
    {
        $options = [
            'source' => $this->createMock(PropertyPathInterface::class),
            'destination' => $this->createMock(PropertyPathInterface::class),
            'organization' => $this->createMock(PropertyPathInterface::class),
        ];

        $this->assertInstanceOf(
            ActionInterface::class,
            $this->action->initialize($options)
        );

        static::assertAttributeEquals($options, 'options', $this->action);
    }

    /**
     * @dataProvider initializeExceptionDataProvider
     *
     * @param array  $inputData
     * @param string $exception
     * @param string $exceptionMessage
     */
    public function testInitializeException(array $inputData, $exception, $exceptionMessage)
    {
        $this->expectException($exception);
        $this->expectExceptionMessage($exceptionMessage);

        $this->action->initialize($inputData);
    }

    /**
     * @return array
     */
    public function initializeExceptionDataProvider()
    {
        return [
            [
                'inputData' => ['source' => 1],
                'expectedException' => InvalidParameterException::class,
                'expectedExceptionMessage' => 'Source must be valid property definition',
            ],
            [
                'inputData' => [
                    'source' => $this->createMock(PropertyPathInterface::class),
                    'destination' => 1,
                ],
                'expectedException' => InvalidParameterException::class,
                'expectedExceptionMessage' => 'Destination must be valid property definition',
            ],
        ];
    }

    public function testExecuteMethod()
    {
        $source = $this->createMock(Taggable::class);
        $destination = $this->createMock(Taggable::class);
        $organization = $this->createMock(Organization::class);

        $data = new StubStorage([
            'source' => $source,
            'destination' => $destination,
            'organization' => $organization,
        ]);
        $options = [
            'source' => new PropertyPath('source'),
            'destination' => new PropertyPath('destination'),
            'organization' => new PropertyPath('organization'),
        ];

        $this->taggableHelper->expects(static::at(0))
            ->method('isTaggable')
            ->willReturn(true);

        $this->taggableHelper->expects(static::at(1))
            ->method('isTaggable')
            ->willReturn(true);

        $this->tagManager->expects(static::once())
            ->method('loadTagging')
            ->with($source, $organization);

        $tags = $this->createMock(Collection::class);

        $this->tagManager->expects(static::once())
            ->method('getTags')
            ->with($source)
            ->willReturn($tags);

        $this->tagManager->expects(static::once())
            ->method('setTags')
            ->with($destination, $tags);

        $this->tagManager->expects(static::once())
            ->method('saveTagging')
            ->with($destination, true, $organization);

        $this->action->initialize($options);
        $this->action->execute($data);
    }

    public function testExecuteMethodExceptionSource()
    {
        $this->expectException(
            \LogicException::class
        );
        $this->expectExceptionMessage(
            'Object in path "source" in "copy_tagging" action should be taggable.'
        );

        $inputData = [
            'source' => $this->createMock(Taggable::class),
        ];

        $this->taggableHelper->expects(static::once())
            ->method('isTaggable')
            ->willReturn(false);

        $data = new StubStorage($inputData);
        $options = [
            'source' => new PropertyPath('source'),
            'destination' => new PropertyPath('destination'),
            'organization' => new PropertyPath('organization'),
        ];

        $this->action->initialize($options);
        $this->action->execute($data);
    }

    public function testExecuteMethodExceptionDestination()
    {
        $this->expectException(
            \LogicException::class
        );
        $this->expectExceptionMessage(
            'Object in path "destination" in "copy_tagging" action should be taggable.'
        );

        $inputData = [
            'source' => $this->createMock(Taggable::class),
            'destination' => $this->createMock(Taggable::class),
        ];

        $this->taggableHelper->expects(static::at(0))
            ->method('isTaggable')
            ->willReturn(true);

        $this->taggableHelper->expects(static::at(1))
            ->method('isTaggable')
            ->willReturn(false);

        $data = new StubStorage($inputData);
        $options = [
            'source' => new PropertyPath('source'),
            'destination' => new PropertyPath('destination'),
            'organization' => new PropertyPath('organization'),
        ];

        $this->action->initialize($options);
        $this->action->execute($data);
    }
}


text:
import os, sys, imp, struct, marshal, time
from pysnmp.smi import error
from pysnmp import debug

if sys.version_info[0] <= 2:
    import types
    classTypes = (types.ClassType, type)
else:
    classTypes = (type,)

class __AbstractMibSource:
    def __init__(self, srcName):
        self._srcName = srcName
        self.__magic = imp.get_magic()
        self.__sfx = {}
        self.__inited = None
        for sfx, mode, typ in imp.get_suffixes():
            if typ not in self.__sfx:
                self.__sfx[typ] = []
            self.__sfx[typ].append((sfx, len(sfx), mode))
        debug.logger & debug.flagBld and debug.logger('trying %s' % self)

    def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, self._srcName)

    def _uniqNames(self, files):
        u = {}
        for f in files:
            if f[:9] == '__init__.':
                continue
            for typ in (imp.PY_SOURCE, imp.PY_COMPILED):
                for sfx, sfxLen, mode in self.__sfx[typ]:
                    if f[-sfxLen:] == sfx:
                        u[f[:-sfxLen]] = None
        return tuple(u.keys())

    # MibSource API follows

    def fullPath(self, f='', sfx=''):
        return self._srcName + (f and (os.sep + f + sfx) or '')

    def init(self):
        if self.__inited is None:
            self.__inited = self._init()
            if self.__inited is self:
                self.__inited = True
        if self.__inited is True:
            return self
        else:
            return self.__inited
    def listdir(self): return self._listdir()
    def read(self, f):
        for pycSfx, pycSfxLen, pycMode in self.__sfx[imp.PY_COMPILED]:
            try:
                pycData = self._getData(f + pycSfx, pycMode)
            except IOError:
                pycTime = -1
            else:
                if self.__magic == pycData[:4]:
                    pycData = pycData[4:]
                    pycTime = struct.unpack('<L', pycData[:4])[0]
                    pycData = pycData[4:]
                    break
                else:
                    debug.logger & debug.flagBld and debug.logger(
                        'bad magic in %s' % (f+pycSfx,)
                        )
                    pycTime = -1

        debug.logger & debug.flagBld and debug.logger(
            'file %s mtime %d' % (f+pycSfx, pycTime)
            )

        for pySfx, pySfxLen, pyMode in self.__sfx[imp.PY_SOURCE]:
            try:
                pyTime = self._getTimestamp(f+pySfx)
            except (IOError, OSError):
                pyTime = -1
            else:
                break

        debug.logger & debug.flagBld and debug.logger(
            'file %s mtime %d' % (f+pySfx, pyTime)
            )

        if pycTime != -1 and pycTime >= pyTime:
            return marshal.loads(pycData), pycSfx
        if pyTime != -1:
            return self._getData(f+pySfx, pyMode), pySfx

        raise IOError('No suitable module found')

class ZipMibSource(__AbstractMibSource):
    def _init(self):
        try:
            p = __import__(
                self._srcName, globals(), locals(), self._srcName.split('.')
                )
            if hasattr(p, '__loader__'):
                self.__loader = p.__loader__
                self._srcName = self._srcName.replace('.', os.sep)
                return self
            else:
                # Dir relative to PYTHONPATH
                return DirMibSource(os.path.split(p.__file__)[0]).init()
        except ImportError:
            # Dir relative to CWD
            return DirMibSource(self._srcName).init()

    def _parseDosTime(self, dosdate, dostime):
        t = ( ((dosdate >> 9) & 0x7f) + 1980, # year
              ((dosdate >> 5) & 0x0f),  # month
              dosdate & 0x1f, # mday
              (dostime >> 11) & 0x1f, # hour
              (dostime >> 5) & 0x3f, # min
              (dostime & 0x1f) * 2, # sec
              -1, # wday
              -1, # yday
              -1  ) # dst
        return time.mktime(t)

    def _listdir(self):
        l = []
        for f in self.__loader._files.keys():
            d, f = os.path.split(f)
            if d == self._srcName:
                l.append(f)
        return tuple(self._uniqNames(l))

    def _getTimestamp(self, f):
        p = os.path.join(self._srcName, f)
        if p in self.__loader._files:
            return self._parseDosTime(
                self.__loader._files[p][6],
                self.__loader._files[p][5]
                )
        else:
            raise IOError('No file in ZIP: %s' % p)

    def _getData(self, f, mode=None):
        return self.__loader.get_data(os.path.join(self._srcName, f))

class DirMibSource(__AbstractMibSource):
    def _init(self):
        self._srcName = os.path.normpath(self._srcName)
        return self

    def _listdir(self):
        try:
            return self._uniqNames(os.listdir(self._srcName))
        except OSError:
            return ()

    def _getTimestamp(self, f):
        return os.stat(os.path.join(self._srcName, f))[8]

    def _getData(self, f, mode):
        try:
            if f in os.listdir(self._srcName): # make FS case-sensitive
                return open(os.path.join(self._srcName, f), mode).read()
        except OSError:
            pass
        raise IOError  # pretend there's no such file

class MibBuilder:
    loadTexts = 0
    defaultCoreMibs = 'pysnmp.smi.mibs.instances:pysnmp.smi.mibs'
    defaultMiscMibs = 'pysnmp_mibs'
    moduleID = 'PYSNMP_MODULE_ID'
    def __init__(self):
        self.lastBuildId = self._autoName = 0
        sources = []
        for m in os.environ.get('PYSNMP_MIB_PKGS', self.defaultCoreMibs).split(':'):
            sources.append(ZipMibSource(m).init())
        # Compatibility variable
        if 'PYSNMP_MIB_DIR' in os.environ:
            os.environ['PYSNMP_MIB_DIRS'] = os.environ['PYSNMP_MIB_DIR']
        if 'PYSNMP_MIB_DIRS' in os.environ:
            for m in os.environ['PYSNMP_MIB_DIRS'].split(':'):
                sources.append(DirMibSource(m))
        if self.defaultMiscMibs:
            for m in self.defaultMiscMibs.split(':'):
                try:
                    sources.append(ZipMibSource(m))
                except ImportError:
                    pass
        self.mibSymbols = {}
        self.__modSeen = {}
        self.__modPathsSeen = {}
        self.setMibSources(*sources)

    # MIB modules management

    def setMibSources(self, *mibSources):
        self.__mibSources = [ s.init() for s in mibSources ]
        debug.logger & debug.flagBld and debug.logger('setMibPath: new MIB sources %s' % (self.__mibSources,))

    def getMibSources(self): return tuple(self.__mibSources)

    # Legacy/compatibility methods (won't work for .eggs)
    def setMibPath(self, *mibPaths):
        self.setMibSources(*[ DirMibSource(x) for x in mibPaths ])

    def getMibPath(self):
        paths = ()
        for mibSource in self.getMibSources():
            if isinstance(mibSource, DirMibSource):
                paths += ( mibSource.fullPath(), )
            else:
                raise error.SmiError(
                    'MIB source is not a plain directory: %s' % (mibSource,)
                    )
        return paths

    def loadModules(self, *modNames, **userCtx):
        # Build a list of available modules
        if not modNames:
            modNames = {}
            for mibSource in self.__mibSources:
                for modName in mibSource.listdir():
                    modNames[modName] = None
            modNames = list(modNames.keys())
        if not modNames:
            raise error.SmiError(
                'No MIB module to load at %s' % (self,)
                )

        for modName in modNames:
            for mibSource in self.__mibSources:
                debug.logger & debug.flagBld and debug.logger('loadModules: trying %s at %s' % (modName, mibSource))
                try:
                    modData, sfx = mibSource.read(modName)
                except IOError:
                    debug.logger & debug.flagBld and debug.logger('loadModules: read %s from %s failed: %s' % (modName, mibSource, sys.exc_info()[1]))
                    continue

                modPath = mibSource.fullPath(modName, sfx)

                if modPath in self.__modPathsSeen:
                    debug.logger & debug.flagBld and debug.logger('loadModules: seen %s' % modPath)
                    break
                else:
                    self.__modPathsSeen[modPath] = 1

                debug.logger & debug.flagBld and debug.logger('loadModules: evaluating %s' % modPath)

                g = { 'mibBuilder': self,
                      'userCtx': userCtx }

                try:
                    exec(modData, g)
                except Exception:
                    del self.__modPathsSeen[modPath]
                    raise error.SmiError(
                        'MIB module \"%s\" load error: %s' % (modPath, sys.exc_info()[1])
                        )

                self.__modSeen[modName] = modPath

                debug.logger & debug.flagBld and debug.logger('loadModules: loaded %s' % modPath)

                break

            if modName not in self.__modSeen:
                raise error.SmiError(
                    'MIB file \"%s\" not found in search path' % (modName and modName + ".py[co]")
                    )

        return self

    def unloadModules(self, *modNames):
        if not modNames:
            modNames = list(self.mibSymbols.keys())
        for modName in modNames:
            if modName not in self.mibSymbols:
                raise error.SmiError(
                    'No module %s at %s' % (modName, self)
                    )
            self.unexportSymbols(modName)
            del self.__modPathsSeen[self.__modSeen[modName]]
            del self.__modSeen[modName]

            debug.logger & debug.flagBld and debug.logger('unloadModules: ' % (modName))

        return self

    def importSymbols(self, modName, *symNames, **userCtx):
        if not modName:
            raise error.SmiError(
                'importSymbols: empty MIB module name'
            )
        r = ()
        for symName in symNames:
            if modName not in self.mibSymbols:
                self.loadModules(modName, **userCtx)
            if modName not in self.mibSymbols:
                raise error.SmiError(
                    'No module %s loaded at %s' % (modName, self)
                    )
            if symName not in self.mibSymbols[modName]:
                raise error.SmiError(
                    'No symbol %s::%s at %s' % (modName, symName, self)
                    )
            r = r + (self.mibSymbols[modName][symName],)
        return r

    def exportSymbols(self, modName, *anonymousSyms, **namedSyms):
        if modName not in self.mibSymbols:
            self.mibSymbols[modName] = {}
        mibSymbols = self.mibSymbols[modName]

        for symObj in anonymousSyms:
            debug.logger & debug.flagBld and debug.logger('exportSymbols: anonymous symbol %s::__pysnmp_%ld'  % (modName, self._autoName))
            mibSymbols['__pysnmp_%ld' % self._autoName] = symObj
            self._autoName = self._autoName + 1
        for symName, symObj in namedSyms.items():
            if symName in mibSymbols:
                raise error.SmiError(
                    'Symbol %s already exported at %s' % (symName, modName)
                    )

            if symName != self.moduleID and \
                   not isinstance(symObj, classTypes):
                label = symObj.getLabel()
                if label:
                    symName = label
                else:
                    symObj.setLabel(symName)

            mibSymbols[symName] = symObj

            debug.logger & debug.flagBld and debug.logger('exportSymbols: symbol %s::%s' % (modName, symName))

        self.lastBuildId = self.lastBuildId + 1

    def unexportSymbols(self, modName, *symNames):
        if modName not in self.mibSymbols:
            raise error.SmiError(
                'No module %s at %s' % (modName, self)
                )
        mibSymbols = self.mibSymbols[modName]
        if not symNames:
            symNames = list(mibSymbols.keys())
        for symName in symNames:
            if symName not in mibSymbols:
                raise error.SmiError(
                    'No symbol %s::%s at %s' % (modName, symName, self)
                    )
            del mibSymbols[symName]

            debug.logger & debug.flagBld and debug.logger('unexportSymbols: symbol %s::%s' % (modName, symName))

        if not self.mibSymbols[modName]:
            del self.mibSymbols[modName]

        self.lastBuildId = self.lastBuildId + 1


text:
"""
pircel.protocol
---------------

This module defines functions and objects for interacting with an IRC server including:
    - parsing IRC protocol messages received from the server
    - generating IRC protocol messages to be sent back to the server
    - a callback-based API for interacting with these that should be agnostic to the multiprocessing mechanism used
      (e.g. it'll work with both asyncio and tornado if you set them up right; though twisted won't work at the moment
      because it doesn't support python 3)
"""
import logging

import chardet

import pircel
import pircel.signals

logger = logging.getLogger(__name__)

verbatim_logger = logging.getLogger('{}.verbatim'.format(__name__))
signal_factory = pircel.signals.namespace('irc_protocol')

class Error(pircel.Error):
    """ Root exception for protocol parsing errors. """

class UnknownNumericCommandError(Error):
    """ Exception thrown when a numeric command is given but no symbolic version can be found. """

class UnknownModeCommandError(Error):
    """ Exception thrown on unknown mode change command. """

def split_irc_line(s):
    """Breaks a message from an IRC server into its prefix, command, and arguments.

    Copied straight from twisted, license and copyright for this function follows:
    Copyright (c) 2001-2014
    Allen Short
    Andy Gayton
    Andrew Bennetts
    Antoine Pitrou
    Apple Computer, Inc.
    Ashwini Oruganti
    Benjamin Bruheim
    Bob Ippolito
    Canonical Limited
    Christopher Armstrong
    David Reid
    Donovan Preston
    Eric Mangold
    Eyal Lotem
    Google Inc.
    Hybrid Logic Ltd.
    Hynek Schlawack
    Itamar Turner-Trauring
    James Knight
    Jason A. Mobarak
    Jean-Paul Calderone
    Jessica McKellar
    Jonathan Jacobs
    Jonathan Lange
    Jonathan D. Simms
    Jürgen Hermann
    Julian Berman
    Kevin Horn
    Kevin Turner
    Laurens Van Houtven
    Mary Gardiner
    Matthew Lefkowitz
    Massachusetts Institute of Technology
    Moshe Zadka
    Paul Swartz
    Pavel Pergamenshchik
    Ralph Meijer
    Richard Wall
    Sean Riley
    Software Freedom Conservancy
    Travis B. Hartwell
    Thijs Triemstra
    Thomas Herve
    Timothy Allen
    Tom Prince

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
    documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
    rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
    permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
    Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
    WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
    OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
    OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    """
    prefix = ''
    trailing = []
    if not s:
        # Raise an exception of some kind
        pass
    if s[0] == ':':
        prefix, s = s[1:].split(' ', 1)
    if s.find(' :') != -1:
        s, trailing = s.split(' :', 1)
        args = s.split()
        args.append(trailing)
    else:
        args = s.split()
    command = args.pop(0)
    return prefix, command, args

def parse_identity(who):
    """ Extract the parts out of an IRC user identifier string. """
    nick, rest = who.split('!')
    username, host = rest.split('@')

    if username.startswith('~'):
        username = username[1:]

    return nick, username, host

def get_symbolic_command(command):
    """ Normalizes both numeric and symbolic commands into just symbolic commands. """
    if command.isdecimal():
        try:
            return numeric_to_symbolic[command]
        except KeyError as e:
            raise UnknownNumericCommandError("No numeric command found: '{}'".format(command)) from e
    else:
        return command

def decode(line):
    """ Attempts to decode the line with utf8 but falls back to chardet otherwise. """
    try:
        line = str(line, encoding='utf8')
    except UnicodeDecodeError:
        logger.debug('UTF8 decode failed, bytes: %s', line)
        encoding = chardet.detect(line)['encoding']
        logger.debug('Tried autodetecting and got %s, decoding now', encoding)
        line = str(line, encoding=encoding)
    except TypeError as e:
        if e.args[0] != 'decoding str is not supported':
            raise
    return line

def parse_line(line):
    """ Normalizes the line from the server and splits it into component parts. """
    line = decode(line)
    line = line.strip()
    return split_irc_line(line)

class IRCServerHandler:
    def __init__(self, identity):
        """ Protocol parser (and response generator) for an IRC server.

        Args:
            identity (User object): "Our" nick and user name etc.
        """
        self._write = None
        self.identity = identity

        # Default values
        self.motd = ''

    @property
    def _user_string(self):
        return ':{}!~{}@localhost'.format(self.identity.nick, self.identity.username)

    # =========================================================================
    # Parsing and "reading"
    # ---------------------
    #
    # Methods that result from a new input from the IRC server.
    # =========================================================================
    def handle_line(self, line):
        verbatim_logger.debug(line)
        # Parse the line
        prefix, command, args = parse_line(line)

        try:
            symbolic_command = get_symbolic_command(command)
        except UnknownNumericCommandError:
            self.log_unhandled(line)
            return

        # local callbacks deal with the protocol stuff
        try:
            handler_name = 'on_{}'.format(symbolic_command.lower())
            handler = getattr(self, handler_name)
        except AttributeError:
            handled = False
        else:
            handler(prefix, *args)
            handled = True

        # user callbacks do whatever they want them to do
        signal = signal_factory(symbolic_command.lower())
        signal.send(self, prefix=prefix, args=args)
        if signal.receivers:
            handled = True

        if not handled:
            self.log_unhandled(line)

    def log_unhandled(self, line):
        """ Called when we encounter a command we either don't know or don't have a handler for.

        Method rather than function because I might later make it send debug logging over IRC sometimes.
        """
        logger.warning('Unhandled: %s', line.decode().rstrip())
    # =========================================================================

    # =========================================================================
    # Generating and "writing"
    # ------------------------
    #
    # Methods that ultimately call self._write or are used in other methods in
    # this section.
    #
    # TODO: Should public API functions like `who` and `connect` be in here? Is
    #       this an appropriate description for this section?
    # =========================================================================
    @property  # Why is this a property?
    def write_function(self):
        return self._write

    @write_function.setter
    def write_function(self, new_write_function):
        self._write = new_write_function

    def pong(self, value):
        self._write('PONG :{}'.format(value))

    def connect(self):
        self._write('NICK {}'.format(self.identity.nick))
        self._write('USER {} 0 * :{}'.format(self.identity.username, self.identity.realname))

    def who(self, mask):
        self._write('WHO {}'.format(mask))

    def join(self, channel, password=None):
        logger.debug('Joining %s', channel)
        if password:
            self._write('JOIN {} {}'.format(channel, password))
        else:
            self._write('JOIN {}'.format(channel))

    def part(self, channel):
        self._write('PART {}'.format(channel))

    def quit(self, message):
        self._write('QUIT :{}'.format(message))

    def _split_line_channel_command(self, command, channel, message):
        if not isinstance(message, (str, bytes)):
            message = str(message)
        for line in message.split('\n'):
            command = '{} {} :{}'.format(command, channel, line)
            self._write(command)
            self.handle_line('{} {}'.format(self._user_string, command))

    def send_message(self, channel, message):
        self._split_line_channel_command('PRIVMSG', channel, message)

    def send_notice(self, channel, message):
        self._split_line_channel_command('NOTICE', channel, message)

    def send_ping(self, value):
        self._write('PING {}'.format(value))

    def change_nick(self, new_nick):
        self._write('NICK {}'.format(new_nick))
        self.identity.nick = new_nick
    # =========================================================================

    # =========================================================================
    # Callback API
    # ------------
    #
    # The primary intended mechanism for interacting with this module, a user
    # will instantiate this class then add callbacks where they want.
    #
    # A callback is any old callable, details in the docstring for
    # `add_callback`.
    # =========================================================================
    def add_callback(self, signal, callback, weak=True):
        """ Attach a function to be called on an IRC command (specified symbolically).

        The function will be called with the following args:
            * The calling IRCServerHandler object
            * The prefix of the command (usually who it's from?)
            * The remaining arguments from the command

        For example the `join` signal will be called with `(self, who, channel)`.
        """
        signal_factory(signal).connect(callback, sender=self, weak=weak)

    def remove_callback(self, signal, callback):
        signal_factory(signal).disconnect(callback, sender=self)
    # =========================================================================

    # =========================================================================
    # Default handlers
    # ----------------
    #
    # So far just ping responding. In future might handle protocol negotiation
    # bits like character encoding and the like.
    # =========================================================================
    def on_ping(self, prefix, token, *args):
        logger.debug('Ping received: %s, %s', prefix, token)
        self.pong(token)
    # =========================================================================

symbolic_to_numeric = {
    "RPL_WELCOME": '001',
    "RPL_YOURHOST": '002',
    "RPL_CREATED": '003',
    "RPL_MYINFO": '004',
    "RPL_ISUPPORT": '005',
    "RPL_BOUNCE": '010',
    "RPL_STATSCONN": '250',
    "RPL_LOCALUSERS": '265',
    "RPL_GLOBALUSERS": '266',
    "RPL_USERHOST": '302',
    "RPL_ISON": '303',
    "RPL_AWAY": '301',
    "RPL_UNAWAY": '305',
    "RPL_NOWAWAY": '306',
    "RPL_WHOISUSER": '311',
    "RPL_WHOISSERVER": '312',
    "RPL_WHOISOPERATOR": '313',
    "RPL_WHOISIDLE": '317',
    "RPL_ENDOFWHOIS": '318',
    "RPL_WHOISCHANNELS": '319',
    "RPL_WHOWASUSER": '314',
    "RPL_ENDOFWHOWAS": '369',
    "RPL_LISTSTART": '321',
    "RPL_LIST": '322',
    "RPL_LISTEND": '323',
    "RPL_UNIQOPIS": '325',
    "RPL_CHANNELMODEIS": '324',
    "RPL_NOTOPIC": '331',
    "RPL_TOPIC": '332',
    "RPL_TOPICWHOTIME": '333',
    "RPL_INVITING": '341',
    "RPL_SUMMONING": '342',
    "RPL_INVITELIST": '346',
    "RPL_ENDOFINVITELIST": '347',
    "RPL_EXCEPTLIST": '348',
    "RPL_ENDOFEXCEPTLIST": '349',
    "RPL_VERSION": '351',
    "RPL_WHOREPLY": '352',
    "RPL_ENDOFWHO": '315',
    "RPL_NAMREPLY": '353',
    "RPL_ENDOFNAMES": '366',
    "RPL_LINKS": '364',
    "RPL_ENDOFLINKS": '365',
    "RPL_BANLIST": '367',
    "RPL_ENDOFBANLIST": '368',
    "RPL_INFO": '371',
    "RPL_ENDOFINFO": '374',
    "RPL_MOTDSTART": '375',
    "RPL_MOTD": '372',
    "RPL_ENDOFMOTD": '376',
    "RPL_YOUREOPER": '381',
    "RPL_REHASHING": '382',
    "RPL_YOURESERVICE": '383',
    "RPL_TIME": '391',
    "RPL_USERSSTART": '392',
    "RPL_USERS": '393',
    "RPL_ENDOFUSERS": '394',
    "RPL_NOUSERS": '395',
    "RPL_TRACELINK": '200',
    "RPL_TRACECONNECTING": '201',
    "RPL_TRACEHANDSHAKE": '202',
    "RPL_TRACEUNKNOWN": '203',
    "RPL_TRACEOPERATOR": '204',
    "RPL_TRACEUSER": '205',
    "RPL_TRACESERVER": '206',
    "RPL_TRACESERVICE": '207',
    "RPL_TRACENEWTYPE": '208',
    "RPL_TRACECLASS": '209',
    "RPL_TRACERECONNECT": '210',
    "RPL_TRACELOG": '261',
    "RPL_TRACEEND": '262',
    "RPL_STATSLINKINFO": '211',
    "RPL_STATSCOMMANDS": '212',
    "RPL_ENDOFSTATS": '219',
    "RPL_STATSUPTIME": '242',
    "RPL_STATSOLINE": '243',
    "RPL_UMODEIS": '221',
    "RPL_SERVLIST": '234',
    "RPL_SERVLISTEND": '235',
    "RPL_LUSERCLIENT": '251',
    "RPL_LUSEROP": '252',
    "RPL_LUSERUNKNOWN": '253',
    "RPL_LUSERCHANNELS": '254',
    "RPL_LUSERME": '255',
    "RPL_ADMINME": '256',
    "RPL_ADMINLOC": '257',
    "RPL_ADMINLOC": '258',
    "RPL_ADMINEMAIL": '259',
    "RPL_TRYAGAIN": '263',
    "ERR_NOSUCHNICK": '401',
    "ERR_NOSUCHSERVER": '402',
    "ERR_NOSUCHCHANNEL": '403',
    "ERR_CANNOTSENDTOCHAN": '404',
    "ERR_TOOMANYCHANNELS": '405',
    "ERR_WASNOSUCHNICK": '406',
    "ERR_TOOMANYTARGETS": '407',
    "ERR_NOSUCHSERVICE": '408',
    "ERR_NOORIGIN": '409',
    "ERR_NORECIPIENT": '411',
    "ERR_NOTEXTTOSEND": '412',
    "ERR_NOTOPLEVEL": '413',
    "ERR_WILDTOPLEVEL": '414',
    "ERR_BADMASK": '415',
    "ERR_UNKNOWNCOMMAND": '421',
    "ERR_NOMOTD": '422',
    "ERR_NOADMININFO": '423',
    "ERR_FILEERROR": '424',
    "ERR_NONICKNAMEGIVEN": '431',
    "ERR_ERRONEUSNICKNAME": '432',
    "ERR_NICKNAMEINUSE": '433',
    "ERR_NICKCOLLISION": '436',
    "ERR_UNAVAILRESOURCE": '437',
    "ERR_USERNOTINCHANNEL": '441',
    "ERR_NOTONCHANNEL": '442',
    "ERR_USERONCHANNEL": '443',
    "ERR_NOLOGIN": '444',
    "ERR_SUMMONDISABLED": '445',
    "ERR_USERSDISABLED": '446',
    "ERR_NOTREGISTERED": '451',
    "ERR_NEEDMOREPARAMS": '461',
    "ERR_ALREADYREGISTRED": '462',
    "ERR_NOPERMFORHOST": '463',
    "ERR_PASSWDMISMATCH": '464',
    "ERR_YOUREBANNEDCREEP": '465',
    "ERR_YOUWILLBEBANNED": '466',
    "ERR_KEYSET": '467',
    "ERR_CHANNELISFULL": '471',
    "ERR_UNKNOWNMODE": '472',
    "ERR_INVITEONLYCHAN": '473',
    "ERR_BANNEDFROMCHAN": '474',
    "ERR_BADCHANNELKEY": '475',
    "ERR_BADCHANMASK": '476',
    "ERR_NOCHANMODES": '477',
    "ERR_BANLISTFULL": '478',
    "ERR_NOPRIVILEGES": '481',
    "ERR_CHANOPRIVSNEEDED": '482',
    "ERR_CANTKILLSERVER": '483',
    "ERR_RESTRICTED": '484',
    "ERR_UNIQOPPRIVSNEEDED": '485',
    "ERR_NOOPERHOST": '491',
    "ERR_NOSERVICEHOST": '492',
    "ERR_UMODEUNKNOWNFLAG": '501',
    "ERR_USERSDONTMATCH": '502',
}
numeric_to_symbolic = {v: k for k, v in symbolic_to_numeric.items()}


text:
/******************************************************************************
 *
 * Module Name: aslpredef - support for ACPI predefined names
 *
 *****************************************************************************/

/*
 * Copyright (C) 2000 - 2013, Intel Corp.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 * 3. Neither the names of the above-listed copyright holders nor the names
 *    of any contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * Alternatively, this software may be distributed under the terms of the
 * GNU General Public License ("GPL") version 2 as published by the Free
 * Software Foundation.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 */

#define ACPI_CREATE_PREDEFINED_TABLE
#define ACPI_CREATE_RESOURCE_TABLE

#include <contrib/dev/acpica/compiler/aslcompiler.h>
#include "aslcompiler.y.h"
#include <contrib/dev/acpica/include/acpredef.h>
#include <contrib/dev/acpica/include/acnamesp.h>

#define _COMPONENT          ACPI_COMPILER
        ACPI_MODULE_NAME    ("aslpredef")

/* Local prototypes */

static void
ApCheckForUnexpectedReturnValue (
    ACPI_PARSE_OBJECT       *Op,
    ASL_METHOD_INFO         *MethodInfo);

static UINT32
ApCheckForSpecialName (
    ACPI_PARSE_OBJECT       *Op,
    char                    *Name);

/*******************************************************************************
 *
 * FUNCTION:    ApCheckForPredefinedMethod
 *
 * PARAMETERS:  Op              - A parse node of type "METHOD".
 *              MethodInfo      - Saved info about this method
 *
 * RETURN:      None
 *
 * DESCRIPTION: If method is a predefined name, check that the number of
 *              arguments and the return type (returns a value or not)
 *              is correct.
 *
 ******************************************************************************/

BOOLEAN
ApCheckForPredefinedMethod (
    ACPI_PARSE_OBJECT       *Op,
    ASL_METHOD_INFO         *MethodInfo)
{
    UINT32                      Index;
    UINT32                      RequiredArgCount;
    const ACPI_PREDEFINED_INFO  *ThisName;

    /* Check for a match against the predefined name list */

    Index = ApCheckForPredefinedName (Op, Op->Asl.NameSeg);

    switch (Index)
    {
    case ACPI_NOT_RESERVED_NAME:        /* No underscore or _Txx or _xxx name not matched */
    case ACPI_PREDEFINED_NAME:          /* Resource Name or reserved scope name */
    case ACPI_COMPILER_RESERVED_NAME:   /* A _Txx that was not emitted by compiler */

        /* Just return, nothing to do */
        return (FALSE);

    case ACPI_EVENT_RESERVED_NAME:      /* _Lxx/_Exx/_Wxx/_Qxx methods */

        Gbl_ReservedMethods++;

        /* NumArguments must be zero for all _Lxx/_Exx/_Wxx/_Qxx methods */

        if (MethodInfo->NumArguments != 0)
        {
            sprintf (MsgBuffer, "%s requires %u", Op->Asl.ExternalName, 0);

            AslError (ASL_WARNING, ASL_MSG_RESERVED_ARG_COUNT_HI, Op,
                MsgBuffer);
        }
        break;

    default:
        /*
         * Matched a predefined method name - validate the ASL-defined
         * argument count against the ACPI specification.
         *
         * Some methods are allowed to have a "minimum" number of args
         * (_SCP) because their definition in ACPI has changed over time.
         */
        Gbl_ReservedMethods++;
        ThisName = &AcpiGbl_PredefinedMethods[Index];
        RequiredArgCount = METHOD_GET_ARG_COUNT (ThisName->Info.ArgumentList);

        if (MethodInfo->NumArguments != RequiredArgCount)
        {
            sprintf (MsgBuffer, "%4.4s requires %u",
                ThisName->Info.Name, RequiredArgCount);

            if (MethodInfo->NumArguments < RequiredArgCount)
            {
                AslError (ASL_WARNING, ASL_MSG_RESERVED_ARG_COUNT_LO, Op,
                    MsgBuffer);
            }
            else if ((MethodInfo->NumArguments > RequiredArgCount) &&
                !(ThisName->Info.ArgumentList & ARG_COUNT_IS_MINIMUM))
            {
                AslError (ASL_WARNING, ASL_MSG_RESERVED_ARG_COUNT_HI, Op,
                    MsgBuffer);
            }
        }

        /*
         * Check if method returns no value, but the predefined name is
         * required to return a value
         */
        if (MethodInfo->NumReturnNoValue &&
            ThisName->Info.ExpectedBtypes)
        {
            AcpiUtGetExpectedReturnTypes (StringBuffer,
                ThisName->Info.ExpectedBtypes);

            sprintf (MsgBuffer, "%s required for %4.4s",
                StringBuffer, ThisName->Info.Name);

            AslError (ASL_WARNING, ASL_MSG_RESERVED_RETURN_VALUE, Op,
                MsgBuffer);
        }
        break;
    }

    return (TRUE);
}

/*******************************************************************************
 *
 * FUNCTION:    ApCheckForUnexpectedReturnValue
 *
 * PARAMETERS:  Op              - A parse node of type "RETURN".
 *              MethodInfo      - Saved info about this method
 *
 * RETURN:      None
 *
 * DESCRIPTION: Check for an unexpected return value from a predefined method.
 *              Invoked for predefined methods that are defined to not return
 *              any value. If there is a return value, issue a remark, since
 *              the ASL writer may be confused as to the method definition
 *              and/or functionality.
 *
 * Note: We ignore all return values of "Zero", since this is what a standalone
 *       Return() statement will always generate -- so we ignore it here --
 *       i.e., there is no difference between Return() and Return(Zero).
 *       Also, a null Return() will be disassembled to return(Zero) -- so, we
 *       don't want to generate extraneous remarks/warnings for a disassembled
 *       ASL file.
 *
 ******************************************************************************/

static void
ApCheckForUnexpectedReturnValue (
    ACPI_PARSE_OBJECT       *Op,
    ASL_METHOD_INFO         *MethodInfo)
{
    ACPI_PARSE_OBJECT       *ReturnValueOp;

    /* Ignore Return() and Return(Zero) (they are the same) */

    ReturnValueOp = Op->Asl.Child;
    if (ReturnValueOp->Asl.ParseOpcode == PARSEOP_ZERO)
    {
        return;
    }

    /* We have a valid return value, but the reserved name did not expect it */

    AslError (ASL_WARNING, ASL_MSG_RESERVED_NO_RETURN_VAL,
        Op, MethodInfo->Op->Asl.ExternalName);
}

/*******************************************************************************
 *
 * FUNCTION:    ApCheckPredefinedReturnValue
 *
 * PARAMETERS:  Op              - A parse node of type "RETURN".
 *              MethodInfo      - Saved info about this method
 *
 * RETURN:      None
 *
 * DESCRIPTION: If method is a predefined name, attempt to validate the return
 *              value. Only "static" types can be validated - a simple return
 *              of an integer/string/buffer/package or a named reference to
 *              a static object. Values such as a Localx or Argx or a control
 *              method invocation are not checked. Issue a warning if there is
 *              a valid return value, but the reserved method defines no
 *              return value.
 *
 ******************************************************************************/

void
ApCheckPredefinedReturnValue (
    ACPI_PARSE_OBJECT       *Op,
    ASL_METHOD_INFO         *MethodInfo)
{
    UINT32                      Index;
    ACPI_PARSE_OBJECT           *ReturnValueOp;
    const ACPI_PREDEFINED_INFO  *ThisName;

    /* Check parent method for a match against the predefined name list */

    Index = ApCheckForPredefinedName (MethodInfo->Op,
                MethodInfo->Op->Asl.NameSeg);

    switch (Index)
    {
    case ACPI_EVENT_RESERVED_NAME:      /* _Lxx/_Exx/_Wxx/_Qxx methods */

        /* No return value expected, warn if there is one */

        ApCheckForUnexpectedReturnValue (Op, MethodInfo);
        return;

    case ACPI_NOT_RESERVED_NAME:        /* No underscore or _Txx or _xxx name not matched */
    case ACPI_PREDEFINED_NAME:          /* Resource Name or reserved scope name */
    case ACPI_COMPILER_RESERVED_NAME:   /* A _Txx that was not emitted by compiler */

        /* Just return, nothing to do */
        return;

    default: /* A standard predefined ACPI name */

        ThisName = &AcpiGbl_PredefinedMethods[Index];
        if (!ThisName->Info.ExpectedBtypes)
        {
            /* No return value expected, warn if there is one */

            ApCheckForUnexpectedReturnValue (Op, MethodInfo);
            return;
        }

        /* Get the object returned, it is the next argument */

        ReturnValueOp = Op->Asl.Child;
        switch (ReturnValueOp->Asl.ParseOpcode)
        {
        case PARSEOP_ZERO:
        case PARSEOP_ONE:
        case PARSEOP_ONES:
        case PARSEOP_INTEGER:
        case PARSEOP_STRING_LITERAL:
        case PARSEOP_BUFFER:
        case PARSEOP_PACKAGE:

            /* Static data return object - check against expected type */

            ApCheckObjectType (ThisName->Info.Name, ReturnValueOp,
                ThisName->Info.ExpectedBtypes, ACPI_NOT_PACKAGE_ELEMENT);

            /* For packages, check the individual package elements */

            if (ReturnValueOp->Asl.ParseOpcode == PARSEOP_PACKAGE)
            {
                ApCheckPackage (ReturnValueOp, ThisName);
            }
            break;

        default:
            /*
             * All other ops are very difficult or impossible to typecheck at
             * compile time. These include all Localx, Argx, and method
             * invocations. Also, NAMESEG and NAMESTRING because the type of
             * any named object can be changed at runtime (for example,
             * CopyObject will change the type of the target object.)
             */
            break;
        }
    }
}

/*******************************************************************************
 *
 * FUNCTION:    ApCheckForPredefinedObject
 *
 * PARAMETERS:  Op              - A parse node
 *              Name            - The ACPI name to be checked
 *
 * RETURN:      None
 *
 * DESCRIPTION: Check for a predefined name for a static object (created via
 *              the ASL Name operator). If it is a predefined ACPI name, ensure
 *              that the name does not require any arguments (which would
 *              require a control method implemenation of the name), and that
 *              the type of the object is one of the expected types for the
 *              predefined name.
 *
 ******************************************************************************/

void
ApCheckForPredefinedObject (
    ACPI_PARSE_OBJECT       *Op,
    char                    *Name)
{
    UINT32                      Index;
    ACPI_PARSE_OBJECT           *ObjectOp;
    const ACPI_PREDEFINED_INFO  *ThisName;

    /*
     * Check for a real predefined name -- not a resource descriptor name
     * or a predefined scope name
     */
    Index = ApCheckForPredefinedName (Op, Name);

    switch (Index)
    {
    case ACPI_NOT_RESERVED_NAME:        /* No underscore or _Txx or _xxx name not matched */
    case ACPI_PREDEFINED_NAME:          /* Resource Name or reserved scope name */
    case ACPI_COMPILER_RESERVED_NAME:   /* A _Txx that was not emitted by compiler */

        /* Nothing to do */
        return;

    case ACPI_EVENT_RESERVED_NAME:      /* _Lxx/_Exx/_Wxx/_Qxx methods */

        /*
         * These names must be control methods, by definition in ACPI spec.
         * Also because they are defined to return no value. None of them
         * require any arguments.
         */
        AslError (ASL_ERROR, ASL_MSG_RESERVED_METHOD, Op,
            "with zero arguments");
        return;

    default:

        break;
    }

    /* A standard predefined ACPI name */

    /*
     * If this predefined name requires input arguments, then
     * it must be implemented as a control method
     */
    ThisName = &AcpiGbl_PredefinedMethods[Index];
    if (METHOD_GET_ARG_COUNT (ThisName->Info.ArgumentList) > 0)
    {
        AslError (ASL_ERROR, ASL_MSG_RESERVED_METHOD, Op,
            "with arguments");
        return;
    }

    /*
     * If no return value is expected from this predefined name, then
     * it follows that it must be implemented as a control method
     * (with zero args, because the args > 0 case was handled above)
     * Examples are: _DIS, _INI, _IRC, _OFF, _ON, _PSx
     */
    if (!ThisName->Info.ExpectedBtypes)
    {
        AslError (ASL_ERROR, ASL_MSG_RESERVED_METHOD, Op,
            "with zero arguments");
        return;
    }

    /* Typecheck the actual object, it is the next argument */

    ObjectOp = Op->Asl.Child->Asl.Next;
    ApCheckObjectType (ThisName->Info.Name, Op->Asl.Child->Asl.Next,
        ThisName->Info.ExpectedBtypes, ACPI_NOT_PACKAGE_ELEMENT);

    /* For packages, check the individual package elements */

    if (ObjectOp->Asl.ParseOpcode == PARSEOP_PACKAGE)
    {
        ApCheckPackage (ObjectOp, ThisName);
    }
}

/*******************************************************************************
 *
 * FUNCTION:    ApCheckForPredefinedName
 *
 * PARAMETERS:  Op              - A parse node
 *              Name            - NameSeg to check
 *
 * RETURN:      None
 *
 * DESCRIPTION: Check a NameSeg against the reserved list.
 *
 ******************************************************************************/

UINT32
ApCheckForPredefinedName (
    ACPI_PARSE_OBJECT       *Op,
    char                    *Name)
{
    UINT32                      i;
    const ACPI_PREDEFINED_INFO  *ThisName;

    if (Name[0] == 0)
    {
        AcpiOsPrintf ("Found a null name, external = %s\n",
            Op->Asl.ExternalName);
    }

    /* All reserved names are prefixed with a single underscore */

    if (Name[0] != '_')
    {
        return (ACPI_NOT_RESERVED_NAME);
    }

    /* Check for a standard predefined method name */

    ThisName = AcpiGbl_PredefinedMethods;
    for (i = 0; ThisName->Info.Name[0]; i++)
    {
        if (ACPI_COMPARE_NAME (Name, ThisName->Info.Name))
        {
            /* Return index into predefined array */
            return (i);
        }

        ThisName++; /* Does not account for extra package data, but is OK */
    }

    /* Check for resource names and predefined scope names */

    ThisName = AcpiGbl_ResourceNames;
    while (ThisName->Info.Name[0])
    {
        if (ACPI_COMPARE_NAME (Name, ThisName->Info.Name))
        {
            return (ACPI_PREDEFINED_NAME);
        }

        ThisName++;
    }

    ThisName = AcpiGbl_ScopeNames;
    while (ThisName->Info.Name[0])
    {
        if (ACPI_COMPARE_NAME (Name, ThisName->Info.Name))
        {
            return (ACPI_PREDEFINED_NAME);
        }

        ThisName++;
    }

    /* Check for _Lxx/_Exx/_Wxx/_Qxx/_T_x. Warning if unknown predefined name */

    return (ApCheckForSpecialName (Op, Name));
}

/*******************************************************************************
 *
 * FUNCTION:    ApCheckForSpecialName
 *
 * PARAMETERS:  Op              - A parse node
 *              Name            - NameSeg to check
 *
 * RETURN:      None
 *
 * DESCRIPTION: Check for the "special" predefined names -
 *              _Lxx, _Exx, _Qxx, _Wxx, and _T_x
 *
 ******************************************************************************/

static UINT32
ApCheckForSpecialName (
    ACPI_PARSE_OBJECT       *Op,
    char                    *Name)
{

    /*
     * Check for the "special" predefined names. We already know that the
     * first character is an underscore.
     *   GPE:  _Lxx
     *   GPE:  _Exx
     *   GPE:  _Wxx
     *   EC:   _Qxx
     */
    if ((Name[1] == 'L') ||
        (Name[1] == 'E') ||
        (Name[1] == 'W') ||
        (Name[1] == 'Q'))
    {
        /* The next two characters must be hex digits */

        if ((isxdigit ((int) Name[2])) &&
            (isxdigit ((int) Name[3])))
        {
            return (ACPI_EVENT_RESERVED_NAME);
        }
    }

    /* Check for the names reserved for the compiler itself: _T_x */

    else if ((Op->Asl.ExternalName[1] == 'T') &&
             (Op->Asl.ExternalName[2] == '_'))
    {
        /* Ignore if actually emitted by the compiler */

        if (Op->Asl.CompileFlags & NODE_COMPILER_EMITTED)
        {
            return (ACPI_NOT_RESERVED_NAME);
        }

        /*
         * Was not actually emitted by the compiler. This is a special case,
         * however. If the ASL code being compiled was the result of a
         * dissasembly, it may possibly contain valid compiler-emitted names
         * of the form "_T_x". We don't want to issue an error or even a
         * warning and force the user to manually change the names. So, we
         * will issue a remark instead.
         */
        AslError (ASL_REMARK, ASL_MSG_COMPILER_RESERVED, Op, Op->Asl.ExternalName);
        return (ACPI_COMPILER_RESERVED_NAME);
    }

    /*
     * The name didn't match any of the known predefined names. Flag it as a
     * warning, since the entire namespace starting with an underscore is
     * reserved by the ACPI spec.
     */
    AslError (ASL_WARNING, ASL_MSG_UNKNOWN_RESERVED_NAME, Op,
        Op->Asl.ExternalName);

    return (ACPI_NOT_RESERVED_NAME);
}

/*******************************************************************************
 *
 * FUNCTION:    ApCheckObjectType
 *
 * PARAMETERS:  PredefinedName  - Name of the predefined object we are checking
 *              Op              - Current parse node
 *              ExpectedBtypes  - Bitmap of expected return type(s)
 *              PackageIndex    - Index of object within parent package (if
 *                                applicable - ACPI_NOT_PACKAGE_ELEMENT
 *                                otherwise)
 *
 * RETURN:      None
 *
 * DESCRIPTION: Check if the object type is one of the types that is expected
 *              by the predefined name. Only a limited number of object types
 *              can be returned by the predefined names.
 *
 ******************************************************************************/

ACPI_STATUS
ApCheckObjectType (
    const char              *PredefinedName,
    ACPI_PARSE_OBJECT       *Op,
    UINT32                  ExpectedBtypes,
    UINT32                  PackageIndex)
{
    UINT32                  ReturnBtype;
    char                    *TypeName;

    if (!Op)
    {
        return (AE_TYPE);
    }

    /* Map the parse opcode to a bitmapped return type (RTYPE) */

    switch (Op->Asl.ParseOpcode)
    {
    case PARSEOP_ZERO:
    case PARSEOP_ONE:
    case PARSEOP_ONES:
    case PARSEOP_INTEGER:

        ReturnBtype = ACPI_RTYPE_INTEGER;
        TypeName = "Integer";
        break;

    case PARSEOP_STRING_LITERAL:

        ReturnBtype = ACPI_RTYPE_STRING;
        TypeName = "String";
        break;

    case PARSEOP_BUFFER:

        ReturnBtype = ACPI_RTYPE_BUFFER;
        TypeName = "Buffer";
        break;

    case PARSEOP_PACKAGE:
    case PARSEOP_VAR_PACKAGE:

        ReturnBtype = ACPI_RTYPE_PACKAGE;
        TypeName = "Package";
        break;

    case PARSEOP_NAMESEG:
    case PARSEOP_NAMESTRING:
        /*
         * Ignore any named references within a package object.
         *
         * For Package objects, references are allowed instead of any of the
         * standard data types (Integer/String/Buffer/Package). These
         * references are resolved at runtime. NAMESEG and NAMESTRING are
         * impossible to typecheck at compile time because the type of
         * any named object can be changed at runtime (for example,
         * CopyObject will change the type of the target object).
         */
        if (PackageIndex != ACPI_NOT_PACKAGE_ELEMENT)
        {
            return (AE_OK);
        }

        ReturnBtype = ACPI_RTYPE_REFERENCE;
        TypeName = "Reference";
        break;

    default:

        /* Not one of the supported object types */

        TypeName = UtGetOpName (Op->Asl.ParseOpcode);
        goto TypeErrorExit;
    }

    /* Exit if the object is one of the expected types */

    if (ReturnBtype & ExpectedBtypes)
    {
        return (AE_OK);
    }

TypeErrorExit:

    /* Format the expected types and emit an error message */

    AcpiUtGetExpectedReturnTypes (StringBuffer, ExpectedBtypes);

    if (PackageIndex == ACPI_NOT_PACKAGE_ELEMENT)
    {
        sprintf (MsgBuffer, "%4.4s: found %s, %s required",
            PredefinedName, TypeName, StringBuffer);
    }
    else
    {
        sprintf (MsgBuffer, "%4.4s: found %s at index %u, %s required",
            PredefinedName, TypeName, PackageIndex, StringBuffer);
    }

    AslError (ASL_ERROR, ASL_MSG_RESERVED_OPERAND_TYPE, Op, MsgBuffer);
    return (AE_TYPE);
}

/*******************************************************************************
 *
 * FUNCTION:    ApDisplayReservedNames
 *
 * PARAMETERS:  None
 *
 * RETURN:      None
 *
 * DESCRIPTION: Dump information about the ACPI predefined names and predefined
 *              resource descriptor names.
 *
 ******************************************************************************/

void
ApDisplayReservedNames (
    void)
{
    const ACPI_PREDEFINED_INFO  *ThisName;
    UINT32                      Count;
    UINT32                      NumTypes;

    /*
     * Predefined names/methods
     */
    printf ("\nPredefined Name Information\n\n");

    Count = 0;
    ThisName = AcpiGbl_PredefinedMethods;
    while (ThisName->Info.Name[0])
    {
        AcpiUtDisplayPredefinedMethod (MsgBuffer, ThisName, FALSE);
        Count++;
        ThisName = AcpiUtGetNextPredefinedMethod (ThisName);
    }

    printf ("%u Predefined Names are recognized\n", Count);

    /*
     * Resource Descriptor names
     */
    printf ("\nPredefined Names for Resource Descriptor Fields\n\n");

    Count = 0;
    ThisName = AcpiGbl_ResourceNames;
    while (ThisName->Info.Name[0])
    {
        NumTypes = AcpiUtGetResourceBitWidth (MsgBuffer,
            ThisName->Info.ArgumentList);

        printf ("%4.4s    Field is %s bits wide%s\n",
            ThisName->Info.Name, MsgBuffer,
            (NumTypes > 1) ? " (depending on descriptor type)" : "");

        Count++;
        ThisName++;
    }

    printf ("%u Resource Descriptor Field Names are recognized\n", Count);

    /*
     * Predefined scope names
     */
    printf ("\nPredefined Scope/Device Names (automatically created at root)\n\n");

    ThisName = AcpiGbl_ScopeNames;
    while (ThisName->Info.Name[0])
    {
        printf ("%4.4s    Scope/Device\n", ThisName->Info.Name);
        ThisName++;
    }
}


text:
if (self.importScripts) {
  importScripts('../resources/fetch-test-helpers.js');
  importScripts('/streams/resources/rs-utils.js');
}

function isLocked(stream) {
  try {
    var reader = stream.getReader();
    reader.releaseLock();
    return false;
  } catch(e) {
    return true;
  }
}

promise_test(function(test) {
    return fetch('/fetch/resources/doctype.html')
      .then(function(response) {
          // Accessing the body property makes the stream start working.
          var stream = response.body;
          return response.text();
        })
      .then(function(text) {
          assert_equals(text, '<!DOCTYPE html>\n');
        })
    }, 'FetchTextAfterAccessingStreamTest');

promise_test(function(test) {
    var actual = '';
    return fetch('/fetch/resources/doctype.html')
      .then(function(response) {
          r = response;
          return readableStreamToArray(response.body);
        })
      .then(function(chunks) {
          var decoder = new TextDecoder();
          for (var chunk of chunks) {
            actual += decoder.decode(chunk, {stream: true});
          }
          // Put an empty buffer without the stream option to end decoding.
          actual += decoder.decode(new Uint8Array(0));
          assert_equals(actual, '<!DOCTYPE html>\n');
        })
    }, 'FetchStreamTest');

promise_test(function(test) {
    return fetch('/fetch/resources/progressive.php')
      .then(function(response) {
          var p1 = response.text();
          // Because progressive.php takes some time to load, we expect
          // response.text() is not yet completed here.
          var p2 = response.text().then(function() {
              return Promise.reject(new Error('resolved unexpectedly'));
            }, function(e) {
              return e;
            });
          return Promise.all([p1, p2]);
        })
      .then(function(results) {
          assert_equals(results[0].length, 190);
          assert_equals(results[1].name, 'TypeError');
        })
    }, 'FetchTwiceTest');

promise_test(function(test) {
    var response;
    return fetch('/fetch/resources/doctype.html')
      .then(function(res) {
          response = res;
          assert_false(response.bodyUsed);
          var p = response.arrayBuffer();
          assert_true(response.bodyUsed);
          assert_true(isLocked(response.body));
          return p;
        })
      .then(function(b) {
          assert_true(isLocked(response.body));
          assert_equals(b.byteLength, 16);
        })
    }, 'ArrayBufferTest');

promise_test(function(test) {
    var response;
    return fetch('/fetch/resources/doctype.html')
      .then(function(res) {
          response = res;
          assert_false(response.bodyUsed);
          var p = response.blob();
          assert_true(response.bodyUsed);
          assert_true(isLocked(response.body));
          return p;
        })
      .then(function(blob) {
          assert_true(isLocked(response.body));
          assert_equals(blob.size, 16);
          assert_equals(blob.type, 'text/html');
        })
    }, 'BlobTest');

promise_test(function(test) {
    var response;
    return fetch('/fetch/resources/doctype.html')
      .then(function(res) {
          response = res;
          assert_false(response.bodyUsed);
          var p = response.json();
          assert_true(response.bodyUsed);
          assert_true(isLocked(response.body));
          return p;
        })
      .then(
        test.unreached_func('json() must fail'),
        function(e) {
          assert_true(isLocked(response.body));
          assert_equals(e.name, 'SyntaxError', 'expected JSON error');
        })
    }, 'JSONFailedTest');

promise_test(function(test) {
    var response;
    return fetch('/fetch/resources/simple.json')
      .then(function(res) {
          response = res;
          assert_false(response.bodyUsed);
          var p = response.json();
          assert_true(response.bodyUsed);
          assert_true(isLocked(response.body));
          return p;
        })
      .then(function(json) {
          assert_true(isLocked(response.body));
          assert_equals(json['a'], 1);
          assert_equals(json['b'], 2);
        })
    }, 'JSONTest');

promise_test(function(test) {
    var response;
    return fetch('/fetch/resources/doctype.html')
      .then(function(res) {
          response = res;
          assert_false(response.bodyUsed);
          var p = response.text();
          assert_true(response.bodyUsed);
          assert_true(isLocked(response.body));
          return p;
        })
      .then(function(text) {
          assert_true(isLocked(response.body));
          assert_equals(text, '<!DOCTYPE html>\n');
        })
    }, 'TextTest');

promise_test(function(test) {
    return fetch('/fetch/resources/non-ascii.txt')
      .then(function(response) {
          assert_false(response.bodyUsed);
          var p = response.text();
          assert_true(response.bodyUsed);
          return p;
        })
      .then(function(text) {
          assert_equals(text, '\u4e2d\u6587 Gem\u00fcse\n');
        })
    }, 'NonAsciiTextTest');

promise_test(function(test) {
    return fetch('/fetch/resources/bom-utf-8.php')
      .then(function(response) { return response.text(); })
      .then(function(text) {
          assert_equals(text, '\u4e09\u6751\u304b\u306a\u5b50',
                        'utf-8 string with BOM is decoded as utf-8 and ' +
                        'BOM is not included in the decoded result.');
        })
    }, 'BOMUTF8Test');

promise_test(function(test) {
    return fetch('/fetch/resources/bom-utf-16le.php')
      .then(function(response) { return response.text(); })
      .then(function(text) {
          assert_equals(text, '\ufffd\ufffd\tNQgK0j0P[',
                        'utf-16le string is decoded as if utf-8 ' +
                        'even if the data has utf-16le BOM.');
        })
    }, 'BOMUTF16LETest');

promise_test(function(test) {
    return fetch('/fetch/resources/bom-utf-16be.php')
      .then(function(response) { return response.text(); })
      .then(function(text) {
          assert_equals(text, '\ufffd\ufffdN\tgQ0K0j[P',
                        'utf-16be string is decoded as if utf-8 ' +
                        'even if the data has utf-16be BOM.');
        })
    }, 'BOMUTF16BETest');

test(t => {
    var req = new Request('/');
    assert_false(req.bodyUsed);
    req.text();
    assert_false(req.bodyUsed);
  }, 'BodyUsedShouldNotBeSetForNullBody');

test(t => {
    var req = new Request('/', {method: 'POST', body: ''});
    assert_false(req.bodyUsed);
    req.text();
    assert_true(req.bodyUsed);
  }, 'BodyUsedShouldBeSetForEmptyBody');

test(t => {
    var res = new Response('');
    assert_false(res.bodyUsed);
    var reader = res.body.getReader();
    assert_false(res.bodyUsed);
    reader.read();
    assert_true(res.bodyUsed);
  }, 'BodyUsedShouldBeSetWhenRead');

test(t => {
    var res = new Response('');
    assert_false(res.bodyUsed);
    var reader = res.body.getReader();
    assert_false(res.bodyUsed);
    reader.cancel();
    assert_true(res.bodyUsed);
  }, 'BodyUsedShouldBeSetWhenCancelled');

promise_test(t => {
    var res = new Response('');
    res.body.cancel();
    return res.arrayBuffer().then(unreached_fulfillment(t), e => {
        assert_equals(e.name, 'TypeError');
      });
  }, 'Used => arrayBuffer');

promise_test(t => {
    var res = new Response('');
    res.body.cancel();
    return res.blob().then(unreached_fulfillment(t), e => {
        assert_equals(e.name, 'TypeError');
      });
  }, 'Used => blob');

promise_test(t => {
    var res = new Response('');
    res.body.cancel();
    return res.json().then(unreached_fulfillment(t), e => {
        assert_equals(e.name, 'TypeError');
      });
  }, 'Used => json');

promise_test(t => {
    var res = new Response('');
    res.body.cancel();
    return res.text().then(unreached_fulfillment(t), e => {
        assert_equals(e.name, 'TypeError');
      });
  }, 'Used => text');

promise_test(t => {
    var res = new Response('');
    const reader = res.body.getReader();
    return res.arrayBuffer().then(unreached_fulfillment(t), e => {
        // TODO(yhirano): Use finally when it's available. Ditto below.
        reader.releaseLock();
        assert_equals(e.name, 'TypeError');
      });
  }, 'Locked => arrayBuffer');

promise_test(t => {
    var res = new Response('');
    const reader = res.body.getReader();
    return res.blob().then(unreached_fulfillment(t), e => {
        reader.releaseLock();
        assert_equals(e.name, 'TypeError');
      });
  }, 'Locked => blob');

promise_test(t => {
    var res = new Response('');
    const reader = res.body.getReader();
    return res.json().then(unreached_fulfillment(t), e => {
        reader.releaseLock();
        assert_equals(e.name, 'TypeError');
      });
  }, 'Locked => json');

promise_test(t => {
    var res = new Response('');
    const reader = res.body.getReader();
    return res.text().then(unreached_fulfillment(t), e => {
        reader.releaseLock();
        assert_equals(e.name, 'TypeError');
      });
  }, 'Locked => text');

done();


text:
var frameModule = require("ui/frame");
function navigate(navigationContext) {
    var topmost = frameModule.topmost();
    topmost.navigate(navigationContext);
}
exports.navigate = navigate;
function navigateWitouthHistory(navigationContext) {
    this.navigate(navigationContext);
}
exports.navigateWitouthHistory = navigateWitouthHistory;
function goBack() {
    var topmost = frameModule.topmost();
    topmost.goBack();
}
exports.goBack = goBack;


text:
use std::collections::{BTreeMap, HashMap};

use anyhow::{Context, Result};
use pueue_lib::task::Task;
use rstest::rstest;
use serde_derive::Deserialize;

use crate::fixtures::*;
use crate::helper::*;

/// Test that the `log` command works for both:
/// - The log being streamed by the daemon.
/// - The log being read from the local files.
#[rstest]
#[case(true)]
#[case(false)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn read(#[case] read_local_logs: bool) -> Result<()> {
    let mut daemon = daemon().await?;
    let shared = &daemon.settings.shared;

    // Force the client to read remote logs via config file.
    daemon.settings.client.read_local_logs = read_local_logs;
    // Persist the change, so it can be seen by the client.
    daemon
        .settings
        .save(&Some(daemon.tempdir.path().join("pueue.yml")))
        .context("Couldn't write pueue config to temporary directory")?;

    // Add a task and wait until it finishes.
    assert_success(add_task(shared, "echo test", false).await?);
    wait_for_task_condition(shared, 0, |task| task.is_done()).await?;

    let output = run_client_command(shared, &["log"])?;

    let context = get_task_context(&daemon.settings).await?;
    assert_stdout_matches("log__default", output.stdout, context)?;

    Ok(())
}

/// Test that the `log` command properly truncates content and hints this to the user for:
/// - The log being streamed by the daemon.
/// - The log being read from the local files.
#[rstest]
#[case(true)]
#[case(false)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn read_truncated(#[case] read_local_logs: bool) -> Result<()> {
    let mut daemon = daemon().await?;
    let shared = &daemon.settings.shared;

    // Force the client to read remote logs via config file.
    daemon.settings.client.read_local_logs = read_local_logs;
    // Persist the change, so it can be seen by the client.
    daemon
        .settings
        .save(&Some(daemon.tempdir.path().join("pueue.yml")))
        .context("Couldn't write pueue config to temporary directory")?;

    // Add a task and wait until it finishes.
    assert_success(add_task(shared, "echo '1\n2\n3\n4\n5\n6\n7\n8\n9\n10'", false).await?);
    wait_for_task_condition(shared, 0, |task| task.is_done()).await?;

    let output = run_client_command(shared, &["log", "--lines=5"])?;

    let context = get_task_context(&daemon.settings).await?;
    assert_stdout_matches("log__last_lines", output.stdout, context)?;

    Ok(())
}

/// If a task has a label, it is included in the log output
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn task_with_label() -> Result<()> {
    let daemon = daemon().await?;
    let shared = &daemon.settings.shared;

    // Add a task and wait until it finishes.
    run_client_command(shared, &["add", "--label", "test_label", "echo test"])?;
    wait_for_task_condition(shared, 0, |task| task.is_done()).await?;

    let output = run_client_command(shared, &["log"])?;

    let context = get_task_context(&daemon.settings).await?;
    assert_stdout_matches("log__with_label", output.stdout, context)?;

    Ok(())
}

/// Calling `log` with the `--color=always` flag, colors the output as expected.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn colored() -> Result<()> {
    let daemon = daemon().await?;
    let shared = &daemon.settings.shared;

    // Add a task and wait until it finishes.
    assert_success(add_task(shared, "echo test", false).await?);
    wait_for_task_condition(shared, 0, |task| task.is_done()).await?;

    let output = run_client_command(shared, &["--color", "always", "log"])?;

    let context = get_task_context(&daemon.settings).await?;
    assert_stdout_matches("log__colored", output.stdout, context)?;

    Ok(())
}

/// This is the output struct used for task logs.
/// Since the Pueue client isn't exposed as a library, we have to declare our own for testing
/// purposes. The counter part can be found in `client/display/log/json.rs`.
#[derive(Debug, Deserialize)]
pub struct TaskLog {
    pub task: Task,
    pub output: String,
}

/// Calling `pueue log --json` prints the expected json output to stdout.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn json() -> Result<()> {
    let daemon = daemon().await?;
    let shared = &daemon.settings.shared;

    // Add a task and wait until it finishes.
    assert_success(add_task(shared, "echo test", false).await?);
    wait_for_task_condition(shared, 0, |task| task.is_done()).await?;

    let output = run_client_command(shared, &["log", "--json"])?;

    // Deserialize the json back to the original task BTreeMap.
    let json = String::from_utf8_lossy(&output.stdout);
    let mut task_logs: BTreeMap<usize, TaskLog> = serde_json::from_str(&*json)
        .context(format!("Failed to deserialize json tasks: \n{json}"))?;

    // Get the actual BTreeMap from the daemon
    let mut state = get_state(shared).await?;
    let original_task = state.tasks.get_mut(&0).unwrap();
    // Clean the environment variables, as they aren't transmitted when calling `log`.
    original_task.envs = HashMap::new();

    let task_log = task_logs.get_mut(&0).expect("Expected one task log");
    assert_eq!(
        original_task, &task_log.task,
        "Deserialized task and original task aren't equal"
    );

    // Append a newline to the deserialized task's output, which is automatically done when working
    // with the shell.
    task_log.output.push('\n');

    assert_stdout_matches("log__json", task_log.output.clone().into(), HashMap::new())?;

    Ok(())
}


text:
package com.jvjsoftware.inst.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;

import com.btg.dao.entidad.Entidad;

@Entity
public class Provincia implements Entidad {

	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="provincia_p_id_seq")
    @SequenceGenerator(name="provincia_p_id_seq", sequenceName="provincia_p_id_seq", allocationSize=1)
	@Column(name= "p_id")
	private Integer id;

	@ManyToOne
	@JoinColumn(name = "p_departamento_id")
	private Departamento departamento;

	private String p_descripcion;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Departamento getDepartamento() {
		return departamento;
	}

	public void setDepartamento(Departamento departamento) {
		this.departamento = departamento;
	}

	public String getP_descripcion() {
		return p_descripcion;
	}

	public void setP_descripcion(String p_descripcion) {
		this.p_descripcion = p_descripcion;
	}

	@Override
	public String getLabel() {
		// TODO Auto-generated method stub
		return null;
	}
}


text:
using System.Collections.Generic;
using Xunit;

namespace System.Globalization.Tests
{
    public class DateTimeFormatInfoCalendarWeekRule
    {
        public static IEnumerable<object[]> CalendarWeekRule_TestData()
        {
            yield return new object[] { DateTimeFormatInfo.InvariantInfo, CalendarWeekRule.FirstDay };
            yield return new object[] { new CultureInfo("en-US").DateTimeFormat, CalendarWeekRule.FirstDay };
            yield return new object[] { new CultureInfo("br-FR").DateTimeFormat, DateTimeFormatInfoData.BrFRCalendarWeekRule() };
        }

        [Theory]
        [MemberData(nameof(CalendarWeekRule_TestData))]
        public void CalendarWeekRuleTest(DateTimeFormatInfo format, CalendarWeekRule expected)
        {
            Assert.Equal(expected, format.CalendarWeekRule);
        }

        [Theory]
        [InlineData(CalendarWeekRule.FirstDay)]
        [InlineData(CalendarWeekRule.FirstFourDayWeek)]
        [InlineData(CalendarWeekRule.FirstFullWeek)]
        public void CalendarWeekRule_Set(CalendarWeekRule newCalendarWeekRule)
        {
            var format = new DateTimeFormatInfo();
            format.CalendarWeekRule = newCalendarWeekRule;
            Assert.Equal(newCalendarWeekRule, format.CalendarWeekRule);
        }

        [Theory]
        [InlineData(CalendarWeekRule.FirstDay - 1)]
        [InlineData(CalendarWeekRule.FirstFourDayWeek + 1)]
        public void CalendarWeekRule_Set_Invalid_ThrowsArgumentOutOfRangeException(CalendarWeekRule value)
        {
            Assert.Throws<ArgumentOutOfRangeException>("value", () => new DateTimeFormatInfo().CalendarWeekRule = value);
        }

        [Fact]
        public void CalendarWeekRule_Set_ReadOnly_ThrowsInvalidOperationException()
        {
            Assert.Throws<InvalidOperationException>(() => DateTimeFormatInfo.InvariantInfo.CalendarWeekRule = CalendarWeekRule.FirstDay); // DateTimeFormatInfo.InvariantInfo is read only
        }
    }
}


text:
/**
 * Create and manage task JSON Object
 *
 * @param details - JSON object used to overwrite the default values
 * @constructor
 */

var Task = function (details) {

    this.processInstanceId;
    this.sort;

    Object.assign(this, details);
};
module.exports = Task;


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.btnDisplay = New System.Windows.Forms.Button()
        Me.btnClear = New System.Windows.Forms.Button()
        Me.btnExit = New System.Windows.Forms.Button()
        Me.txtGreeting = New System.Windows.Forms.TextBox()
        Me.SuspendLayout()
        '
        'btnDisplay
        '
        Me.btnDisplay.Location = New System.Drawing.Point(12, 179)
        Me.btnDisplay.Name = "btnDisplay"
        Me.btnDisplay.Size = New System.Drawing.Size(75, 23)
        Me.btnDisplay.TabIndex = 0
        Me.btnDisplay.Text = "Display"
        Me.btnDisplay.UseVisualStyleBackColor = True
        '
        'btnClear
        '
        Me.btnClear.Location = New System.Drawing.Point(376, 179)
        Me.btnClear.Name = "btnClear"
        Me.btnClear.Size = New System.Drawing.Size(75, 23)
        Me.btnClear.TabIndex = 1
        Me.btnClear.Text = "Clear"
        Me.btnClear.UseVisualStyleBackColor = True
        '
        'btnExit
        '
        Me.btnExit.Location = New System.Drawing.Point(376, 12)
        Me.btnExit.Name = "btnExit"
        Me.btnExit.Size = New System.Drawing.Size(75, 23)
        Me.btnExit.TabIndex = 2
        Me.btnExit.Text = "Exit"
        Me.btnExit.UseVisualStyleBackColor = True
        '
        'txtGreeting
        '
        Me.txtGreeting.Font = New System.Drawing.Font("Times New Roman", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txtGreeting.Location = New System.Drawing.Point(12, 70)
        Me.txtGreeting.Name = "txtGreeting"
        Me.txtGreeting.Size = New System.Drawing.Size(439, 26)
        Me.txtGreeting.TabIndex = 3
        Me.txtGreeting.Text = "Hello Everybody"
        '
        'Form1
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(463, 214)
        Me.Controls.Add(Me.txtGreeting)
        Me.Controls.Add(Me.btnExit)
        Me.Controls.Add(Me.btnClear)
        Me.Controls.Add(Me.btnDisplay)
        Me.Name = "Form1"
        Me.Text = "Hello"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents btnDisplay As System.Windows.Forms.Button
    Friend WithEvents btnClear As System.Windows.Forms.Button
    Friend WithEvents btnExit As System.Windows.Forms.Button
    Friend WithEvents txtGreeting As System.Windows.Forms.TextBox

End Class


text:
module LBT
	# Holds +Step+ subclasses and allows a magic constructor to be used
	#
	# For +Fetcher+, +Verifier+, etc...
	#
	# Subclasses will automagically have a magic constructor.
	#
	# A subclass will be implemented as such:
	#
	#   class Foobarer < LBT::StepsFabricator
	#       class BazBar < LBT::Step
	#           def initialize fizz
	#               @fizz = fizz
	#           end
	#           def run
	#               # Do whatever
	#               puts @fizz
	#           end
	#       end
	#   end
	#
	# And used as such:
	#
	#   library.foobarer = Foobarer::BazBar("buzz")
	# or
	#   library.foobarer = Foobarer::BazBar "buzz"
	#
	# The magic constructor will call +BazBar.new()+.
	#
	# This is not your idiomatic Ruby, but is used to make a DSL.
	#
	# @see Step Step for more informations about Steps.
	class StepsFabricator

		# Implements the magic constructor
		#
		# @return [LBT::Step] Instance of step according to the name used.
		def self.method_missing(method, *args)
			unless self.constants.include? method
				raise "#{self.name}::#{method} not found."
			end
			self.const_get(method).new(*args)
		end
	end
end