text:
.. _benchmarking:

============
Benchmarking
============

.. versionadded:: 0.17

Scrapy comes with a simple benchmarking suite that spawns a local HTTP server
and crawls it at the maximum possible speed. The goal of this benchmarking is
to get an idea of how Scrapy performs in your hardware, in order to have a
common baseline for comparisons. It uses a simple spider that does nothing and
just follows links.

To run it use::

    scrapy bench

You should see an output like this::

    2016-12-16 21:18:48 [scrapy.utils.log] INFO: Scrapy 1.2.2 started (bot: quotesbot)
    2016-12-16 21:18:48 [scrapy.utils.log] INFO: Overridden settings: {'CLOSESPIDER_TIMEOUT': 10, 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['quotesbot.spiders'], 'LOGSTATS_INTERVAL': 1, 'BOT_NAME': 'quotesbot', 'LOG_LEVEL': 'INFO', 'NEWSPIDER_MODULE': 'quotesbot.spiders'}
    2016-12-16 21:18:49 [scrapy.middleware] INFO: Enabled extensions:
    ['scrapy.extensions.closespider.CloseSpider',
     'scrapy.extensions.logstats.LogStats',
     'scrapy.extensions.telnet.TelnetConsole',
     'scrapy.extensions.corestats.CoreStats']
    2016-12-16 21:18:49 [scrapy.middleware] INFO: Enabled downloader middlewares:
    ['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
     'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
     'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
     'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
     'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
     'scrapy.downloadermiddlewares.retry.RetryMiddleware',
     'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
     'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
     'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
     'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
     'scrapy.downloadermiddlewares.stats.DownloaderStats']
    2016-12-16 21:18:49 [scrapy.middleware] INFO: Enabled spider middlewares:
    ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
     'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
     'scrapy.spidermiddlewares.referer.RefererMiddleware',
     'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
     'scrapy.spidermiddlewares.depth.DepthMiddleware']
    2016-12-16 21:18:49 [scrapy.middleware] INFO: Enabled item pipelines:
    []
    2016-12-16 21:18:49 [scrapy.core.engine] INFO: Spider opened
    2016-12-16 21:18:49 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
    2016-12-16 21:18:50 [scrapy.extensions.logstats] INFO: Crawled 70 pages (at 4200 pages/min), scraped 0 items (at 0 items/min)
    2016-12-16 21:18:51 [scrapy.extensions.logstats] INFO: Crawled 134 pages (at 3840 pages/min), scraped 0 items (at 0 items/min)
    2016-12-16 21:18:52 [scrapy.extensions.logstats] INFO: Crawled 198 pages (at 3840 pages/min), scraped 0 items (at 0 items/min)
    2016-12-16 21:18:53 [scrapy.extensions.logstats] INFO: Crawled 254 pages (at 3360 pages/min), scraped 0 items (at 0 items/min)
    2016-12-16 21:18:54 [scrapy.extensions.logstats] INFO: Crawled 302 pages (at 2880 pages/min), scraped 0 items (at 0 items/min)
    2016-12-16 21:18:55 [scrapy.extensions.logstats] INFO: Crawled 358 pages (at 3360 pages/min), scraped 0 items (at 0 items/min)
    2016-12-16 21:18:56 [scrapy.extensions.logstats] INFO: Crawled 406 pages (at 2880 pages/min), scraped 0 items (at 0 items/min)
    2016-12-16 21:18:57 [scrapy.extensions.logstats] INFO: Crawled 438 pages (at 1920 pages/min), scraped 0 items (at 0 items/min)
    2016-12-16 21:18:58 [scrapy.extensions.logstats] INFO: Crawled 470 pages (at 1920 pages/min), scraped 0 items (at 0 items/min)
    2016-12-16 21:18:59 [scrapy.core.engine] INFO: Closing spider (closespider_timeout)
    2016-12-16 21:18:59 [scrapy.extensions.logstats] INFO: Crawled 518 pages (at 2880 pages/min), scraped 0 items (at 0 items/min)
    2016-12-16 21:19:00 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
    {'downloader/request_bytes': 229995,
     'downloader/request_count': 534,
     'downloader/request_method_count/GET': 534,
     'downloader/response_bytes': 1565504,
     'downloader/response_count': 534,
     'downloader/response_status_count/200': 534,
     'finish_reason': 'closespider_timeout',
     'finish_time': datetime.datetime(2016, 12, 16, 16, 19, 0, 647725),
     'log_count/INFO': 17,
     'request_depth_max': 19,
     'response_received_count': 534,
     'scheduler/dequeued': 533,
     'scheduler/dequeued/memory': 533,
     'scheduler/enqueued': 10661,
     'scheduler/enqueued/memory': 10661,
     'start_time': datetime.datetime(2016, 12, 16, 16, 18, 49, 799869)}
    2016-12-16 21:19:00 [scrapy.core.engine] INFO: Spider closed (closespider_timeout)

That tells you that Scrapy is able to crawl about 3000 pages per minute in the
hardware where you run it. Note that this is a very simple spider intended to
follow links, any custom spider you write will probably do more stuff which
results in slower crawl rates. How slower depends on how much your spider does
and how well it's written.

In the future, more cases will be added to the benchmarking suite to cover
other common scenarios.

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * CGallery class, used to display a set of images from a chosen directory
 */

class CGallery
{
  private $path;
  private $gallery;
  private $breadcrumb;

  /**
  * __construct Used to construct the CGallery, directory argument is supplied
  * GALLERY_PATH and GALLERY_BASEURL must be defined in pagecontroller
  */
  public function __construct($path)
  {
    $this->path = $path;

    // Direct flow to correct html function
    self::selectAction();
  }

  private function validatePaths()
  {
   // Validate incoming arguments
  is_dir(GALLERY_PATH) or
  $gallery->errorMessage('The gallery dir is not a valid directory.');

  substr_compare(GALLERY_PATH, $this->path, 0, strlen(GALLERY_PATH)) == 0 or
  $gallery->errorMessage('Security constraint: Source gallery is not directly below the
  directory GALLERY_PATH.');
  }

  /*
  * Select a function for creating the html output
  */
  private function selectAction()
  {
    // Read and present images in the current directory
    if(is_dir($this->path))
    {
      self::readAllItemsInDir($this->path);
    }
    else if(is_file($this->path))
    {
      self::readItem($this->path);
    }
  }

  /**
   * Display error message.
   *
   * @param string $message the error message to display.
   */
  public function errorMessage($message)
  {
    header("Status: 404 Not Found");
    die('CGallery class throwed a 404 - ' . htmlentities($message));
  }

  /**
   * Read directory and return all items in a ul/li list.
   *
   * @param string $path to the current gallery directory.
   * @param array $validImages to define extensions on what are considered to be valid images.
   */
  private function readAllItemsInDir($path, $validImages = array('png', 'jpg', 'jpeg'))
  {
    $files = glob($path . '/*');
    $this->gallery = "
\n";
    $len = strlen(GALLERY_PATH);

    foreach($files as $file)
    {
      $parts = pathinfo($file);
      $href  = str_replace('\\', '/', substr($file, $len + 1));

      // Is this an image or a directory
      if(is_file($file) && in_array($parts['extension'], $validImages))
      {
        $item = "";
        $caption = basename($file);
      }
      elseif(is_dir($file))
      {
        $item    = "";
        $caption = basename($file) . '/';
      }
      else
      {
        continue;
      }

      // Avoid to long captions breaking layout
      $fullCaption = $caption;
      if(strlen($caption) > 18) {
        $caption = substr($caption, 0, 10) . '…' . substr($caption, -5);
      }

      $this->gallery .= "

{$item}

{$caption}

\n";
    }
    $this->gallery .= "
\n";
  }

  /**
   * Read and return info on choosen item.
   *
   * @param string $path to the current gallery item.
   * @param array $validImages to define extensions on what are considered to be valid images.
   */
  private function readItem($path, $validImages = array('png', 'jpg', 'jpeg'))
  {
    $parts = pathinfo($path);
    if(!(is_file($path) && in_array($parts['extension'], $validImages)))
    {
      return "
This is not a valid image for this gallery.";
    }

    // Get info on image
    $imgInfo = list($width, $height, $type, $attr) = getimagesize($path);
    $mime = $imgInfo['mime'];
    $gmdate = gmdate("D, d M Y H:i:s", filemtime($path));
    $filesize = round(filesize($path) / 1024);

    // Get constraints to display original image
    $displayWidth  = $width > 800 ? "&width=800" : null;
    $displayHeight = $height > 600 ? "&height=600" : null;

    // Display details on image
    $len = strlen(GALLERY_PATH);
    $href = GALLERY_BASEURL . str_replace('\\', '/', substr($path, $len + 1));
    $this->gallery = <<<EOD

Original image dimensions are {$width}x{$height} pixels. View original image.

File size is {$filesize}KBytes.

Image has mimetype: {$mime}.

Image was last modified: {$gmdate} GMT.

EOD;
  }

  // Returns the gallery to the pagecontroller
  public function getGallery()
  {
    return $this->gallery;
  }

  /**
   * Create a breadcrumb of the gallery query path.
   *
   * @param string $path to the current gallery directory.
   * @return string html with ul/li to display the thumbnail.
   */
  public function createBreadcrumb()
  {
    $parts = explode('/', trim(substr($this->path, strlen(GALLERY_PATH) + 1), '/'));
    $breadcrumb = "
\n
Hem »
\n";

    if(!empty($parts[0]))
    {
      $combine = null;
      foreach($parts as $part)
      {
        $combine .= ($combine ? '/' : null) . $part;
        $breadcrumb .= "
$part »
\n";
      }
    }

    $breadcrumb .= "
\n";
    return $breadcrumb;
  }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
All loggers are asynchronous because of log42.component.properties in cas-server-core-logging-api.
Set -Dlog4j2.contextSelector=org.apache.logging.log4j.core.selector.BasicContextSelector or override log42.component.properties to turn off async
-->
<!-- Specify the refresh internal in seconds. -->
<Configuration monitorInterval="5">
    <Appenders>
        <Console name="casConsole" target="SYSTEM_OUT">
            <PatternLayout pattern="%highlight{%d %p [%c] - <%m>%n}" />
        </Console>
        <RollingFile name="casFile" fileName="casconfigserver.log" append="true"
                     filePattern="cas-%d{yyyy-MM-dd-HH}-%i.log">
            <PatternLayout pattern="%highlight{%d %p [%c] - <%m>%n}" />
            <Policies>
                <OnStartupTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="10 MB"/>
                <TimeBasedTriggeringPolicy />
            </Policies>
        </RollingFile>
    </Appenders>

    <Loggers>
        <Logger name="org.apereo.cas" level="info" includeLocation="true" additivity="false">
            <AppenderRef ref="casFile"/>
            <AppenderRef ref="casConsole"/>
        </Logger>
        <Logger name="org.apache" level="info" additivity="false">
            <AppenderRef ref="casFile"/>
            <AppenderRef ref="casConsole"/>
        </Logger>
        <Logger name="org.springframework.cloud.server" level="debug" additivity="false">
            <AppenderRef ref="casFile"/>
            <AppenderRef ref="casConsole"/>
        </Logger>
        <Logger name="org.springframework.cloud.config" level="debug" additivity="false">
            <AppenderRef ref="casFile"/>
            <AppenderRef ref="casConsole"/>
        </Logger>
        <Logger name="org.springframework.cloud.bus" level="info" additivity="false">
            <AppenderRef ref="casFile"/>
            <AppenderRef ref="casConsole"/>
        </Logger>
        <Logger name="org.springframework.cloud.vault" level="warn" additivity="false">
            <AppenderRef ref="casFile"/>
            <AppenderRef ref="casConsole"/>
        </Logger>
        <Logger name="org.springframework.security" level="debug" additivity="false">
            <AppenderRef ref="casFile"/>
            <AppenderRef ref="casConsole"/>
        </Logger>
        <Logger name="org.springframework.boot" level="info" additivity="false">
            <AppenderRef ref="casFile"/>
            <AppenderRef ref="casConsole"/>
        </Logger>
        <Logger name="org.springframework.boot.autoconfigure.security" level="debug" additivity="false">
            <AppenderRef ref="casFile"/>
            <AppenderRef ref="casConsole"/>
        </Logger>
        <Logger name="org.springframework.amqp" level="off" additivity="false">
            <AppenderRef ref="casFile"/>
            <AppenderRef ref="casConsole"/>
        </Logger>
        <Logger name="org.springframework.web" level="warn" additivity="false">
            <AppenderRef ref="casFile"/>
            <AppenderRef ref="casConsole"/>
        </Logger>
        <Root level="error">
            <AppenderRef ref="casConsole"/>
        </Root>
    </Loggers>
</Configuration>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 7(5-6): 304 (1953)

#### Original name
Phoma xanthina Sacc.

### Remarks
null


text:
React Router
============

[![Build Status](https://travis-ci.org/rackt/react-router.svg?branch=master)](https://travis-ci.org/rackt/react-router)

A complete routing library for React.

Docs
----

- [Guide: Overview](/docs/guides/overview.md)
- [API](/docs/api/)

Important Notes
---------------

### **** NPM USERS THIS PACKAGE MOVED ****

This package has moved from `react-nested-router` to `react-router`.

Update your package.json to point to the new package, or if you aren't
ready to update, make sure your package.json specifically points to
`0.3.5` or less, `0.3.6` just throws an error telling you the package
has moved.

### SemVer

Before our `1.0` release, breaking API changes will cause a bump to
`0.x`. For example, `0.4.1` and `0.4.8` will have the same API, but
`0.5.0` will have breaking changes.

Please refer to the [upgrade guide](/UPGRADE_GUIDE.md) and
[changelog](/CHANGELOG) when upgrading.

Installation
------------

```sh
npm install react-router
# or
bower install react-router
```

This library is written with CommonJS modules. If you are using
browserify, webpack, or similar, you can consume it like anything else
installed from npm.

There is also a UMD build available on bower, find the library on
`window.ReactRouter`.

Features
--------

- Nested views mapped to nested routes
- Modular construction of route hierarchy
- Fully asynchronous transition hooks
- Transition abort / redirect / retry
- Dynamic segments
- Query parameters
- Links with automatic `.active` class when their route is active
- Multiple root routes
- Hash or HTML5 history URLs

Check out the `examples` directory to see how simple previously complex UI
and workflows are to create.

What's it look like?
--------------------

```js
React.renderComponent((
  <Routes>
    <Route handler={App}>
      <Route name="about" handler={About}/>
      <Route name="users" handler={Users}>
        <Route name="user" path="/user/:userId" handler={User}/>
      </Route>
    </Route>
  </Routes>
), document.body);
```

See more in the [overview guide](/docs/guides/overview.md).

Benefits of This Approach
-------------------------

1. **Incredible screen-creation productivity** - There is only one
   use-case when a user visits a route: render something. Every user
   interface has layers (or nesting) whether its a simple navbar or
   multiple levels of master-detail. Coupling nested routes to these
   nested views gets rid of a ton of work for the developer to wire all
   of it together when the user switches routes. Adding new screens
   could not get faster.

2. **Immediate understanding of application structure** - When routes
   are declared in one place, developers can easily construct a mental
   image of the application. It's essentially a sitemap. There's not a
   better way to get so much information about your app this quickly.

3. **Code tractability** - When a developer gets a ticket to fix a bug
   at as specific url they simply 1) look at the route config, then 2)
   go find the handler for that route. Every entry point into your
   application is represented by these routes.

4. **URLs are your first thought, not an after-thought** - With React
   Nested Router, you don't get UI on the page without configuring a url
   first. Fortunately, its wildly productive this way, too.

Related Modules
---------------

- https://github.com/bjyoungblood/rnr-constrained-route - validate paths
  and parameters on route handlers.

Contributing
------------

Please see [CONTRIBUTING](CONTRIBUTING.md)

Thanks, Ember
-------------

This library is highly inspired by the Ember.js routing API. In general,
its a translation of the Ember router api to React. Huge thanks to the
Ember team for solving the hardest part already.


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

namespace _02.Dict_Ref
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] tokens = Console.ReadLine().Split(new char[] { ' ', '=' }, StringSplitOptions.RemoveEmptyEntries);

            string firstHalf = tokens[0];

            Dictionary<string, int> namesValues = new Dictionary<string, int>();

            while (firstHalf != "end")
            {
                string secondHalf = tokens[1];
                int number;
                if (int.TryParse(tokens[1], out number))
                {
                    if (!namesValues.ContainsKey(firstHalf))
                    {
                        namesValues.Add(firstHalf, number);
                    }
                    else
                    {
                        namesValues[firstHalf] = number;
                    }
                }
                else
                {
                    int temp;
                    namesValues.TryGetValue(secondHalf, out temp);
                    if (namesValues.ContainsValue(temp))
                    {
                        if (!namesValues.ContainsKey(firstHalf))
                        {
                            namesValues.Add(firstHalf, temp);
                        }
                        else
                        {
                            namesValues[firstHalf] = temp;
                        }
                    }
                }

                tokens = Console.ReadLine().Split(new char[] { ' ', '=' }, StringSplitOptions.RemoveEmptyEntries);
                firstHalf = tokens[0];
            }

            foreach (KeyValuePair<string, int> pair in namesValues)
            {
                Console.WriteLine($"{pair.Key} === {pair.Value}");
            }
        }
    }
}


text:
struct test
    : private std::priority_queue<int>
{
    test()
    {
        c.push_back(1);
        assert(comp(1, 2));
    }
};

struct C
{
    typedef int value_type;
    typedef int& reference;
    typedef const int& const_reference;
    typedef int size_type;
};

int main()
{
    static_assert((std::is_same<std::priority_queue<int>::container_type, std::vector<int> >::value), "");
    static_assert((std::is_same<std::priority_queue<double, std::deque<int> >::container_type, std::deque<int> >::value), "");
    static_assert((std::is_same<std::priority_queue<double, std::deque<int> >::value_type, int>::value), "");
    static_assert((std::is_same<std::priority_queue<int>::reference, std::vector<int>::reference>::value), "");
    static_assert((std::is_same<std::priority_queue<int>::const_reference, std::vector<int>::const_reference>::value), "");
    static_assert((std::is_same<std::priority_queue<int>::size_type, std::vector<int>::size_type>::value), "");
    static_assert((std::uses_allocator<std::priority_queue<int>, std::allocator<int> >::value), "");
    static_assert((!std::uses_allocator<std::priority_queue<int, C>, std::allocator<int> >::value), "");
    test t;
}


text:
module FileReaderTest
  module EachCodepoint
    def test_each_codepoint
      file = file_containing("tāiko")
      codepoints = []

      file.each_codepoint do |codepoint|
        codepoints << codepoint
      end

      assert_equal [116, 257, 105, 107, 111], codepoints
    end

    def test_each_codepoint_increments_pos
      file = file_containing("tōrea")
      poses = []

      file.each_codepoint do
        poses << file.pos
      end

      assert_equal [1, 3, 4, 5, 6], poses
    end

    def test_each_codepoint_at_eof_does_nothing
      file_at_eof.each_codepoint do
        flunk "Expected block not to be called."
      end
    end

    def test_cannot_enumerate_codepoints_when_closed
      assert_raises IOError do
        closed_file.each_codepoint do
          flunk "Expected block not to be called."
        end
      end
    end

    def test_each_codepoint_returns_enumerator_when_no_block_given
      file = file_containing("tāiko")

      enumerator = file.each_codepoint

      assert_equal 116, enumerator.next
      assert_equal 257, enumerator.next
    end

    def test_cannot_get_codepoint_enumerator_when_closed
      assert_raises IOError do
        closed_file.each_codepoint
      end
    end
  end
end


text:
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#nav-main" aria-expanded="true">

            </button>

            <link rel="import" href="ul.html?__inline">


text:
<?php
namespace Application\Controller;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class MessageStoreControllerFactory implements FactoryInterface
{

    /**
     *
     * {@inheritdoc}
     * @see \Zend\ServiceManager\FactoryInterface::createService()
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $container = $serviceLocator->getServiceLocator();

        $controller = new MessageStoreController();

        $sv = $container->get('doctrine.entitymanager.orm_default');
        $controller->setDoctrineEM($sv);

        $sv = $container->get(\Application\Application\Service\MessageStore\MessageQuery::class);
        $controller->setMessageQuery($sv);

        return $controller;
    }
}


text:
using Aragas.Network.Data;
using Aragas.Network.IO;

namespace PokeD.Core.Packets.PokeD.Chat
{
    public class ChatPrivateMessagePacket : PokeDPacket
    {
        public VarInt PlayerID { get; set; }
        public string Message { get; set; } = string.Empty;

        public override void Deserialize(ProtobufDeserialiser deserialiser)
        {
            PlayerID = deserialiser.Read(PlayerID);
            Message = deserialiser.Read(Message);
        }
        public override void Serialize(ProtobufSerializer serializer)
        {
            serializer.Write(PlayerID);
            serializer.Write(Message);
        }
    }
}


text:
struct moveable {
    bool    state;
    int     value;

    moveable() :
        state( false),
        value( -1) {
    }

    moveable( int v) :
        state( true),
        value( v) {
    }

    moveable( moveable && other) :
        state( other.state),
        value( other.value) {
        other.state = false;
        other.value = -1;
    }

    moveable & operator=( moveable && other) {
        if ( this == & other) return * this;
        state = other.state;
        other.state = false;
        value = other.value;
        other.value = -1;
        return * this;
    }
};

void test_zero_wm() {
    bool thrown = false;
    try {
        boost::fibers::buffered_channel< int > c( 0);
    } catch ( boost::fibers::fiber_error const&) {
        thrown = true;
    }
    BOOST_CHECK( thrown);
}

void test_push() {
    boost::fibers::buffered_channel< int > c( 16);
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 1) );
}

void test_push_closed() {
    boost::fibers::buffered_channel< int > c( 16);
    c.close();
    BOOST_CHECK( boost::fibers::channel_op_status::closed == c.push( 1) );
}

void test_try_push() {
    boost::fibers::buffered_channel< int > c( 2);
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 1) );
}

void test_try_push_closed() {
    boost::fibers::buffered_channel< int > c( 2);
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.try_push( 1) );
    c.close();
    BOOST_CHECK( boost::fibers::channel_op_status::closed == c.try_push( 2) );
}

void test_try_push_full() {
    boost::fibers::buffered_channel< int > c( 2);
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.try_push( 1) );
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.try_push( 2) );
    BOOST_CHECK( boost::fibers::channel_op_status::full == c.try_push( 3) );
}

void test_push_wait_for() {
    boost::fibers::buffered_channel< int > c( 2);
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push_wait_for( 1, std::chrono::seconds( 1) ) );
}

void test_push_wait_for_closed() {
    boost::fibers::buffered_channel< int > c( 2);
    c.close();
    BOOST_CHECK( boost::fibers::channel_op_status::closed == c.push_wait_for( 1, std::chrono::seconds( 1) ) );
}

void test_push_wait_for_timeout() {
    boost::fibers::buffered_channel< int > c( 2);
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push_wait_for( 1, std::chrono::seconds( 1) ) );
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push_wait_for( 2, std::chrono::seconds( 1) ) );
    BOOST_CHECK( boost::fibers::channel_op_status::timeout == c.push_wait_for( 3, std::chrono::seconds( 1) ) );
}

void test_push_wait_until() {
    boost::fibers::buffered_channel< int > c( 2);
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push_wait_until( 1,
                    std::chrono::system_clock::now() + std::chrono::seconds( 1) ) );
}

void test_push_wait_until_closed() {
    boost::fibers::buffered_channel< int > c( 2);
    c.close();
    BOOST_CHECK( boost::fibers::channel_op_status::closed == c.push_wait_until( 1,
                    std::chrono::system_clock::now() + std::chrono::seconds( 1) ) );
}

void test_push_wait_until_timeout() {
    boost::fibers::buffered_channel< int > c( 2);
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push_wait_until( 1,
                    std::chrono::system_clock::now() + std::chrono::seconds( 1) ) );
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push_wait_until( 2,
                    std::chrono::system_clock::now() + std::chrono::seconds( 1) ) );
    BOOST_CHECK( boost::fibers::channel_op_status::timeout == c.push_wait_until( 3,
                    std::chrono::system_clock::now() + std::chrono::seconds( 1) ) );
}

void test_pop() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.pop( v2) );
    BOOST_CHECK_EQUAL( v1, v2);
}

void test_pop_closed() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    c.close();
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.pop( v2) );
    BOOST_CHECK_EQUAL( v1, v2);
    BOOST_CHECK( boost::fibers::channel_op_status::closed == c.pop( v2) );
}

void test_pop_success() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    boost::fibers::fiber f1( boost::fibers::launch::post, [&c,&v2](){
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.pop( v2) );
    });
    boost::fibers::fiber f2( boost::fibers::launch::post, [&c,v1](){
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    });
    f1.join();
    f2.join();
    BOOST_CHECK_EQUAL( v1, v2);
}

void test_value_pop() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    v2 = c.value_pop();
    BOOST_CHECK_EQUAL( v1, v2);
}

void test_value_pop_closed() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    c.close();
    v2 = c.value_pop();
    BOOST_CHECK_EQUAL( v1, v2);
    bool thrown = false;
    try {
        c.value_pop();
    } catch ( boost::fibers::fiber_error const&) {
        thrown = true;
    }
    BOOST_CHECK( thrown);
}

void test_value_pop_success() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    boost::fibers::fiber f1( boost::fibers::launch::post, [&c,&v2](){
        v2 = c.value_pop();
    });
    boost::fibers::fiber f2( boost::fibers::launch::post, [&c,v1](){
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    });
    f1.join();
    f2.join();
    BOOST_CHECK_EQUAL( v1, v2);
}

void test_try_pop() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.try_pop( v2) );
    BOOST_CHECK_EQUAL( v1, v2);
}

void test_try_pop_closed() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    c.close();
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.try_pop( v2) );
    BOOST_CHECK_EQUAL( v1, v2);
    BOOST_CHECK( boost::fibers::channel_op_status::closed == c.try_pop( v2) );
}

void test_try_pop_success() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    boost::fibers::fiber f1( boost::fibers::launch::post, [&c,&v2](){
        while ( boost::fibers::channel_op_status::success != c.try_pop( v2) ) {
            boost::this_fiber::yield();
        }
    });
    boost::fibers::fiber f2( boost::fibers::launch::post, [&c,v1](){
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    });
    f1.join();
    f2.join();
    BOOST_CHECK_EQUAL( v1, v2);
}

void test_pop_wait_for() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.pop_wait_for( v2, std::chrono::seconds( 1) ) );
    BOOST_CHECK_EQUAL( v1, v2);
}

void test_pop_wait_for_closed() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    c.close();
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.pop_wait_for( v2, std::chrono::seconds( 1) ) );
    BOOST_CHECK_EQUAL( v1, v2);
    BOOST_CHECK( boost::fibers::channel_op_status::closed == c.pop_wait_for( v2, std::chrono::seconds( 1) ) );
}

void test_pop_wait_for_success() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    boost::fibers::fiber f1( boost::fibers::launch::post, [&c,&v2](){
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.pop_wait_for( v2, std::chrono::seconds( 1) ) );
    });
    boost::fibers::fiber f2( boost::fibers::launch::post, [&c,v1](){
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    });
    f1.join();
    f2.join();
    BOOST_CHECK_EQUAL( v1, v2);
}

void test_pop_wait_for_timeout() {
    boost::fibers::buffered_channel< int > c( 16);
    int v = 0;
    boost::fibers::fiber f( boost::fibers::launch::post, [&c,&v](){
        BOOST_CHECK( boost::fibers::channel_op_status::timeout == c.pop_wait_for( v, std::chrono::seconds( 1) ) );
    });
    f.join();
}

void test_pop_wait_until() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.pop_wait_until( v2,
            std::chrono::system_clock::now() + std::chrono::seconds( 1) ) );
    BOOST_CHECK_EQUAL( v1, v2);
}

void test_pop_wait_until_closed() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    c.close();
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.pop_wait_until( v2,
            std::chrono::system_clock::now() + std::chrono::seconds( 1) ) );
    BOOST_CHECK_EQUAL( v1, v2);
    BOOST_CHECK( boost::fibers::channel_op_status::closed == c.pop_wait_until( v2,
            std::chrono::system_clock::now() + std::chrono::seconds( 1) ) );
}

void test_pop_wait_until_success() {
    boost::fibers::buffered_channel< int > c( 16);
    int v1 = 2, v2 = 0;
    boost::fibers::fiber f1( boost::fibers::launch::post, [&c,&v2](){
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.pop_wait_until( v2,
                    std::chrono::system_clock::now() + std::chrono::seconds( 1) ) );
    });
    boost::fibers::fiber f2( boost::fibers::launch::post, [&c,v1](){
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( v1) );
    });
    f1.join();
    f2.join();
    BOOST_CHECK_EQUAL( v1, v2);
}

void test_pop_wait_until_timeout() {
    boost::fibers::buffered_channel< int > c( 16);
    int v = 0;
    boost::fibers::fiber f( boost::fibers::launch::post, [&c,&v](){
        BOOST_CHECK( boost::fibers::channel_op_status::timeout == c.pop_wait_until( v,
                    std::chrono::system_clock::now() + std::chrono::seconds( 1) ) );
    });
    f.join();
}

void test_wm_1() {
    boost::fibers::buffered_channel< int > c( 4);
    std::vector< boost::fibers::fiber::id > ids;
    boost::fibers::fiber f1( boost::fibers::launch::post, [&c,&ids](){
        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 1) );

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 2) );

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 3) );

        ids.push_back( boost::this_fiber::get_id() );
        // would be blocked because channel is full
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 4) );

        ids.push_back( boost::this_fiber::get_id() );
        // would be blocked because channel is full
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 5) );

        ids.push_back( boost::this_fiber::get_id() );
    });
    boost::fibers::fiber f2( boost::fibers::launch::post, [&c,&ids](){
        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK_EQUAL( 1, c.value_pop() );

        // let other fiber run
        boost::this_fiber::yield();

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK_EQUAL( 2, c.value_pop() );

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK_EQUAL( 3, c.value_pop() );

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK_EQUAL( 4, c.value_pop() );

        ids.push_back( boost::this_fiber::get_id() );
        // would block because channel is empty
        BOOST_CHECK_EQUAL( 5, c.value_pop() );

        ids.push_back( boost::this_fiber::get_id() );
    });
    boost::fibers::fiber::id id1 = f1.get_id();
    boost::fibers::fiber::id id2 = f2.get_id();
    f1.join();
    f2.join();
    BOOST_CHECK_EQUAL( 12u, ids.size() );
    BOOST_CHECK_EQUAL( id1, ids[0]);
    BOOST_CHECK_EQUAL( id1, ids[1]);
    BOOST_CHECK_EQUAL( id1, ids[2]);
    BOOST_CHECK_EQUAL( id1, ids[3]);
    BOOST_CHECK_EQUAL( id1, ids[4]);
    BOOST_CHECK_EQUAL( id2, ids[5]);
    BOOST_CHECK_EQUAL( id1, ids[6]);
    BOOST_CHECK_EQUAL( id2, ids[7]);
    BOOST_CHECK_EQUAL( id2, ids[8]);
    BOOST_CHECK_EQUAL( id2, ids[9]);
    BOOST_CHECK_EQUAL( id2, ids[10]);
    BOOST_CHECK_EQUAL( id2, ids[11]);
}

void test_wm_2() {
    boost::fibers::buffered_channel< int > c( 8);
    std::vector< boost::fibers::fiber::id > ids;
    boost::fibers::fiber f1( boost::fibers::launch::post, [&c,&ids](){
        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 1) );

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 2) );

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 3) );

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 4) );

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( 5) );

        ids.push_back( boost::this_fiber::get_id() );
    });
    boost::fibers::fiber f2( boost::fibers::launch::post, [&c,&ids](){
        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK_EQUAL( 1, c.value_pop() );

        // let other fiber run
        boost::this_fiber::yield();

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK_EQUAL( 2, c.value_pop() );

        // let other fiber run
        boost::this_fiber::yield();

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK_EQUAL( 3, c.value_pop() );

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK_EQUAL( 4, c.value_pop() );

        ids.push_back( boost::this_fiber::get_id() );
        BOOST_CHECK_EQUAL( 5, c.value_pop() );

        ids.push_back( boost::this_fiber::get_id() );
    });
    boost::fibers::fiber::id id1 = f1.get_id();
    boost::fibers::fiber::id id2 = f2.get_id();
    f1.join();
    f2.join();
    BOOST_CHECK_EQUAL( 12u, ids.size() );
    BOOST_CHECK_EQUAL( id1, ids[0]);
    BOOST_CHECK_EQUAL( id1, ids[1]);
    BOOST_CHECK_EQUAL( id1, ids[2]);
    BOOST_CHECK_EQUAL( id1, ids[3]);
    BOOST_CHECK_EQUAL( id1, ids[4]);
    BOOST_CHECK_EQUAL( id1, ids[5]);
    BOOST_CHECK_EQUAL( id2, ids[6]);
    BOOST_CHECK_EQUAL( id2, ids[7]);
    BOOST_CHECK_EQUAL( id2, ids[8]);
    BOOST_CHECK_EQUAL( id2, ids[9]);
    BOOST_CHECK_EQUAL( id2, ids[10]);
    BOOST_CHECK_EQUAL( id2, ids[11]);
}

void test_moveable() {
    boost::fibers::buffered_channel< moveable > c( 16);
    moveable m1( 3), m2;
    BOOST_CHECK( m1.state);
    BOOST_CHECK_EQUAL( 3, m1.value);
    BOOST_CHECK( ! m2.state);
    BOOST_CHECK_EQUAL( -1, m2.value);
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.push( std::move( m1) ) );
    BOOST_CHECK( ! m1.state);
    BOOST_CHECK( ! m2.state);
    BOOST_CHECK( boost::fibers::channel_op_status::success == c.pop( m2) );
    BOOST_CHECK( ! m1.state);
    BOOST_CHECK_EQUAL( -1, m1.value);
    BOOST_CHECK( m2.state);
    BOOST_CHECK_EQUAL( 3, m2.value);
}

void test_rangefor() {
    boost::fibers::buffered_channel< int > chan{ 2 };
    std::vector< int > vec;
    boost::fibers::fiber f1([&chan]{
        chan.push( 1);
        chan.push( 1);
        chan.push( 2);
        chan.push( 3);
        chan.push( 5);
        chan.push( 8);
        chan.push( 12);
        chan.close();
    });
    boost::fibers::fiber f2([&vec,&chan]{
        for ( int value : chan) {
            vec.push_back( value);
        }
    });
    f1.join();
    f2.join();
    BOOST_CHECK_EQUAL( 1, vec[0]);
    BOOST_CHECK_EQUAL( 1, vec[1]);
    BOOST_CHECK_EQUAL( 2, vec[2]);
    BOOST_CHECK_EQUAL( 3, vec[3]);
    BOOST_CHECK_EQUAL( 5, vec[4]);
    BOOST_CHECK_EQUAL( 8, vec[5]);
    BOOST_CHECK_EQUAL( 12, vec[6]);
}

boost::unit_test::test_suite * init_unit_test_suite( int, char* []) {
    boost::unit_test::test_suite * test =
        BOOST_TEST_SUITE("Boost.Fiber: buffered_channel test suite");

     test->add( BOOST_TEST_CASE( & test_zero_wm) );
     test->add( BOOST_TEST_CASE( & test_push) );
     test->add( BOOST_TEST_CASE( & test_push_closed) );
     test->add( BOOST_TEST_CASE( & test_try_push) );
     test->add( BOOST_TEST_CASE( & test_try_push_closed) );
     test->add( BOOST_TEST_CASE( & test_try_push_full) );
     test->add( BOOST_TEST_CASE( & test_push_wait_for) );
     test->add( BOOST_TEST_CASE( & test_push_wait_for_closed) );
     test->add( BOOST_TEST_CASE( & test_push_wait_for_timeout) );
     test->add( BOOST_TEST_CASE( & test_push_wait_until) );
     test->add( BOOST_TEST_CASE( & test_push_wait_until_closed) );
     test->add( BOOST_TEST_CASE( & test_push_wait_until_timeout) );
     test->add( BOOST_TEST_CASE( & test_pop) );
     test->add( BOOST_TEST_CASE( & test_pop_closed) );
     test->add( BOOST_TEST_CASE( & test_pop_success) );
     test->add( BOOST_TEST_CASE( & test_value_pop) );
     test->add( BOOST_TEST_CASE( & test_value_pop_closed) );
     test->add( BOOST_TEST_CASE( & test_value_pop_success) );
     test->add( BOOST_TEST_CASE( & test_try_pop) );
     test->add( BOOST_TEST_CASE( & test_try_pop_closed) );
     test->add( BOOST_TEST_CASE( & test_try_pop_success) );
     test->add( BOOST_TEST_CASE( & test_pop_wait_for) );
     test->add( BOOST_TEST_CASE( & test_pop_wait_for_closed) );
     test->add( BOOST_TEST_CASE( & test_pop_wait_for_success) );
     test->add( BOOST_TEST_CASE( & test_pop_wait_for_timeout) );
     test->add( BOOST_TEST_CASE( & test_pop_wait_until) );
     test->add( BOOST_TEST_CASE( & test_pop_wait_until_closed) );
     test->add( BOOST_TEST_CASE( & test_pop_wait_until_success) );
     test->add( BOOST_TEST_CASE( & test_pop_wait_until_timeout) );
     test->add( BOOST_TEST_CASE( & test_wm_1) );
     test->add( BOOST_TEST_CASE( & test_wm_2) );
     test->add( BOOST_TEST_CASE( & test_moveable) );
     test->add( BOOST_TEST_CASE( & test_rangefor) );

    return test;
}


text:
// Copyright 2021 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.packages;

import static com.google.common.truth.Truth.assertThat;

import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import java.util.HashMap;
import java.util.Map;
import net.starlark.java.annot.Param;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.Dict;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkInt;
import net.starlark.java.eval.StarlarkList;
import net.starlark.java.eval.StarlarkValue;
import net.starlark.java.eval.Tuple;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@code native.existing_rule} and {@code native.existing_rules} functions.
 *
 * <p>This class covers the legacy behavior where the {@code
 * --incompatible_existing_rules_immutable_view} flag is disabled. The enabled case is covered by
 * the subclass, {@link WithImmutableView}.
 */
@RunWith(JUnit4.class)
public class NativeExistingRulesTest extends BuildViewTestCase {
  private TestStarlarkBuiltin testStarlarkBuiltin; // initialized by createRuleClassProvider()

  // Intended to be overridden by this test case's subclasses. Note that overriding of JUnit's
  // @Before methods is not recommended.
  protected void setupOptions() throws Exception {
    // --noincompatible_existing_rules_immutable_view is the default; set it explicitly for clarity.
    setBuildLanguageOptions("--noincompatible_existing_rules_immutable_view");
  }

  @Before
  public final void setUp() throws Exception {
    setupOptions();
  }

  @StarlarkBuiltin(name = "test")
  private static final class TestStarlarkBuiltin implements StarlarkValue {

    private final Map<String, Object> saved = new HashMap<>();

    @StarlarkMethod(
        name = "save",
        parameters = {
          @Param(name = "name", doc = "Name under which to save the value"),
          @Param(name = "value", doc = "Value to save")
        },
        doc = "Saves a Starlark value for testing from Java")
    public synchronized void save(String name, Object value) {
      saved.put(name, value);
    }
  }

  @Override
  protected ConfiguredRuleClassProvider createRuleClassProvider() {
    ConfiguredRuleClassProvider.Builder builder = new ConfiguredRuleClassProvider.Builder();
    TestRuleClassProvider.addStandardRules(builder);
    testStarlarkBuiltin = new TestStarlarkBuiltin();
    builder.addStarlarkAccessibleTopLevels("test", testStarlarkBuiltin);
    return builder.build();
  }

  private Object getSaved(String name) {
    return testStarlarkBuiltin.saved.get(name);
  }

  @Test
  public void existingRule_handlesSelect() throws Exception {
    scratch.file("test/starlark/BUILD");
    scratch.file(
        "test/starlark/rulestr.bzl", //
        "def rule_dict(name):",
        "  return native.existing_rule(name)");

    scratch.file(
        "test/getrule/BUILD",
        "load('//test/starlark:rulestr.bzl', 'rule_dict')",
        "cc_library(",
        "    name ='x',",
        "    srcs = select({'//conditions:default': []}),",
        ")",
        "rule_dict('x')");

    // Parse the BUILD file, to make sure select() makes it out of native.existing_rule().
    assertThat(getConfiguredTarget("//test/getrule:x")).isNotNull();
  }

  @Test
  public void existingRule_returnsNone() throws Exception {
    scratch.file(
        "test/rulestr.bzl",
        "def test_rule(name, x):",
        "  print(native.existing_rule(x))",
        "  if native.existing_rule(x) == None:",
        "    native.cc_library(name = name)");
    scratch.file(
        "test/BUILD",
        "load('//test:rulestr.bzl', 'test_rule')",
        "test_rule('a', 'does not exist')",
        "test_rule('b', 'BUILD')"); // exists, but as a target and not a rule

    assertThat(getConfiguredTarget("//test:a")).isNotNull();
    assertThat(getConfiguredTarget("//test:b")).isNotNull();
  }

  @Test
  public void existingRule_roundTripsSelect() throws Exception {
    scratch.file(
        "test/existing_rule.bzl",
        "def macro():",
        "  s = select({'//foo': ['//bar']})",
        "  print('Passed: ' + repr(s))",
        "  native.cc_library(name = 'x', srcs = s)",
        "  print('Returned: ' + repr(native.existing_rule('x')['srcs']))",
        // The value returned here should round-trip fine.
        "  native.cc_library(name = 'y', srcs = native.existing_rule('x')['srcs'])");
    scratch.file(
        "test/BUILD",
        "load('//test:existing_rule.bzl', 'macro')",
        "macro()",
        "cc_library(name = 'a', srcs = [])");
    getConfiguredTarget("//test:a");
    assertContainsEvent("Passed: select({\"//foo\": [\"//bar\"]}");
    // The short labels are now in their canonical form, and the sequence is represented as
    // tuple instead of list, but the meaning is unchanged.
    assertContainsEvent("Returned: select({\"//foo:foo\": (\"//bar:bar\",)}");
  }

  @Test
  public void existingRule_shortensLabelsInSamePackage() throws Exception {
    scratch.file(
        "test/existing_rule.bzl",
        "def save_deps():",
        "  r = native.existing_rule('b')",
        "  test.save(\"r['deps']\", r['deps'])");
    scratch.file(
        "test/BUILD",
        "load('//test:existing_rule.bzl', 'save_deps')",
        "cc_library(name = 'a', srcs = [])",
        "cc_binary(name = 'b', deps = ['//test:a'])",
        "save_deps()");
    getConfiguredTarget("//test:b");
    assertThat(Starlark.toIterable(getSaved("r['deps']")))
        .containsExactly(":a"); // as opposed to "//test:a"
  }

  @Test
  public void existingRules_findsRulesAndAttributes() throws Exception {
    scratch.file("test/BUILD");
    scratch.file("test/starlark/BUILD");
    scratch.file(
        "test/starlark/rulestr.bzl",
        "def rule_dict(name):",
        "  return native.existing_rule(name)",
        "def rules_dict():",
        "  return native.existing_rules()",
        "def nop(ctx):",
        "  pass",
        "nop_rule = rule(attrs = {'x': attr.label()}, implementation = nop)",
        "def test_save(name, value):",
        "  test.save(name, value)");

    scratch.file(
        "test/getrule/BUILD",
        "load('//test/starlark:rulestr.bzl', 'rules_dict', 'rule_dict', 'nop_rule', 'test_save')",
        "genrule(name = 'a', outs = ['a.txt'], ",
        "        licenses = ['notice'],",
        "        output_to_bindir = False,",
        "        tools = [ '//test:bla' ], cmd = 'touch $@')",
        "nop_rule(name = 'c', x = ':a')",
        "rlist = rules_dict()",
        "test_save('all_str', [rlist['a']['kind'], rlist['a']['name'],",
        "                      rlist['c']['kind'], rlist['c']['name']])",
        "adict = rule_dict('a')",
        "cdict = rule_dict('c')",
        "test_save('a_str', [adict['kind'], adict['name'], adict['outs'][0], adict['tools'][0]])",
        "test_save('c_str', [cdict['kind'], cdict['name'], cdict['x']])",
        "test_save('adict.keys()', adict.keys())");

    getConfiguredTarget("//test/getrule:BUILD");
    assertThat(Starlark.toIterable(getSaved("all_str")))
        .containsExactly("genrule", "a", "nop_rule", "c")
        .inOrder();
    assertThat(Starlark.toIterable(getSaved("a_str")))
        .containsExactly("genrule", "a", ":a.txt", "//test:bla")
        .inOrder();
    assertThat(Starlark.toIterable(getSaved("c_str")))
        .containsExactly("nop_rule", "c", ":a")
        .inOrder();
    assertThat(Starlark.toIterable(getSaved("adict.keys()")))
        .containsAtLeast(
            "name",
            "visibility",
            "transitive_configs",
            "tags",
            "generator_name",
            "generator_function",
            "generator_location",
            "features",
            "compatible_with",
            "target_compatible_with",
            "restricted_to",
            "srcs",
            "tools",
            "toolchains",
            "outs",
            "cmd",
            "output_to_bindir",
            "local",
            "message",
            "executable",
            "stamp",
            "heuristic_label_expansion",
            "kind");
  }

  @Test
  public void existingRule_ignoresHiddenAttributes() throws Exception {
    scratch.file(
        "test/inc.bzl", //
        "def _check_hidden_attr_exists(ctx):",
        "    if ctx.attr._hidden_attr != 'hidden_val':",
        "        fail('ctx.attr._hidden_attr != \"hidden_val\"')",
        "    pass",
        "my_rule = rule(",
        "    attrs = {",
        "        '_hidden_attr': attr.string(default = 'hidden_val'),",
        "        'normal_attr': attr.string(default = 'normal_val'),",
        "    },",
        "    implementation = _check_hidden_attr_exists",
        ")",
        "def f():",
        "    my_rule(name = 'rulename')",
        "    r = native.existing_rule('rulename')",
        "    test.save('r.keys()', r.keys())",
        "    test.save('r.values()', r.values())",
        "    test.save('\"_hidden_attr\" in r', \"_hidden_attr\" in r)");
    scratch.file(
        "test/BUILD",
        "load('inc.bzl', 'f')", //
        "f()");

    assertThat(getConfiguredTarget("//test:rulename")).isNotNull();
    assertThat(Starlark.toIterable(getSaved("r.keys()")))
        .containsAtLeast("name", "kind", "normal_attr");
    assertThat(Starlark.toIterable(getSaved("r.keys()"))).doesNotContain("_hidden_attr");
    assertThat(Starlark.toIterable(getSaved("r.values()")))
        .containsAtLeast("rulename", "my_rule", "normal_val");
    assertThat(Starlark.toIterable(getSaved("r.values()"))).doesNotContain("hidden_val");
    assertThat((Boolean) getSaved("\"_hidden_attr\" in r")).isFalse();
  }

  @Test
  public void existingRule_returnsObjectWithCorrectMutability() throws Exception {
    scratch.file(
        "test/BUILD",
        "load('inc.bzl', 'f')", //
        "f()");
    scratch.file(
        "test/inc.bzl", //
        "def f():",
        "  native.config_setting(name='x', define_values={'key': 'value'})",
        "  r = native.existing_rule('x')",
        "  r['no_such_attribute'] = 'foo'",
        "  r['define_values']['key'] = 123"); // mutate the dict

    assertThat(getConfiguredTarget("//test:BUILD")).isNotNull(); // no error on mutation
  }

  @Test
  public void existingRule_returnsDictLikeObject() throws Exception {
    scratch.file(
        "test/BUILD",
        "load('inc.bzl', 'f')", //
        "f()");
    scratch.file(
        "test/inc.bzl", //
        "def f():",
        "  native.config_setting(name='x', define_values={'key': 'value'})",
        "  r = native.existing_rule('x')",
        "  print('r == %s' % repr(r))",
        "  test.save('[key for key in r]', [key for key in r])",
        "  test.save('list(r)', list(r))",
        "  test.save('r.keys()', r.keys())",
        "  test.save('r.values()', r.values())",
        "  test.save('r.items()', r.items())",
        "  test.save(\"r['define_values']\", r['define_values'])",
        "  test.save(\"r.get('define_values', 123)\", r.get('define_values', 123))",
        "  test.save(\"r.get('invalid_attr', 123)\", r.get('invalid_attr', 123))",
        "  test.save(\"'define_values' in r\", 'define_values' in r)",
        "  test.save(\"'invalid_attr' in r\", 'invalid_attr' in r)");

    Dict<?, ?> expectedDefineValues = Dict.builder().put("key", "value").buildImmutable();
    assertThat(getConfiguredTarget("//test:BUILD")).isNotNull(); // no error
    assertThat(Starlark.toIterable(getSaved("[key for key in r]")))
        .containsAtLeast("define_values", "name", "kind");
    assertThat(Starlark.toIterable(getSaved("list(r)")))
        .containsAtLeast("define_values", "name", "kind");
    assertThat(Starlark.toIterable(getSaved("r.keys()")))
        .containsAtLeast("define_values", "name", "kind");
    assertThat(Starlark.toIterable(getSaved("r.values()")))
        .containsAtLeast(expectedDefineValues, "x", "config_setting");
    assertThat(Starlark.toIterable(getSaved("r.items()")))
        .containsAtLeast(
            Tuple.of("define_values", expectedDefineValues),
            Tuple.of("name", "x"),
            Tuple.of("kind", "config_setting"));
    assertThat(getSaved("r['define_values']")).isEqualTo(expectedDefineValues);
    assertThat(getSaved("r.get('define_values', 123)")).isEqualTo(expectedDefineValues);
    assertThat(getSaved("r.get('invalid_attr', 123)")).isEqualTo(StarlarkInt.of(123));
    assertThat(getSaved("'define_values' in r")).isEqualTo(true);
    assertThat(getSaved("'invalid_attr' in r")).isEqualTo(false);
  }

  @Test
  public void existingRule_asDictArgument() throws Exception {
    scratch.file(
        "test/test.bzl",
        "def save_as_dict(r):",
        "  test.save('type(dict(r))', type(dict(r)))",
        "  test.save('dict(r)[\"name\"]', dict(r)[\"name\"])",
        "  test.save('dict(r)[\"kind\"]', dict(r)[\"kind\"])");
    scratch.file(
        "test/BUILD",
        "load('//test:test.bzl', 'save_as_dict')", //
        "cc_library(",
        "    name ='rulename',",
        ")",
        "save_as_dict(existing_rule('rulename'))");
    getConfiguredTarget("//test:rulename");
    assertThat(getSaved("type(dict(r))")).isEqualTo("dict");
    assertThat(getSaved("dict(r)[\"name\"]")).isEqualTo("rulename");
    assertThat(getSaved("dict(r)[\"kind\"]")).isEqualTo("cc_library");
  }

  @Test
  public void existingRule_asDictUpdateArgument() throws Exception {
    // We do not test `existing_rule(r).update({...})` because `existing_rule(r)` may be immutable
    // (as verified by other test cases).
    scratch.file(
        "test/test.bzl",
        "def save_as_updated_dict(r):",
        "  updated_dict = {'name': 'dictname', 'dictkey': 1}",
        "  updated_dict.update(r)",
        "  test.save('updated_dict[\"name\"]', updated_dict[\"name\"])",
        "  test.save('updated_dict[\"kind\"]', updated_dict[\"kind\"])",
        "  test.save('updated_dict[\"dictkey\"]', updated_dict[\"dictkey\"])");
    scratch.file(
        "test/BUILD",
        "load('//test:test.bzl', 'save_as_updated_dict')", //
        "cc_library(",
        "    name ='rulename',",
        ")",
        "save_as_updated_dict(existing_rule('rulename'))");
    getConfiguredTarget("//test:rulename");
    assertThat(getSaved("updated_dict[\"name\"]")).isEqualTo("rulename");
    assertThat(getSaved("updated_dict[\"kind\"]")).isEqualTo("cc_library");
    assertThat(getSaved("updated_dict[\"dictkey\"]")).isEqualTo(StarlarkInt.of(1));
  }

  @Test
  public void existingRule_unionableWithDict() throws Exception {
    scratch.file(
        "test/test.bzl",
        "def save_as_union(dict_val, r):",
        "  test.save('dict_val | r', dict_val | r)",
        "  test.save('r | dict_val', r | dict_val)",
        "  dict_val |= r",
        "  test.save('dict_val |= r', dict_val)");
    scratch.file(
        "test/BUILD",
        "load('//test:test.bzl', 'save_as_union')",
        "cc_library(",
        "    name ='rulename',",
        ")",
        "save_as_union({'name': 'dictname', 'dictkey': 1}, existing_rule('rulename'))");
    getConfiguredTarget("//test:rulename");
    Map<String, Object> unionDictWithExistingRule =
        Dict.cast(getSaved("dict_val | r"), String.class, Object.class, "dict_val | r");
    assertThat(unionDictWithExistingRule)
        .containsAtLeast("name", "rulename", "dictkey", StarlarkInt.of(1), "kind", "cc_library");
    Map<String, Object> unionExistingRuleWithDict =
        Dict.cast(getSaved("r | dict_val"), String.class, Object.class, "r | dict_val");
    assertThat(unionExistingRuleWithDict)
        .containsAtLeast("name", "dictname", "dictkey", StarlarkInt.of(1), "kind", "cc_library");
    Map<String, Object> inPlaceUnionDictWithExistingRule =
        Dict.cast(getSaved("dict_val |= r"), String.class, Object.class, "dict_val | r");
    assertThat(inPlaceUnionDictWithExistingRule)
        .containsAtLeast("name", "rulename", "dictkey", StarlarkInt.of(1), "kind", "cc_library");
  }

  @Test
  public void existingRule_asKwargs() throws Exception {
    scratch.file(
        "test/test.bzl",
        "def save_kwargs(**kwargs):",
        "  test.save('kwargs[\"name\"]', kwargs[\"name\"])",
        "  test.save('kwargs[\"kind\"]', kwargs[\"kind\"])",
        "def save_kwargs_of_existing_rule(name):",
        "  save_kwargs(**native.existing_rule(name))");
    scratch.file(
        "test/BUILD",
        "load('//test:test.bzl', 'save_kwargs_of_existing_rule')", //
        "cc_library(",
        "    name ='rulename',",
        ")",
        "save_kwargs_of_existing_rule('rulename')");
    getConfiguredTarget("//test:rulename");
    assertThat(getSaved("kwargs[\"name\"]")).isEqualTo("rulename");
    assertThat(getSaved("kwargs[\"kind\"]")).isEqualTo("cc_library");
  }

  // Regression test for https://github.com/bazelbuild/bazel/issues/16256
  @Test
  public void existingRule_encodesToJson() throws Exception {
    // We need a Starlark rule - native rules can have attribute values that the json encoder
    // doesn't handle.
    scratch.file(
        "test/test.bzl",
        "def _dummy_impl(ctx):",
        "  pass",
        "test_library = rule(",
        "  implementation = _dummy_impl,",
        "  attrs = {'srcs': attr.label_list(allow_files = True)},",
        ")",
        // TODO(b/249397668): simplifying this to `json_encode = json.encode` etc. causes a
        // NoCodecException. Need to investigate.
        "def json_encode(value):",
        "  return json.encode(value)",
        "def json_decode(text):",
        "  return json.decode(text)",
        "def save(name, object):",
        "  test.save(name, object)");
    scratch.file(
        "test/BUILD",
        "load('//test:test.bzl', 'test_library', 'json_decode', 'json_encode', 'save')", //
        "test_library(",
        "    name ='foo',",
        "    srcs = ['foo.cc'],",
        ")",
        "save('foo', json_decode(json_encode(existing_rule('foo'))))");
    scratch.file("test/foo.cc");
    getConfiguredTarget("//test:foo");
    // We test a subset of attributes after an encode-decode round trip because the rule also has
    // default attributes with default values, which will get encoded to json and which will change
    // whenever default attributes get introduced, making string comparison of encoded json fragile.
    Map<String, Object> jsonRoundTripValue =
        Dict.cast(
            getSaved("foo"), String.class, Object.class, "json round trip of existing_rule('foo')");
    assertThat(jsonRoundTripValue)
        .containsAtLeast(
            "name", "foo", "kind", "test_library", "srcs", StarlarkList.immutableOf(":foo.cc"));
  }

  @Test
  public void existingRules_returnsObjectWithCorrectMutability() throws Exception {
    scratch.file(
        "test/BUILD",
        "load('inc.bzl', 'f')", //
        "f()");
    scratch.file(
        "test/inc.bzl", //
        "def f():",
        "  native.config_setting(name='x', define_values={'key': 'value'})",
        "  rs = native.existing_rules()",
        "  rs['no_such_rule'] = {'name': 'no_such_rule', 'kind': 'config_setting'}"); // mutate

    assertThat(getConfiguredTarget("//test:BUILD")).isNotNull(); // no error on mutation
  }

  @Test
  public void existingRules_returnsDictLikeObject() throws Exception {
    scratch.file(
        "test/BUILD",
        "load('inc.bzl', 'f')", //
        "f()");
    scratch.file(
        "test/inc.bzl", //
        "def f():",
        "  native.config_setting(name='x', define_values={'key_x': 'value_x'})",
        "  native.config_setting(name='y', define_values={'key_y': 'value_y'})",
        "  rs = native.existing_rules()",
        "  print('rs == %s' % repr(rs))",
        "  test.save('[key for key in rs]', [key for key in rs])",
        "  test.save('list(rs)', list(rs))",
        "  test.save('rs.keys()', rs.keys())",
        "  test.save(\"[v['name'] for v in rs.values()]\", [v['name'] for v in rs.values()])",
        "  test.save(\"[(i[0], i[1]['name']) for i in rs.items()]\", [(i[0], i[1]['name']) for i in"
            + " rs.items()])",
        "  test.save(\"rs['x']['define_values']\", rs['x']['define_values'])",
        "  test.save(\"rs.get('x', {'name': 'z'})['name']\", rs.get('x', {'name': 'z'})['name'])",
        "  test.save(\"rs.get('invalid_rule', {'name': 'invalid_rule'})\", rs.get('invalid_rule',"
            + " {'name': 'invalid_rule'}))",
        "  test.save(\"'x' in rs\", 'x' in rs)",
        "  test.save(\"'invalid_rule' in rs\", 'invalid_rule' in rs)");

    assertThat(getConfiguredTarget("//test:BUILD")).isNotNull(); // no error
    assertThat(Starlark.toIterable(getSaved("[key for key in rs]"))).containsExactly("x", "y");
    assertThat(Starlark.toIterable(getSaved("list(rs)"))).containsExactly("x", "y");
    assertThat(Starlark.toIterable(getSaved("rs.keys()"))).containsExactly("x", "y");
    assertThat(Starlark.toIterable(getSaved("[v['name'] for v in rs.values()]")))
        .containsExactly("x", "y");
    assertThat(Starlark.toIterable(getSaved("[(i[0], i[1]['name']) for i in rs.items()]")))
        .containsExactly(Tuple.of("x", "x"), Tuple.of("y", "y"));
    assertThat(getSaved("rs['x']['define_values']"))
        .isEqualTo(Dict.builder().put("key_x", "value_x").buildImmutable());
    assertThat(getSaved("rs.get('x', {'name': 'z'})['name']")).isEqualTo("x");
    assertThat(getSaved("rs.get('invalid_rule', {'name': 'invalid_rule'})"))
        .isEqualTo(Dict.builder().put("name", "invalid_rule").buildImmutable());
    assertThat(getSaved("'x' in rs")).isEqualTo(true);
    assertThat(getSaved("'invalid_rule' in rs")).isEqualTo(false);
  }

  @Test
  public void existingRules_returnsSnapshotOfOnlyRulesInstantiatedUpToThatPoint() throws Exception {
    scratch.file(
        "test/BUILD",
        "load('inc.bzl', 'f')", //
        "f()");
    scratch.file(
        "test/inc.bzl", //
        "def f():",
        "  native.config_setting(name='x', define_values={'key_x': 'value_x'})",
        "  rs1 = native.existing_rules()",
        "  native.config_setting(name='y', define_values={'key_y': 'value_y'})",
        "  rs2 = native.existing_rules()",
        "  native.config_setting(name='z', define_values={'key_z': 'value_z'})",
        "  rs3 = native.existing_rules()",
        "  test.save('rs1.keys()', rs1.keys())",
        "  test.save('rs2.keys()', rs2.keys())",
        "  test.save('rs3.keys()', rs3.keys())");

    assertThat(getConfiguredTarget("//test:BUILD")).isNotNull(); // no error
    assertThat(Starlark.toIterable(getSaved("rs1.keys()"))).containsExactly("x");
    assertThat(Starlark.toIterable(getSaved("rs2.keys()"))).containsExactly("x", "y");
    assertThat(Starlark.toIterable(getSaved("rs3.keys()"))).containsExactly("x", "y", "z");
  }

  // Regression test for https://github.com/bazelbuild/bazel/issues/16256
  @Test
  public void existingRules_encodeToJson() throws Exception {
    // We need a Starlark rule - native rules can have attribute values that the json encoder
    // doesn't handle.
    scratch.file(
        "test/test.bzl",
        "def _dummy_impl(ctx):",
        "  pass",
        "test_library = rule(",
        "  implementation = _dummy_impl,",
        "  attrs = {'srcs': attr.label_list(allow_files = True)},",
        ")",
        // TODO(b/249397668): simplifying this to `json_encode = json.encode` etc. causes a
        // NoCodecException. Need to investigate.
        "def json_encode(value):",
        "  return json.encode(value)",
        "def json_decode(text):",
        "  return json.decode(text)",
        "def save(name, object):",
        "  test.save(name, object)");
    scratch.file(
        "test/BUILD",
        "load('//test:test.bzl', 'test_library', 'json_decode', 'json_encode', 'save')", //
        "test_library(",
        "    name ='foo',",
        "    srcs = ['foo.cc'],",
        ")",
        "test_library(",
        "    name ='bar',",
        "    srcs = ['bar.cc'],",
        ")",
        "save('rules', json_decode(json_encode(existing_rules())))");
    scratch.file("test/foo.cc");
    getConfiguredTarget("//test:bar");
    // We test a subset of attributes after an encode-decode round trip because the rule also has
    // default attributes with default values, which will get encoded to json and which will change
    // whenever default attributes get introduced, making string comparison of encoded json fragile.
    Dict<String, Object> jsonRoundTripRulesValue =
        Dict.cast(
            getSaved("rules"), String.class, Object.class, "json round trip of `existing_rules()`");
    assertThat(jsonRoundTripRulesValue.keySet()).containsExactly("foo", "bar");
    Map<String, Object> jsonRoundTripFooValue =
        Dict.cast(
            jsonRoundTripRulesValue.get("foo"),
            String.class,
            Object.class,
            "json round trip of `existing_rule('foo')`");
    assertThat(jsonRoundTripFooValue)
        .containsAtLeast(
            "name", "foo", "kind", "test_library", "srcs", StarlarkList.immutableOf(":foo.cc"));
    Map<String, Object> jsonRoundTripBarValue =
        Dict.cast(
            jsonRoundTripRulesValue.get("bar"),
            String.class,
            Object.class,
            "json round trip of `existing_rule('bar')`");
    assertThat(jsonRoundTripBarValue)
        .containsAtLeast(
            "name", "bar", "kind", "test_library", "srcs", StarlarkList.immutableOf(":bar.cc"));
  }

  /**
   * Tests for {@code native.existing_rule} and {@code native.existing_rules} Starlark functions
   * with the {@code --incompatible_existing_rules_immutable_view} flag set.
   */
  @RunWith(JUnit4.class)
  public static final class WithImmutableView extends NativeExistingRulesTest {

    @Override
    protected void setupOptions() throws Exception {
      setBuildLanguageOptions("--incompatible_existing_rules_immutable_view");
    }

    @Test
    @Override
    public void existingRule_returnsObjectWithCorrectMutability() throws Exception {
      scratch.file(
          "test/BUILD",
          "load('inc.bzl', 'f')", //
          "f()");
      scratch.file(
          "test/inc.bzl", //
          "def f():",
          "  native.config_setting(name='x', define_values={'key': 'value'})",
          "  r = native.existing_rule('x')",
          "  r['no_such_attribute'] = 123"); // mutate the view

      reporter.removeHandler(failFastHandler);
      assertThat(getConfiguredTarget("//test:BUILD")).isNull(); // mutation fails
      assertContainsEvent("can only assign an element in a dictionary or a list");
    }

    @Test
    @Override
    public void existingRules_returnsObjectWithCorrectMutability() throws Exception {
      scratch.file(
          "test/BUILD",
          "load('inc.bzl', 'f')", //
          "f()");
      scratch.file(
          "test/inc.bzl", //
          "def f():",
          "  native.config_setting(name='x', define_values={'key': 'value'})",
          "  rs = native.existing_rules()",
          "  rs['no_such_rule'] = {'name': 'no_such_rule', 'kind': 'config_setting'}"); // mutate

      reporter.removeHandler(failFastHandler);
      assertThat(getConfiguredTarget("//test:BUILD")).isNull(); // mutation fails
      assertContainsEvent("can only assign an element in a dictionary or a list");
    }

    @Test
    public void existingRules_returnsDeeplyImmutableView() throws Exception {
      scratch.file(
          "test/BUILD",
          "load('inc.bzl', 'f')", //
          "f()");
      scratch.file(
          "test/inc.bzl", //
          "def f():",
          "  native.config_setting(name='x', define_values={'key': 'value'})",
          "  rs = native.existing_rules()",
          "  rs['x']['define_values']['key'] = 123"); // mutate an attribute value within the view

      reporter.removeHandler(failFastHandler);
      assertThat(getConfiguredTarget("//test:BUILD")).isNull();
      assertContainsEvent("trying to mutate a frozen dict value");
    }
  }
}


text:
using System.Collections.Generic;

namespace GraphQLCore.Language.AST
{
    public class GraphQLFragmentSpread : ASTNode, IWithDirectives
    {
        public IEnumerable<GraphQLDirective> Directives { get; set; }

        public override ASTNodeKind Kind
        {
            get
            {
                return ASTNodeKind.FragmentSpread;
            }
        }

        public GraphQLName Name { get; set; }
    }
}


text:
namespace Dike.Core.UI.Inputs
{
    using System.Collections.Generic;

    /// <summary>
    /// Implement this interface to define input types.
    /// </summary>
    public interface IInputType
    {
        #region Properties

        /// <summary>
        /// Gets the attributes objects related to this input type.
        /// </summary>
        /// <value>The attributes objects related to this input type.</value>
        IDictionary<string, object> Attributes
        {
            get;
        }

        /// <summary>
        /// Gets the input type name.
        /// </summary>
        /// <value>The input type name.</value>
        string Name
        {
            get;
        }

        /// <summary>
        /// Gets or sets the validator.
        /// </summary>
        /// <value>The validator.</value>
        Runtime.Validation.IValueValidator Validator
        {
            get;
            set;
        }

        #endregion Properties

        #region Indexers

        /// <summary>
        /// Gets or sets the <see cref="object"/> with the specified key. Gets null if given key does not exists. This is a shortcut for <see cref="Attributes"/> dictionary.
        /// </summary>
        /// <param name="key">The key value of the object.</param>
        /// <returns>The object related to the key value.</returns>
        object this[string key]
        {
            get;
            set;
        }

        #endregion Indexers
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Tomaz Lovrec - Landing Pad</title>

    <link rel="stylesheet" href="/css/landingpad.css">

            {% include content with contentData %}


text:
set -e

# Usage
usage() {
    echo "Usage:"
    echo "    ${0} -c <host> -p <port> -A <username> -P <password> -b <GERRIT_PREFIX> -j <JENKINS_PREFIX> -k <KEY> -u <USER>"
    exit 1
}

# Constants
SLEEP_TIME=10

while getopts "c:p:A:P:b:j:k:u:" opt; do
  case $opt in
    c)
      host=${OPTARG}
      ;;
    p)
      port=${OPTARG}
      ;;
    A)
      username=${OPTARG}
      ;;
    P)
      password=${OPTARG}
      ;;
    b)
      gerrit_prefix=${OPTARG}
      ;;
    j)
      jenkins_prefix=${OPTARG}
      ;;
    k)
      key=${OPTARG}
      ;;
    u)
      user=${OPTARG}
      ;;
    *)
      echo "Invalid parameter(s) or option(s)."
      usage
      ;;
  esac
done

if [ -z "${host}" ] || [ -z "${port}" ] || [ -z "${username}" ] || [ -z "${password}" ] || [ -z "${gerrit_prefix}" ] || [ -z "${jenkins_prefix}" ] || [ -z "${key}" ] || [ -z "${user}" ]; then
    echo "Parameters missing"
    usage
fi

echo "Testing Jenkins Connection & Key Presence"
until curl -sL --output /dev/null --silent --write-out "%{http_code}\\n" \
    -u ${username}:${password} \
    "http://${host}:${port}/${jenkins_prefix}/userContent/${key}" -o /dev/null | grep "200" &> /dev/null
do
    echo "Jenkins or key unavailable, sleeping for ${SLEEP_TIME}"
    sleep "${SLEEP_TIME}"
done

echo "Retrieving value: ${key}"
ssh_key=$(curl -s -X GET -u ${username}:${password} "http://${host}:${port}/${jenkins_prefix}/userContent/${key}")

echo "Checking if \"${user}\" exists"
if curl -sL -w "%{http_code}\\n" "http://localhost:8080/${gerrit_prefix}/accounts/${user}" -o /dev/null | grep "404" &> /dev/null; then
    echo "User does not exist: ${user}"
    exit 1
fi

echo "*** Verify key already exists... Gerrit does not do this ..."
# Download the stored key and decode from to UTF-8 using echo -e the -n switch from echo allows to remove the trailing \n that echo would add.
# The decode part is necessary as Gerrit correctly encode the SSH key and as a result = sign is converted to \u003d
stored_key=$(echo -e $(curl -u ${username}:${password} --silent http://localhost:8080/${gerrit_prefix}/a/accounts/self/sshkeys | grep "ssh_public_key" | awk '{split($0, a, ": "); print a[2]}' | sed 's/[",]//g'))
echo "****** Found stored key, verify if is same are downloaded ..."
[[ "$stored_key" == "$ssh_key" ]] && exit 0 || echo "****** Stored key is not same as downloaded, uploading it ..."

echo "Uploading key to Gerrit user \"${user}\""
curl -X POST -u "${username}:${password}" -d "${ssh_key}" "http://localhost:8080/${gerrit_prefix}/a/accounts/${user}/sshkeys"


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Client</title>
    <link rel="stylesheet" href="node_modules/xterm/dist/xterm.css" />
    <link rel="stylesheet" href="node_modules/xterm/dist/addons/fullscreen/fullscreen.css" />


text:
module API
  module V1
    class UsersController < ApplicationController
      def index
        @users = User.active

        render json: Oj.dump(@users.as_json, mode: :compat)
      end

      def show
        # Looks up via id or rfid. Previous API used user_rfid.
        @user = User.where(id: params[:id]).or(User.where(rfid: params[:id])).sole
        render json: Oj.dump(@user.as_json, mode: :compat)
      end

      def create
        @user = User.new(user_params)

        if @user.save
          render json: Oj.dump(@user.as_json, mode: :compat), status: :created
        else
          render json: Oj.dump(@user.errors.to_json, mode: :compat), status: :unprocessible_entity
        end
      end

      protected

      def user_params
        params.require(:user).permit(:name, :email, :rfid)
      end
    end
  end
end


text:
@interface DoublePlayer : UIViewController{
    int p1_score;
    int p2_score;
    BOOL isClicked;
    //audio players
    AVAudioPlayer *ship_sunk_sound;
    AVAudioPlayer *final_victory_sound;
}

//ships for each player
@property (strong, nonatomic)NSMutableArray *ships_p1;
@property (strong, nonatomic)NSMutableArray *ships_p2;

//ship locations stored in NSValues
@property (strong, nonatomic)NSMutableDictionary *ship_to_loc_p1;
@property (strong, nonatomic)NSMutableDictionary *ship_to_loc_p2;

//ship locations stored in button index
@property (strong, nonatomic)NSMutableDictionary *ship_index_p1;
@property (strong, nonatomic)NSMutableDictionary *ship_index_p2;

//ship status
@property (strong, nonatomic)NSMutableArray *grid_button_p1;
@property (strong, nonatomic)NSMutableArray *grid_button_p2;

//missile image
@property (strong, nonatomic) IBOutlet UIImageView *p2_attack_p1;
@property (strong, nonatomic) IBOutlet UIImageView *p1_attack_p2;

@property (strong, nonatomic) IBOutlet UIButton *switch_turn_button;

//game state
@property (nonatomic)int turn;
@property (nonatomic)int p1_left;
@property (nonatomic)int p2_left;

//labels
@property (strong, nonatomic) IBOutlet UILabel *label_p1;
@property (strong, nonatomic) IBOutlet UILabel *label_p2;
@property (strong, nonatomic) IBOutlet UILabel *current_turn;
@property (strong, nonatomic) IBOutlet UILabel *game_info;

//grid
@property (strong, nonatomic) IBOutlet UIImageView *grid_p1;
@property (strong, nonatomic) IBOutlet UIImageView *grid_p2;
@property (strong, nonatomic) IBOutlet UIButton *placeDoneButton;

//five ships
@property (strong, nonatomic) IBOutlet UIButton *largeship_p1;
@property (strong, nonatomic) IBOutlet UIButton *mediumship_p1;
@property (strong, nonatomic) IBOutlet UIButton *smallship_p1;
@property (strong, nonatomic) IBOutlet UIButton *smallship2_p1;
@property (strong, nonatomic) IBOutlet UIButton *tinyship_p1;

@property (strong, nonatomic) IBOutlet UIButton *largeship_p2;
@property (strong, nonatomic) IBOutlet UIButton *mediumship_p2;
@property (strong, nonatomic) IBOutlet UIButton *smallship_p2;
@property (strong, nonatomic) IBOutlet UIButton *smallship2_p2;
@property (strong, nonatomic) IBOutlet UIButton *tinyship_p2;

@end


text:
import click
from parsec.cli import pass_context, json_loads
from parsec.decorators import custom_exception, json_output

@click.command('delete_history')
@click.argument("history_id", type=str)
@click.option(
    "--purge",
    help="if ``True``, also purge (permanently delete) the history",
    is_flag=True
)
@pass_context
@custom_exception
@json_output
def cli(ctx, history_id, purge=False):
    """Delete a history.

Output:

    An error object if an error occurred or a dictionary
                 containing: ``id`` (the encoded id of the history), ``deleted`` (if the
                 history was marked as deleted), ``purged`` (if the history was
                 purged).

        .. note::
          For the purge option to work, the Galaxy instance must have the
          ``allow_user_dataset_purge`` option set to ``true`` in the
          ``config/galaxy.yml`` configuration file.
    """
    return ctx.gi.histories.delete_history(history_id, purge=purge)


text:
package org.smartpony.provider.segment.actor

import java.util.UUID

import akka.actor.{Actor, ActorLogging}
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.{DateTimeZone, LocalDateTime}
import org.smartpony.common.message.Event
import org.smartpony.core.http.SynchronousHttp
import org.smartpony.provider.segment.actor.SegmentIo.SendEvent
import org.smartpony.common.message.format.json.EventProtocol._
import spray.json.DefaultJsonProtocol._
import spray.json._
import SegmentIo._

class SegmentIo extends Actor with ActorLogging {

  private implicit val t = jsonFormat7(Track)
  private implicit val i = jsonFormat6(Identify)

  def receive = {
    case se @ SendEvent(e @ Event("identify", _, _), client, path, headers, _) => dispatch(se, client, path + "identify", asIdentify(e), headers)
    case se @ SendEvent(e @ Event("track", _, _), client, path, headers, _) => dispatch(se, client, path + "track", asTrack(e), headers)
    case _ => sys.error("SegmentIo dispatch actor received unsupported message")
  }

  private def dispatch(send: SendEvent, httpClient: SynchronousHttp, path: String,
                       content: String, headers: Seq[(String, String)]) = {
    try {
      var requestId: String = null
      if (log.isDebugEnabled) {
        requestId = UUID.randomUUID.toString
        log.debug(s"Attempting to send $content to $path - request id is $requestId")
      }

      //Ref: https://segment.com/docs/libraries/http/
      val response = httpClient.postJson(path, content, headers:_*) //TODO: Send timeout and failure message to parent actor

      if (log.isDebugEnabled) {
        log.debug(s"$requestId resulted in " + response)
      }
    } catch {
      case x: java.net.SocketTimeoutException => sender ! SegmentIoTimeoutError(send.e, path, send.attempt)
      case x: Exception => sender ! SegmentIoClientError(send.e, path, send.attempt, x)
    }

  }

  private def asIdentify(e: Event) = Identify(e.userIdentifier.value, e.attributes).toJson.compactPrint
  private def asTrack(e: Event) = Track(e.userIdentifier.value, e.subEvent.get.toString, e.withoutSubEvent).toJson.compactPrint

}

private case class Track(userId: String, event: String, properties: Map[String, Any],
                         timestamp: String = utcTime(), messageId: String = newId(),
                         `type`: String = "track", context: Map[String, Map[String, String]] = Context)

private case class Identify(userId: String, traits: Map[String, Any],
                            timestamp: String = utcTime(), messageId: String = newId(),
                            `type`: String = "identify", context: Map[String, Map[String, String]] = Context)

object SegmentIo {

  val Context = Map("library" -> Map("name" -> "smart-pony", "version" -> "0.1"))

  def utcTime() = {
    val ldt = LocalDateTime.now
    val dt = ldt.toDateTime(DateTimeZone.UTC)
    ISODateTimeFormat.dateTime().print(dt)
  }

  def newId() = UUID.randomUUID().toString

  case class SendEvent(e: Event, httpClient: SynchronousHttp,
                       hostPath: String, headers: Seq[(String, String)],
                       attempt: Int)
  case class SegmentIoTimeoutError(event: Event, hostPath: String, attempt: Int)
  case class SegmentIoClientError(event: Event, hostPath: String, attempt: Int, ex: Exception)

}


text:
var map = function() {
    var logEntry = this;
    emit(logEntry.Country,
        { count: 1, size: logEntry.Size });
};

var reduce = function(key, values) {
    var result = { count: 0, totalMinutes: 0 };

    values.forEach(function(value) {
        result.count += value.count;
        result.size += value.size;
    });

    return result;
};

db.logs.mapReduce(map, reduce, { out: 'log_result' });
db.log_result.find();


text:
This function is a simple binary_printer formated.

It can separate the bits in groups and can take several numbers
to print

### Format Codes
- `%c` = char to print (one byte)
- `%i` = int to print (four bytes)
- `%d` = delimiter in group (must be a char, defaults to `' '`)
- `%g` = number of bits in one group (must be a number)
- `%D` = delimiter for each binary string (must be a char)
 	if `%D` is not present, `%d` will be used as delimiter for a binary string
 	to avoid this, `%p` should the first letter for the string

#### Return Codes
- 1 if any memory error
- 0 if success


text:
type AnyFn = (...args: any[]) => any;

/**
 * Curry one or more functions, where all must returned falsy values
*/
export function not<T extends AnyFn>(...fns: T[]): T {
    return function _not(...args) {
        return fns.every((fn) => !fn(...args));
    } as T;
}

/**
 * Curry one or more functions, where all must returned truthy values
*/
export function and<T extends AnyFn>(...fns: T[]): T {
    return function _and(...args) {
        return fns.every((fn) => fn(...args));
    } as T;
}

/**
 * Curry one or more functions, where one must returned a truthy value
*/
export function or<T extends AnyFn>(...fns: T[]): T {
    return function _or(...args) {
        return fns.some((fn) => fn(...args));
    } as T;
}


text:
Labb 4
======

##	The Return of the Graph
![Return of the Graph](graph.jpg)

	One Graph to rule them all, One Graph to find them,
	One Graph to bring them all and in the darkness bind them

![finally](http://www.quickmeme.com/img/c2/c2192f9c1e4c9eb5c17e1f24affe37eb67c08459f991487cc19016e1c660cd73.jpg)


text:
const assert = require('yeoman-assert')
const helpers = require('yeoman-test')
const h = require('../../test-helper')
require('chai').should()

describe('service', () => {
  it('generates expected files', done => {
    helpers.run(__dirname)
      .withArguments(['name'])
      .on('end', function () {
        const file = 'app/services/Name.js'
        assert.file(file)
        assert.fileContent(file, 'factory(\'NameService\', ')
        h.eslintCheck(this, [file])
        done()
      })
    .on('error', done)
  })
})


text:
<?php

namespace BingAds\AdIntelligence;

/**
 * Defines an object that you use to specify the start and end dates of a date range.
 * @link http://msdn.microsoft.com/en-us/library/hh921738(v=msads.90).aspx DayMonthAndYear Data Object
 */
final class DayMonthAndYear
{
    /**
     * The day of the month.
     * @var int
     */
    public $Day;

    /**
     * The month specified as an integer value in the range of 1 through 12, where 1 is January and 12 is December.
     * @var int
     */
    public $Month;

    /**
     * The year specified as a four-digit integer value.
     * @var int
     */
    public $Year;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Diagnostics;

namespace Core.Utilities
{
    public class LoadSaver<T> where T : LoadSaver<T>
    {
        protected Action OnLoadStart;
        protected Action OnLoadEnd;
        protected Action OnSaveStart;
        protected Action OnSaveEnd;

        [XmlIgnore]
        public String Path;

        [XmlIgnore]
        public Boolean CreateOnFileNotExists;

        public LoadSaver()
        {
            Path = String.Empty;
            CreateOnFileNotExists = false;

            OnLoadStart = null;
            OnLoadEnd = null;
            OnSaveStart = null;
            OnSaveEnd = null;
        }

        public static void Save(ref T t)
        {
            if (t != null)
            {
                if (t.OnSaveStart != null)
                {
                    t.OnSaveStart();
                }

                var serializer = new XmlSerializer(typeof(T));
                var writer = new StreamWriter(t.Path);
                serializer.Serialize(writer, t);
                writer.Close();

                if (t.OnSaveEnd != null)
                {
                    t.OnSaveEnd();
                }
            }
        }

        public static void Load(ref T t)
        {
            if (t != null)
            {
                String tPath = t.Path;
                if (File.Exists(tPath))
                {
                    if (t.OnLoadStart != null)
                    {
                        t.OnLoadStart();
                    }

                    StreamReader reader = null;
                    try
                    {
                        var deserializer = new XmlSerializer(typeof(T));
                        reader = new StreamReader(tPath);
                        t = (T)deserializer.Deserialize(reader);
                        t.Path = tPath;

                        if (t.OnLoadEnd != null)
                        {
                            t.OnLoadEnd();
                        }
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        throw ex;
#else
                        File.WriteAllText(DateTime.Now.Ticks.ToString(), ex.Message);
#endif
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                }
                else if (t.CreateOnFileNotExists)
                {
                    Save(ref t);
                }
            }
        }
    }
}


text:
use base::monster::Monster;
use types::monster::{StatType, LevelType, StatIndividualType};
use types::species::{StatBaseType, StatYieldType};
use gen::monster::Nature;

pub fn calculate_health(monster: &Monster) -> StatType
{
	let base = monster.base_health() as f32;
	let iv = monster.individual_health() as f32;
	let level = monster.level() as f32;
	let ev = monster.yield_health() as f32;
	((((2_f32 * base + iv + (ev / 4_f32)) * level) / 100_f32) + level + 10_f32).trunc() as StatType
}

fn calculate_stat(base: StatBaseType, iv: StatIndividualType, ev: StatYieldType, level: LevelType, bonus: f32)
	-> StatType
{
	let stat = ((((2_f32 * base as f32 + iv as f32 + (ev as f32 / 4_f32)) * level as f32) /
		100_f32) + 5_f32).trunc();
	(stat * bonus).trunc() as StatType
}

fn nature_bonus_attack(nature: Nature) -> f32
{
	match nature
	{
		Nature::Lonely | Nature::Brave | Nature::Adamant | Nature::Naughty => 1.1f32,
		Nature::Bold | Nature::Timid | Nature::Modest | Nature::Calm => 0.9f32,
		_ => 1.0f32
	}
}

fn nature_bonus_defense(nature: Nature) -> f32
{
	match nature
	{
		Nature::Bold | Nature::Impish | Nature::Lax | Nature::Relaxed => 1.1f32,
		Nature::Lonely | Nature::Mild | Nature::Gentle | Nature::Hasty => 0.9f32,
		_ => 1.0f32
	}
}

fn nature_bonus_spattack(nature: Nature) -> f32
{
	match nature
	{
		Nature::Modest | Nature::Mild | Nature::Rash | Nature::Quiet => 1.1f32,
		Nature::Adamant | Nature::Impish | Nature::Careful | Nature::Jolly => 0.9f32,
		_ => 1.0f32
	}
}

fn nature_bonus_spdefense(nature: Nature) -> f32
{
	match nature
	{
		Nature::Calm | Nature::Gentle | Nature::Careful | Nature::Sassy => 1.1f32,
		Nature::Naughty | Nature::Lax | Nature::Rash | Nature::Naive => 0.9f32,
		_ => 1.0f32
	}
}

fn nature_bonus_speed(nature: Nature) -> f32
{
	match nature
	{
		Nature::Timid | Nature::Hasty | Nature::Jolly | Nature::Naive => 1.1f32,
		Nature::Brave | Nature::Relaxed | Nature::Quiet | Nature::Sassy => 0.9f32,
		_ => 1.0f32
	}
}

pub fn calculate_attack(monster: &Monster) -> StatType
{
	calculate_stat(monster.base_attack(), monster.individual_attack(),
		monster.yield_attack(), monster.level(), nature_bonus_attack(monster.nature()))
}

pub fn calculate_defense(monster: &Monster) -> StatType
{
	calculate_stat(monster.base_defense(), monster.individual_defense(),
		monster.yield_defense(), monster.level(), nature_bonus_defense(monster.nature()))
}

pub fn calculate_spattack(monster: &Monster) -> StatType
{
	calculate_stat(monster.base_spattack(), monster.individual_spattack(),
		monster.yield_spattack(), monster.level(), nature_bonus_spattack(monster.nature()))
}

pub fn calculate_spdefense(monster: &Monster) -> StatType
{
	calculate_stat(monster.base_spdefense(), monster.individual_spdefense(),
		monster.yield_spdefense(), monster.level(), nature_bonus_spdefense(monster.nature()))
}

pub fn calculate_speed(monster: &Monster) -> StatType
{
	calculate_stat(monster.base_speed(), monster.individual_speed(),
		monster.yield_speed(), monster.level(), nature_bonus_speed(monster.nature()))
}


text:
package com.streamsets.pipeline.lib.io;

import com.streamsets.pipeline.lib.executor.SafeScheduledExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * The file DirectoryPathCreationWatcher is used to watch for paths yet to be created.
 *

 * If {@link #scanIntervalSecs} greater than 0, this will spawn another thread to look for paths.
 *
 * Use {@link #find()} to get newly foundPaths.
 */
public class DirectoryPathCreationWatcher{
  private static final Logger LOGGER = LoggerFactory.getLogger(DirectoryPathCreationWatcher.class);

  private final Collection<Path> pathsWatched = Collections.synchronizedCollection(new TreeSet<Path>());
  private final ConcurrentLinkedQueue<Path> foundPathsQueue = new ConcurrentLinkedQueue<Path>();
  private final int scanIntervalSecs;
  private final Runnable finder;

  private ScheduledExecutorService executor = null;

  public DirectoryPathCreationWatcher(Collection<Path> paths, int scanIntervalSecs){
    this.scanIntervalSecs = scanIntervalSecs;
    pathsWatched.addAll(paths);
    finder = new Runnable() {
      @Override
      public void run() {
        synchronized (pathsWatched) {
          Iterator<Path> dirPathIterator = pathsWatched.iterator();
          while (dirPathIterator.hasNext()) {
            Path dirPath = dirPathIterator.next();
            if (Files.exists(dirPath) && Files.isDirectory(dirPath)) {
              foundPathsQueue.offer(dirPath);
              dirPathIterator.remove();
              LOGGER.debug("Found Path : {}", dirPath.toAbsolutePath().toString());
            }
          }
        }
      }
    };

    //Start finding the directory in the background.
    if (scanIntervalSecs > 0) {
      executor = new SafeScheduledExecutorService(1, "Directory Creation Watcher");
      executor.scheduleWithFixedDelay(finder, 0, scanIntervalSecs, TimeUnit.SECONDS);
    }
  }

  public Set<Path> find() {
    //During Synchronous run.
    if (scanIntervalSecs == 0) {
      finder.run();
    }

    Set<Path> foundPaths = new HashSet<Path>();
    Path detectedPath;
    while ( (detectedPath = foundPathsQueue.poll()) != null) {
      foundPaths.add(detectedPath);
    }

    if (pathsWatched.isEmpty()) {
      LOGGER.debug("All Directory Paths are found");
      close();
    }
    return foundPaths;
  }

  public void close() {
    if (executor != null) {
      LOGGER.debug("Directory Creation Watcher - Closing");
      executor.shutdownNow();
      executor = null;
    }
  }
}


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

namespace Azure.ResourceManager.Compute.Models
{
    /// <summary> The publishing profile of a gallery image Version. </summary>
    public partial class GalleryImageVersionPublishingProfile : GalleryArtifactPublishingProfileBase
    {
        /// <summary> Initializes a new instance of GalleryImageVersionPublishingProfile. </summary>
        public GalleryImageVersionPublishingProfile()
        {
        }

        /// <summary> Initializes a new instance of GalleryImageVersionPublishingProfile. </summary>
        /// <param name="targetRegions"> The target regions where the Image Version is going to be replicated to. This property is updatable. </param>
        /// <param name="replicaCount"> The number of replicas of the Image Version to be created per region. This property would take effect for a region when regionalReplicaCount is not specified. This property is updatable. </param>
        /// <param name="excludeFromLatest"> If set to true, Virtual Machines deployed from the latest version of the Image Definition won't use this Image Version. </param>
        /// <param name="publishedOn"> The timestamp for when the gallery image version is published. </param>
        /// <param name="endOfLifeOn"> The end of life date of the gallery image version. This property can be used for decommissioning purposes. This property is updatable. </param>
        /// <param name="storageAccountType"> Specifies the storage account type to be used to store the image. This property is not updatable. </param>
        /// <param name="replicationMode"> Optional parameter which specifies the mode to be used for replication. This property is not updatable. </param>
        /// <param name="targetExtendedLocations"> The target extended locations where the Image Version is going to be replicated to. This property is updatable. </param>
        internal GalleryImageVersionPublishingProfile(IList<TargetRegion> targetRegions, int? replicaCount, bool? excludeFromLatest, DateTimeOffset? publishedOn, DateTimeOffset? endOfLifeOn, ImageStorageAccountType? storageAccountType, GalleryReplicationMode? replicationMode, IList<GalleryTargetExtendedLocation> targetExtendedLocations) : base(targetRegions, replicaCount, excludeFromLatest, publishedOn, endOfLifeOn, storageAccountType, replicationMode, targetExtendedLocations)
        {
        }
    }
}