text:
<?php

namespace DigitalOcean\Tests\CLI\Droplets;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use DigitalOcean\Tests\TestCase;
use DigitalOcean\CLI\Droplets\ResetRootPasswordCommand;

/**
 * @author Antoine Corcy <contact@sbin.dk>
 */
class ResetRootPasswordCommandTest extends TestCase
{
    protected $application;
    protected $command;
    protected $commandTester;

    protected function setUp()
    {
        $this->application = new Application();

        $result = (object) array(
            'status'   => 'OK',
            'event_id' => 1234,
        );

        $ResetRootPasswordCommand = $this->getMock(
            '\DigitalOcean\CLI\Droplets\ResetRootPasswordCommand', array('getDigitalOcean'));
        $ResetRootPasswordCommand
            ->expects($this->any())
            ->method('getDigitalOcean')
            ->will($this->returnValue(
                $this->getMockDigitalOcean('droplets', $this->getMockDroplets('resetRootPassword', $result))));

        $this->application->add($ResetRootPasswordCommand);

        $this->command = $this->application->find('droplets:reset-root-password');

        $this->commandTester = new CommandTester($this->command);
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Not enough arguments.
     */
    public function testExecuteNotEnoughArguments()
    {
        $this->commandTester->execute(array(
            'command' => $this->command->getName(),
        ));
    }

    public function testExecuteCheckStatusConfirmed()
    {
        $dialog = $this->getDialogAskConfirmation(true);
        $this->command->getHelperSet()->set($dialog, 'dialog');

        $this->commandTester->execute(array(
            'command' => $this->command->getName(),
            'id'      => 123,
        ));

        $this->assertTrue(is_string($this->commandTester->getDisplay()));
        $this->assertRegExp('/\| OK     \|/', $this->commandTester->getDisplay());
    }

    public function testExecuteCheckEventIdConfirmed()
    {
        $dialog = $this->getDialogAskConfirmation(true);
        $this->command->getHelperSet()->set($dialog, 'dialog');

        $this->commandTester->execute(array(
            'command' => $this->command->getName(),
            'id'      => 123,
        ));

        $this->assertTrue(is_string($this->commandTester->getDisplay()));
        $this->assertRegExp('/\| 1234     \|/', $this->commandTester->getDisplay());
    }

    public function testExecuteCheckStatusNotConfirmed()
    {
        $dialog = $this->getDialogAskConfirmation(false);
        $this->command->getHelperSet()->set($dialog, 'dialog');

        $this->commandTester->execute(array(
            'command' => $this->command->getName(),
            'id'      => 123,
        ));

        $this->assertTrue(is_string($this->commandTester->getDisplay()));
        $this->assertRegExp('/Aborted!/', $this->commandTester->getDisplay());
    }

    public function testExecuteCheckEventIdNotConfirmed()
    {
        $dialog = $this->getDialogAskConfirmation(false);
        $this->command->getHelperSet()->set($dialog, 'dialog');

        $this->commandTester->execute(array(
            'command' => $this->command->getName(),
            'id'      => 123,
        ));

        $this->assertTrue(is_string($this->commandTester->getDisplay()));
        $this->assertRegExp('/Aborted!/', $this->commandTester->getDisplay());
    }
}


text:
(function () {

  'use strict';

  MyOD.module('DatasetsModule', function (DatasetsModule, App, Backbone, Marionette, $, _) {

    DatasetsModule.View = Marionette.ItemView.extend({

      initialize: function (options) {
        _.bindAll(this, 'changeAttribute', 'changeRamp');
        this.mapManager = options.mapManager;
      },

      template: JST['datasets/templates/dataset'],

      id: 'page-dataset',

      ui: {
        'mapDiv': '#map',
        'tableContainer': '#table-container'
      },

      modelEvents: {
        'change': 'render'
      },

      templateHelpers: function () {
        var baseUrl = this.model.url().replace(/.json$/, '').replace('/api/v2', '');
        var thumbnailUrl = this.model.get('thumbnailUrl');
        var defaultThumbnailUrl = 'images/default-dataset-thumb.png';
        return {
          baseUrl: baseUrl,
          thumbnailSrc: thumbnailUrl || defaultThumbnailUrl
        };
      },

      onRender: function () {
        //TODO: refactor to use regions...
        this.tableView = new DatasetsModule.TableView({ el: this.ui.tableContainer, model: this.model }).render();
      },

      // onShow: function () {
      //   console.debug('onShow');
      // },

      onDomRefresh: function () {
        if (this.model.get('itemType').toLowerCase() !== 'table') {
          var self = this;
          // TODO: would be nice to encapsulate this in mapmanager so consumers wouldn't have to know to do it
          this.ui.mapDiv.show();
          this.mapManager.dojoReady.done(function () {
            self.mapManager.createMap('map', { coords: self.model.get('extent').coordinates });
            self.mapManager.addDataset(self.model);

            //self.initSmaps();
          });
        }
      },

      initSmaps: function (basemap) {
        var numerics = this.model.getNumericFields();

        if (numerics.length){

          // select the first attr to map
          // we could put some logic around which to use here
          this.fieldName = this.fieldName || numerics[0].name;

          //get stats for selected attribute
          var fields = this.model.get('fields');
          this.stats = this.getStats(fields, this.fieldName);
          this.type = this.getGeometryType(this.model.get('geometryType'));

          var yukiOptions = {
            fields: numerics,
            field: this.fieldName,
            statistics: this.stats,
            type: this.type,
            schemes: this.getSchemes()
          };

          if (!this.yuki) {
            this.yuki = new Yuki('smaps', yukiOptions);
          } else {
            $('#yuki-viz-tools').remove();
            this.yuki = new Yuki('smaps', yukiOptions);
          }

          // EVENT Handlers from yuki
          this.yuki.on('change', this.changeAttribute);
          this.yuki.on('ramp-change', this.changeRamp);

          this._execStyleMap();
        }

      },

      getStats: function (fields, fieldName) {
        var fieldObj = _.findWhere(fields, { name: fieldName });
        return fieldObj ? fieldObj.statistics : null;
      },

      getGeometryType: function (geomType) {
        switch (geomType) {
          case 'esriGeometryPoint':
          case 'esriGeometryMultipoint':
            return 'point';
          case 'esriGeometryPolyline':
            return 'line';
          case 'esriGeometryPolygon':
            return 'polygon';
          default:
            return geomType.toLowerCase();
        }
      },

      getSchemes: function (){
        var theme, styleType, self = this;
        switch (this.type){
          case 'point':
            theme = 'default';
            styleType = 'size';
            break;
          case 'polygon':
            theme = 'high-to-low';
            styleType = 'choropleth';
            break;
        }

        //TODO: move this into mapmanager
        return esri.styles[styleType].getSchemes({
          theme: theme,
          basemap: 'dark-gray',
          geometryType: self.type
        });
      },

      // handler for attr change
      changeAttribute: function (fieldName) {
        //update stats for selected attribute
        var fields = this.model.get('fields');
        this.stats = this.getStats(fields, fieldName);
        this.fieldName = fieldName;

        this._execStyleMap(this.selectedScheme);
      },

      // handler for ramp UI change
      changeRamp: function (index) {
        this.selectedScheme = this.getSchemes().secondarySchemes[index];
        this._execStyleMap(this.selectedScheme);
      },

      //update the map in mapmanager
      _execStyleMap: function (scheme) {
        var self = this;

        var opts = {
          field: this.fieldName,
          basemap: 'dark-gray',
          statistics: this.stats,
          type: this.type
        };

        if (scheme){
          opts.scheme = scheme;
        }

        var foo = App.reqres.request('smaps:update:style', opts)
          .done(function(renderer){
            if (self.type === 'point'){
              self.yuki.buildPointLegend(renderer.breaks);
            }
          });
      },

      onDestroy: function () {
        this.mapManager.destroy();
        this.tableView.destroy();
      }

    });

  });

})();

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="puli-grid.css" type="text/css" media="screen" />

            1


text:
import {TransactionType} from '../base/enum';
import {Global} from '../base/global';
import {TaskPriority} from '../base/private_enum';
import {Resolver} from '../base/resolver';
import {PayloadType, Row} from '../base/row';
import {Service} from '../base/service';
import {UniqueId} from '../base/unique_id';
import {RuntimeIndex} from '../index/runtime_index';
import {BaseTable} from '../schema/base_table';
import {DatabaseSchema} from '../schema/database_schema';
import {Table} from '../schema/table';

import {Relation} from './relation';
import {RelationEntry} from './relation_entry';
import {Task} from './task';

export class ExportTask extends UniqueId implements Task {
  private schema: DatabaseSchema;
  private scope: Set<Table>;
  private resolver: Resolver<Relation[]>;

  constructor(private global: Global) {
    super();
    this.schema = global.getService(Service.SCHEMA);
    this.scope = new Set<Table>(this.schema.tables());
    this.resolver = new Resolver<Relation[]>();
  }

  // Grabs contents from the cache and exports them as a plain object.
  execSync(): PayloadType {
    const indexStore = this.global.getService(Service.INDEX_STORE);
    const cache = this.global.getService(Service.CACHE);

    const tables: PayloadType = {};
    (this.schema.tables() as BaseTable[]).forEach(table => {
      const rowIds = (
        indexStore.get(table.getRowIdIndexName()) as RuntimeIndex
      ).getRange();
      const payloads = cache.getMany(rowIds).map(row => (row as Row).payload());
      tables[table.getName()] = payloads;
    });

    return {
      name: this.schema.name(),
      tables,
      version: this.schema.version(),
    };
  }

  exec(): Promise<Relation[]> {
    const results = this.execSync();
    const entry = new RelationEntry(new Row(Row.DUMMY_ID, results), true);

    return Promise.resolve([new Relation([entry], [])]);
  }

  getType(): TransactionType {
    return TransactionType.READ_ONLY;
  }

  getScope(): Set<Table> {
    return this.scope;
  }

  getResolver(): Resolver<Relation[]> {
    return this.resolver;
  }

  getId(): number {
    return this.getUniqueNumber();
  }

  getPriority(): TaskPriority {
    return TaskPriority.EXPORT_TASK;
  }
}


text:
package org.jboss.elasticsearch.river.sysinfo.mgm;

import java.util.concurrent.atomic.AtomicReferenceArray;

import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.transport.DummyTransportAddress;
import org.elasticsearch.river.RiverName;
import org.elasticsearch.threadpool.ThreadPool;
import org.jboss.elasticsearch.river.sysinfo.IRiverMgm;
import org.jboss.elasticsearch.river.sysinfo.SysinfoRiver;
import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.JRLifecycleCommand;
import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.JRLifecycleRequest;
import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.JRLifecycleResponse;
import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.NodeJRLifecycleRequest;
import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.NodeJRLifecycleResponse;
import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.TransportJRLifecycleAction;
import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.TransportJRLifecycleActionTest;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

/**
 * Unit test for {@link TransportJRMgmBaseAction}.
 *
 * @author Vlastimil Elias (velias at redhat dot com)
 */
public class TransportJRMgmBaseActionTest {

	private static final String RIVER_NAME = "myRiver";
	protected static final ClusterName clusterName = TransportJRLifecycleActionTest.clusterName;
	DiscoveryNode dn = new DiscoveryNode("aa", DummyTransportAddress.INSTANCE, Version.CURRENT);
	DiscoveryNode dn2 = new DiscoveryNode("aa2", DummyTransportAddress.INSTANCE, Version.CURRENT);

	@Test
	public void constructor() {
		TransportJRLifecycleAction tested = TransportJRLifecycleActionTest.prepareTestedInstance(clusterName);
		Assert.assertNotNull(tested.logger);
		Assert.assertEquals(
				"org.elasticsearch.org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.TransportJRLifecycleAction",
				tested.logger.getName());
	}

	@Test
	public void newResponse() {
		TransportJRLifecycleAction tested = TransportJRLifecycleActionTest.prepareTestedInstance(clusterName);

		{
			AtomicReferenceArray<NodeJRLifecycleResponse> responses = new AtomicReferenceArray<NodeJRLifecycleResponse>(0);
			JRLifecycleResponse res = tested.newResponse(null, responses);
			Assert.assertEquals(clusterName, res.getClusterName());
			Assert.assertEquals(0, res.getNodes().length);
		}

		{
			AtomicReferenceArray<NodeJRLifecycleResponse> responses = new AtomicReferenceArray<NodeJRLifecycleResponse>(
					new NodeJRLifecycleResponse[] { new NodeJRLifecycleResponse(dn), new NodeJRLifecycleResponse(dn2) });
			JRLifecycleResponse res = tested.newResponse(null, responses);
			Assert.assertEquals(clusterName, res.getClusterName());
			Assert.assertEquals(2, res.getNodes().length);
		}

	}

	@Test
	public void executor() {
		TransportJRLifecycleAction tested = TransportJRLifecycleActionTest.prepareTestedInstance(clusterName);
		Assert.assertEquals(ThreadPool.Names.MANAGEMENT, tested.executor());
	}

	@Test
	public void accumulateExceptions() {
		TransportJRLifecycleAction tested = TransportJRLifecycleActionTest.prepareTestedInstance(clusterName);
		Assert.assertEquals(false, tested.accumulateExceptions());
	}

	@Test
	public void nodeOperation() {
		SysinfoRiver.clearRunningInstances();

		IRiverMgm jiraRiverMock = Mockito.mock(IRiverMgm.class);
		RiverName riverName = new RiverName("sysinfo", RIVER_NAME);
		Mockito.when(jiraRiverMock.riverName()).thenReturn(riverName);
		SysinfoRiver.addRunningInstance(jiraRiverMock);
		try {
			TransportJRLifecycleAction tested = TransportJRLifecycleActionTest.prepareTestedInstance(clusterName);

			Mockito.reset(jiraRiverMock);
			{
				NodeJRLifecycleRequest nodeRequest = new NodeJRLifecycleRequest("ndid", new JRLifecycleRequest("unknownRiver",
						JRLifecycleCommand.STOP));
				NodeJRLifecycleResponse resp = tested.nodeOperation(nodeRequest);
				Assert.assertNotNull(resp);
				Assert.assertFalse(resp.riverFound);
				Mockito.verifyZeroInteractions(jiraRiverMock);
			}

			Mockito.reset(jiraRiverMock);
			{
				NodeJRLifecycleRequest nodeRequest = new NodeJRLifecycleRequest("ndid", new JRLifecycleRequest(RIVER_NAME,
						JRLifecycleCommand.STOP));
				NodeJRLifecycleResponse resp = tested.nodeOperation(nodeRequest);
				Assert.assertNotNull(resp);
				Assert.assertTrue(resp.riverFound);
				Mockito.verify(jiraRiverMock).stop();
				Mockito.verifyNoMoreInteractions(jiraRiverMock);
			}
		} finally {
			SysinfoRiver.clearRunningInstances();
		}
	}

}


text:
// The MIT License (MIT)

// Copyright (c) 2015 Ben Abelshausen

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

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

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using GTFS.Entities;
using System;
using System.Collections.Generic;

namespace GTFS.Filters
{
    /// <summary>
    /// Represents a GTFS feed filter that leaves only data related to the given routes.
    /// </summary>
    public class GTFSFeedRoutesFilter : GTFSFeedFilter
    {
        /// <summary>
        /// Holds the routes filter function.
        /// </summary>
        private Func<Route, bool> _routesFilter;

        /// <summary>
        /// Creates a new routes filter.
        /// </summary>
        /// <param name="routesFilter"></param>
        public GTFSFeedRoutesFilter(Func<Route, bool> routesFilter)
        {
            _routesFilter = routesFilter;
        }

        /// <summary>
        /// Creates a new routes filter.
        /// </summary>
        /// <param name="routeIds"></param>
        public GTFSFeedRoutesFilter(HashSet<string> routeIds)
        {
            _routesFilter = (r) => routeIds.Contains(r.Id);
        }

        /// <summary>
        /// Filters the given feed and returns a filtered version.
        /// </summary>
        /// <param name="feed"></param>
        /// <returns></returns>
        public override IGTFSFeed Filter(IGTFSFeed feed)
        {
            var filteredFeed = new GTFSFeed();

            // filter routes.
            var routeIds = new HashSet<string>();
            var agencyIds = new HashSet<string>();
            foreach (var route in feed.Routes)
            {
                if (_routesFilter.Invoke(route))
                { // keep this route.
                    filteredFeed.Routes.Add(route);
                    routeIds.Add(route.Id);

                    // keep agency ids.
                    agencyIds.Add(route.AgencyId);
                }
            }

            // filter trips.
            var serviceIds = new HashSet<string>();
            var tripIds = new HashSet<string>();
            var shapeIds = new HashSet<string>();
            foreach (var trip in feed.Trips)
            {
                if (routeIds.Contains(trip.RouteId))
                { // keep this trip, it is related to at least one stop-time.
                    filteredFeed.Trips.Add(trip);
                    tripIds.Add(trip.Id);

                    // keep serviceId, routeId and shapeId.
                    serviceIds.Add(trip.ServiceId);
                    if (!string.IsNullOrWhiteSpace(trip.ShapeId))
                    {
                        shapeIds.Add(trip.ShapeId);
                    }
                }
            }

            // filter stop-times.
            var stopIds = new HashSet<string>();
            foreach (var stopTime in feed.StopTimes)
            {
                if (tripIds.Contains(stopTime.TripId))
                { // stop is included, keep this stopTime.
                    filteredFeed.StopTimes.Add(stopTime);

                    // save the trip id's to keep.
                    stopIds.Add(stopTime.StopId);
                }
            }

            // filter stops.
            foreach (var stop in feed.Stops)
            {
                if (stopIds.Contains(stop.Id))
                { // stop has to be included.
                    stopIds.Add(stop.Id);
                    filteredFeed.Stops.Add(stop);
                }
            }

            // filter agencies.
            foreach (var agency in feed.Agencies)
            {
                if (agencyIds.Contains(agency.Id))
                { // keep this agency.
                    filteredFeed.Agencies.Add(agency);
                }
            }

            // filter calendars.
            foreach (var calendar in feed.Calendars)
            {
                if (serviceIds.Contains(calendar.ServiceId))
                { // keep this calendar.
                    filteredFeed.Calendars.Add(calendar);
                }
            }

            // filter calendar-dates.
            foreach (var calendarDate in feed.CalendarDates)
            {
                if (serviceIds.Contains(calendarDate.ServiceId))
                { // keep this calendarDate.
                    filteredFeed.CalendarDates.Add(calendarDate);
                }
            }

            // filter fare rules.
            var fareIds = new HashSet<string>();
            foreach (var fareRule in feed.FareRules)
            {
                if (routeIds.Contains(fareRule.RouteId))
                { // keep this fare rule.
                    filteredFeed.FareRules.Add(fareRule);

                    // keep fare ids.
                    fareIds.Add(fareRule.FareId);
                }
            }

            // filter fare attributes.
            foreach (var fareAttribute in feed.FareAttributes)
            {
                if (fareIds.Contains(fareAttribute.FareId))
                { // keep this fare attribute.
                    filteredFeed.FareAttributes.Add(fareAttribute);
                }
            }

            // filter frequencies.
            foreach (var frequency in feed.Frequencies)
            {
                if (tripIds.Contains(frequency.TripId))
                { // keep this frequency.
                    filteredFeed.Frequencies.Add(frequency);
                }
            }

            foreach (var transfer in feed.Transfers)
            {
                if (stopIds.Contains(transfer.FromStopId) &&
                    stopIds.Contains(transfer.ToStopId))
                {
                    filteredFeed.Transfers.Add(transfer);
                }
            }
            return filteredFeed;
        }
    }
}


text:
layout: post
title: "I couldn't predict what happen..."
---
I couldn't predict what happened at my work today.


text:
module ProteusCli
  module ExternalHostCommands
    def define_root(cmd)
      cmd.define_command do
        name        'external'
        usage       'external [options]'
        summary     'manage external host dns records'
        desc = 'Create/find/delete external host records in proteus. External records are '
        desc += 'just internal proteus representations of someone else\'s dns record.  They are '
        desc += 'required (for example) to create a CNAME to an AWS load balancer.  The load balancer '
        desc += 'A record would be an "external record" in that case.'
        description desc
      end
    end

    def define_sub(cmd)
      cmd.define_command do
        name    'add'
        usage   'add [options] external [properties]'
        summary 'add an external host record'
        desc = 'Adds an external record.  The only required argument is the record itself.  Properties '
        desc += 'are optional and are a string of key value pairs. ie. "foo=bar|baz=biz|buz=boz"'
        description desc

        option :r, :properties, 'Properties to send to proteus on creation', argument: :required

        run do |opts, args|
          exit_2 'External record add requires 1 or more args' unless args.size >= 1
          configure(opts)
          opts[:properties] ||= ''
          ap proteus { |c| c.add_external_host_record(args[0], opts[:properties]) }
        end
      end

      cmd.define_command do
        name 'delete'
        usage   'delete [options] fqdn'
        summary 'delete an external record'

        run do |opts, args|
          exit_2 'External delete requires 1 args' unless args.size == 1
          configure(opts)
          $stdout.puts 'success' if proteus { |c| c.delete_external_record(args[0]) }.nil?
        end
      end

      cmd.define_command do
        name    'search'
        usage   'search [options] term'
        summary 'searches for an external host records'
        desc = 'Searches for host dns records by keyword only. This is the only option for external '
        desc += 'records from the proteus API.'
        description desc

        option :l, :limit, 'How many records to return (max: 10, default: 10)', argument: :required
        option :s, :start, 'Which record to start with, ie. offset (default: 0)', argument: :required

        run do |opts, args|
          exit_2 'Host search requires 1 args' unless args.size == 1
          configure(opts)
          opts[:start] ||= 0
          opts[:limit] ||= 10
          ap proteus { |c| c.search_by_object_types(args[0], Proteus::Types::EXTERNALHOST, opts[:start], opts[:limit]) }
        end
      end

      cmd.define_command do
        name    'show'
        usage   'show [options] fqdn'
        summary 'show an external host record'

        run do |opts, args|
          exit_2 'Host add requires 1 args' unless args.size == 1
          configure(opts)
          ap proteus { |c| c.get_entity_by_name(@config.viewid, args[0], Proteus::Types::EXTERNALHOST) }
        end
      end

      cmd.define_command do
        name    'udf'
        usage   'udf'
        summary 'list user defined fields for external host records'
        flag :r, :required, 'Only return required user defined fields'

        run do |opts, _|
          configure(opts)
          opts[:required] ||= false
          proteus do |c|
            type = Proteus::Types::EXTERNALHOST
            ap Hash[c.get_user_defined_fields(type, opts[:required]).collect { |u| [u.name, u.type] }]
          end
        end
      end
    end
  end
end


text:
<?php

namespace Sausin\Signere;

use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher;

class SignereServiceProvider extends ServiceProvider
{
    use EventMap;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        // $this->registerEvents();
        $this->registerRoutes();
        $this->defineAssetPublishing();
    }

    /**
     * Register the Signere job events.
     *
     * @return void
     */
    protected function registerEvents()
    {
        $events = $this->app->make(Dispatcher::class);

        foreach ($this->events as $event => $listeners) {
            foreach ($listeners as $listener) {
                $events->listen($event, $listener);
            }
        }
    }

    /**
     * Register the Signere routes.
     *
     * @return void
     */
    protected function registerRoutes()
    {
        Route::group([
            'prefix' => 'signere',
            'namespace' => 'Sausin\Signere\Http\Controllers',
            'middleware' => 'api',
        ], function () {
            $this->loadRoutesFrom(__DIR__.'/../routes/api.php');
        });
    }

    /**
     * Define the asset publishing configuration.
     *
     * @return void
     */
    public function defineAssetPublishing()
    {
        $this->publishes([
            SIGNERE_PATH.'/public' => public_path('vendor/signere'),
        ], 'signere-assets');
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if (! defined('SIGNERE_PATH')) {
            define('SIGNERE_PATH', realpath(__DIR__.'/../'));
        }

        $this->configure();
        $this->registerCommands();
        $this->registerBindings();
        $this->offerPublishing();
    }

    /**
     * Setup the configuration for Signere.
     *
     * @return void
     */
    protected function configure()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../config/signere.php',
            'signere'
        );
    }

    /**
     * Registers the commands available with this package.
     *
     * @return void
     */
    protected function registerCommands()
    {
        if ($this->app->runningInConsole()) {
            // register the console command
            $this->commands([Console\RenewCommand::class]);
        }
    }

    /**
     * Register the bindings.
     *
     * @return void
     */
    protected function registerBindings()
    {
        $this->app->bind('signere-headers', function () {
            return new Headers(config());
        });
        $this->app->alias('signere-headers', Facades\SignereHeaders::class);

        $classes = [
            'ApiKey',
            'Document',
            'DocumentConvert',
            'DocumentFile',
            'DocumentJob',
            'DocumentProvider',
            'Events',
            'ExternalLogin',
            'ExternalSign',
            'Form',
            'Invoice',
            'Message',
            'Receiver',
            'RequestId',
            'Statistics',
            'Status',
        ];

        // get the environment of the application
        $env = is_null(config('signere.mode')) ? $this->app->environment() : config('signere.mode');

        foreach ($classes as $class) {
            $this->app->when('Sausin\Signere\\'.$class)
                        ->needs('$environment')
                        ->give($env);
        }
    }

    /**
     * Setup the resource publishing groups for Signere.
     *
     * @return void
     */
    protected function offerPublishing()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__.'/../config/signere.php' => config_path('signere.php'),
            ], 'signere-config');
        }
    }
}


text:
@interface NSObject (HJBMySometimesUnsafeCategory)

- (void)hjb_mySometimesUnsafeMethod;

@end


text:
ROOTDIR ?= ../..

include $(ROOTDIR)/Makefile.defaults

awa_tags_dir=$(ROOTDIR)/plugins/awa-tags
awa_tags_dynamo=--package AWA.Tags.Models db ../../uml/awa.zargo
awa_tags_install_dirs=config db web

$(eval $(call awa_plugin,awa_tags))


text:
package org.elasticsearch.action.admin.indices.template.put;

import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.metadata.MetaDataIndexTemplateService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Put index template action.
 */
public class TransportPutIndexTemplateAction extends TransportMasterNodeOperationAction<PutIndexTemplateRequest, PutIndexTemplateResponse> {

    private final MetaDataIndexTemplateService indexTemplateService;

    @Inject
    public TransportPutIndexTemplateAction(Settings settings, TransportService transportService, ClusterService clusterService,
                                           ThreadPool threadPool, MetaDataIndexTemplateService indexTemplateService) {
        super(settings, transportService, clusterService, threadPool);
        this.indexTemplateService = indexTemplateService;
    }

    @Override
    protected String executor() {
        return ThreadPool.Names.MANAGEMENT;
    }

    @Override
    protected String transportAction() {
        return PutIndexTemplateAction.NAME;
    }

    @Override
    protected PutIndexTemplateRequest newRequest() {
        return new PutIndexTemplateRequest();
    }

    @Override
    protected PutIndexTemplateResponse newResponse() {
        return new PutIndexTemplateResponse();
    }

    @Override
    protected ClusterBlockException checkBlock(PutIndexTemplateRequest request, ClusterState state) {
        return state.blocks().indexBlockedException(ClusterBlockLevel.METADATA, "");
    }

    @Override
    protected PutIndexTemplateResponse masterOperation(PutIndexTemplateRequest request, ClusterState state) throws ElasticSearchException {
        String cause = request.cause();
        if (cause.length() == 0) {
            cause = "api";
        }

        final AtomicReference<PutIndexTemplateResponse> responseRef = new AtomicReference<PutIndexTemplateResponse>();
        final AtomicReference<Throwable> failureRef = new AtomicReference<Throwable>();
        final CountDownLatch latch = new CountDownLatch(1);
        indexTemplateService.putTemplate(new MetaDataIndexTemplateService.PutRequest(request.cause(), request.name())
                .template(request.template())
                .order(request.order())
                .settings(request.settings())
                .mappings(request.mappings())
                .create(request.create()),

                new MetaDataIndexTemplateService.PutListener() {
                    @Override
                    public void onResponse(MetaDataIndexTemplateService.PutResponse response) {
                        responseRef.set(new PutIndexTemplateResponse(response.acknowledged()));
                        latch.countDown();
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        failureRef.set(t);
                        latch.countDown();
                    }
                });

        try {
            latch.await();
        } catch (InterruptedException e) {
            failureRef.set(e);
        }

        if (failureRef.get() != null) {
            if (failureRef.get() instanceof ElasticSearchException) {
                throw (ElasticSearchException) failureRef.get();
            } else {
                throw new ElasticSearchException(failureRef.get().getMessage(), failureRef.get());
            }
        }

        return responseRef.get();
    }
}


text:
using UnityEngine;
using System.Collections;

public class CatOk : MonoBehaviour {
    public GameObject bw;
    private BoxCollider bc;
    private Renderer rd;

	void Start () {
        bc = bw.gameObject.transform.GetComponent<BoxCollider>();
        rd = bw.gameObject.transform.GetComponent<Renderer>();
        bc.isTrigger = false;
	}

    void Update()
    {

    }

    void OnTriggerStay(Collider col)
    {
        if(col.gameObject.tag == "Cat")
        {
            rd.enabled = false;
            bc.isTrigger = true;
        }
    }
    void OnTriggerExit(Collider col)
    {
        if(col.gameObject.tag == "Cat")
        {
            rd.enabled = false;
            bc.isTrigger = false;
        }
    }
}


text:
package com.kstruct.markdown.utils;

import org.junit.Assert;
import org.junit.Test;

import java.nio.file.Paths;

public class MarkdownUtilsTest {
    @Test
    public void isMarkdownIndexPage() {
        Assert.assertTrue(MarkdownUtils.isMarkdownIndexPage(Paths.get("index.md")));
        Assert.assertFalse(MarkdownUtils.isMarkdownIndexPage(Paths.get("fooindex.md")));
    }
}


text:
/*
 * File:   SequenceManager.hpp
 * Author: Arthur Lisek-Koper <deathvango@gmail.com>
 *
 * Created on February 2, 2015, 10:57 PM
 */

#ifndef SEQUENCEMANAGER_HPP
#define	SEQUENCEMANAGER_HPP

#include "../core/Includes.hpp"
#include "Sequence.hpp"

/*
 * Class Description here
 */
class SequenceManager {
public:
    ///Default Constructor provided by Netbeans.
    SequenceManager();

    ///Default Copy-constructor provided by Netbeans.
    SequenceManager(const SequenceManager& orig);

    ///Default Destructor provided by Netbeans.
    virtual ~SequenceManager();

    ///Create a new sequence of the given frameType. If
    ///the given sequence was previously created, then
    ///and error flag is given.
	void createNewSequence( frameType action );

	///Returns a reference to the requested sequence.
	///Use only if you intend to alter the sequence's
	///options.
	Sequence* getSequence( int index ) { return &mSequenceList[index]; }

	///Begin the given sequence.
	void startSequence( frameType action );

	///Exit the current sequence and begin default sequence.
	void endCurrentSequence( );

	///Returns the currently playing sequence.
	frameType getCurrentSequence() { return mCurrentSequence; }

	///Is the current sequence fully complete? returns true if it is,
	///false otherwise.
	bool isSequenceComplete();

	float getTimeSinceStart() { mTimer.getElapsedTime(); }

	SequenceManager& operator=( const SequenceManager& other );

private:

	frameType mCurrentSequence;

	///Contains sequence information for each frameType.
	Sequence mSequenceList[ etoi( frameType::FRAME_COUNT ) ];

	///Used to manage how much time has elapsed since a sequence
	///has begun.
	Clock mTimer;

};

#endif	/* SEQUENCEMANAGER_HPP */


text:
from subprocess import Popen, PIPE
import re

def __get_ikalog_version():
    try:
        commit_id = Popen(["git", "rev-parse", "--short", "HEAD"], stdout=PIPE).communicate()[0].decode('utf-8')
        return re.sub(r'\s+', r'', commit_id)
    except:
        return 'unknown'

IKALOG_VERSION =  __get_ikalog_version()


text:
require 'rspec'

require_relative '../lib/holiday_scraper'


text:
package com.enhancer.model;

import javax.persistence.*;

/**
 * @author PRITAM. Created for Hibernate ORM mapping with table.
 *
 */
@Entity
@Table(name = "wordlist")
public class Wordlist implements Comparable<Wordlist> {

	@Id
	private int sequence;
	private String words;

	public int getSequence() {
		return sequence;
	}

	public void setSequence(int sequence) {
		this.sequence = sequence;
	}

	public String getWords() {
		return words.toLowerCase().trim();
	}

	public void setWords(String words) {
		this.words = words;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + sequence;
		result = prime * result + ((words == null) ? 0 : words.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Wordlist other = (Wordlist) obj;
		if (sequence != other.sequence)
			return false;
		if (words == null) {
			if (other.words != null)
				return false;
		} else if (!words.equals(other.words))
			return false;
		return true;
	}

	@Override
	public int compareTo(Wordlist o) {
		return (int) (this.words.compareTo(o.words));
	}

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Diagnostics;
using System.Globalization;

namespace System.Data
{
    internal enum ValueType
    {
        Unknown = -1,
        Null = 0,
        Bool = 1,
        Numeric = 2,
        Str = 3,
        Float = 4,
        Decimal = 5,
        Object = 6,
        Date = 7,
    }
    /// <summary>
    ///     ExpressionParser: expression node types
    /// </summary>
    internal enum Nodes
    {
        Noop = 0,
        Unop = 1,       /* Unary operator */
        UnopSpec = 2,   /* Special unop: IFF does not eval args */
        Binop = 3,      /* Binary operator */
        BinopSpec = 4,  /* Special binop: BETWEEN, IN does not eval args */
        Zop = 5,        /* "0-ary operator" - intrinsic constant. */
        Call = 6,       /* Function call or rhs of IN or IFF */
        Const = 7,      /* Constant value */
        Name = 8,       /* Identifier */
        Paren = 9,      /* Parentheses */
        Conv = 10,      /* Type conversion */
    }

    internal sealed class ExpressionParser
    {
        /// <summary>
        ///     Operand situations for parser
        /// </summary>
        private const int Empty = 0;  /* There was no previous operand */
        private const int Scalar = 1; /* The previous operand was a constant or id */
        private const int Expr = 2;   /* The previous operand was a complex expression */

        private readonly struct ReservedWords
        {
            internal readonly string _word;      // the word
            internal readonly Tokens _token;
            internal readonly int _op;

            internal ReservedWords(string word, Tokens token, int op)
            {
                _word = word;
                _token = token;
                _op = op;
            }
        }

        // this should be maintained as a invariantculture sorted array for binary searching
        private static readonly ReservedWords[] s_reservedwords = new ReservedWords[] {
            new ReservedWords("And", Tokens.BinaryOp, Operators.And),
            /*
            the following operator is not implemented in the current version of the
            Expression language, but we need to add them to the Reserved words list
            to prevent future compatibility problems.
            */
            new ReservedWords("Between", Tokens.BinaryOp, Operators.Between),

            new ReservedWords("Child", Tokens.Child, Operators.Noop),
            new ReservedWords("False", Tokens.ZeroOp, Operators.False),
            new ReservedWords("In", Tokens.BinaryOp, Operators.In),
            new ReservedWords("Is", Tokens.BinaryOp, Operators.Is),
            new ReservedWords("Like", Tokens.BinaryOp, Operators.Like),
            new ReservedWords("Not", Tokens.UnaryOp, Operators.Not),
            new ReservedWords("Null", Tokens.ZeroOp, Operators.Null),
            new ReservedWords("Or", Tokens.BinaryOp, Operators.Or),
            new ReservedWords("Parent", Tokens.Parent, Operators.Noop),
            new ReservedWords("True", Tokens.ZeroOp, Operators.True),
        };

        /* the following is the Scanner local configuration, Default settings is US
         * CONSIDER: should we read the user (or system) local settings?
         * CONSIDER: make this configurable by the user, and system locale for the string compare
         */
        private char _escape = '\\';
        private char _decimalSeparator = '.';
        //not used: private char ThousandSeparator = ',';
        private char _listSeparator = ',';
        //not used: private char DateSeparator = '/';
        private char _exponentL = 'e';
        private char _exponentU = 'E';

        internal char[] _text;
        internal int _pos = 0;
        internal int _start = 0;
        internal Tokens _token;
        internal int _op = Operators.Noop;

        internal OperatorInfo[] _ops = new OperatorInfo[MaxPredicates];
        internal int _topOperator = 0;
        internal int _topNode = 0;

        private readonly DataTable _table;

        private const int MaxPredicates = 100;
        internal ExpressionNode[] _nodeStack = new ExpressionNode[MaxPredicates];

        internal int _prevOperand;

        internal ExpressionNode _expression = null;

        internal ExpressionParser(DataTable table)
        {
            _table = table;
        }

        internal void LoadExpression(string data)
        {
            int length;

            if (data == null)
            {
                length = 0;
                _text = new char[length + 1];
            }
            else
            {
                length = data.Length;
                _text = new char[length + 1];
                data.CopyTo(0, _text, 0, length);
            }

            _text[length] = '\0';

            if (_expression != null)
            {
                // free all nodes
                _expression = null;
            }
        }

        internal void StartScan()
        {
            _op = Operators.Noop;
            _pos = 0;
            _start = 0;

            _topOperator = 0;
            _ops[_topOperator++] = new OperatorInfo(Nodes.Noop, Operators.Noop, Operators.priStart);
        }

        // CONSIDER: configure the scanner : local info

        internal ExpressionNode Parse()
        {
            // free all nodes
            _expression = null;

            StartScan();

            int cParens = 0;
            OperatorInfo opInfo;

            while (_token != Tokens.EOS)
            {
            loop:
                Scan();

                switch (_token)
                {
                    case Tokens.EOS:
                        // End of string: must be operand; force out expression;
                        // check for bomb; check nothing left on stack.

                        if (_prevOperand == Empty)
                        {
                            if (_topNode == 0)
                            {
                                // we have an empty expression
                                break;
                            }
                            // set error missing operator
                            // read the last operator info
                            opInfo = _ops[_topOperator - 1];

                            throw ExprException.MissingOperand(opInfo);
                        }
                        // collect all nodes
                        BuildExpression(Operators.priLow);
                        if (_topOperator != 1)
                        {
                            throw ExprException.MissingRightParen();
                        }
                        break;

                    case Tokens.Name:
                    case Tokens.Parent:
                    case Tokens.Numeric:
                    case Tokens.Decimal:
                    case Tokens.Float:
                    case Tokens.StringConst:
                    case Tokens.Date:
                        ExpressionNode node = null;
                        string str = null;

                        /* Constants and identifiers: create leaf node */

                        if (_prevOperand != Empty)
                        {
                            // set error missing operator
                            throw ExprException.MissingOperator(new string(_text, _start, _pos - _start));
                        }

                        if (_topOperator > 0)
                        {
                            // special check for IN without parentheses

                            opInfo = _ops[_topOperator - 1];

                            if (opInfo._type == Nodes.Binop && opInfo._op == Operators.In && _token != Tokens.Parent)
                            {
                                throw ExprException.InWithoutParentheses();
                            }
                        }

                        _prevOperand = Scalar;

                        switch (_token)
                        {
                            case Tokens.Parent:
                                string relname;
                                string colname;

                                // parsing Parent[(relation_name)].column_name)
                                try
                                {
                                    // expecting an '(' or '.'
                                    Scan();
                                    if (_token == Tokens.LeftParen)
                                    {
                                        //read the relation name
                                        ScanToken(Tokens.Name);
                                        relname = NameNode.ParseName(_text, _start, _pos);
                                        ScanToken(Tokens.RightParen);
                                        ScanToken(Tokens.Dot);
                                    }
                                    else
                                    {
                                        relname = null;
                                        CheckToken(Tokens.Dot);
                                    }
                                }
                                catch (Exception e) when (Common.ADP.IsCatchableExceptionType(e))
                                {
                                    throw ExprException.LookupArgument();
                                }

                                ScanToken(Tokens.Name);
                                colname = NameNode.ParseName(_text, _start, _pos);

                                opInfo = _ops[_topOperator - 1];
                                node = new LookupNode(_table, colname, relname);

                                break;

                            case Tokens.Name:
                                /* Qualify name now for nice error checking */

                                opInfo = _ops[_topOperator - 1];

                                /* Create tree element -                */
                                // CONSIDER: Check for reserved proc names here
                                node = new NameNode(_table, _text, _start, _pos);

                                break;

                            case Tokens.Numeric:
                                str = new string(_text, _start, _pos - _start);
                                node = new ConstNode(_table, ValueType.Numeric, str);
                                break;
                            case Tokens.Decimal:
                                str = new string(_text, _start, _pos - _start);
                                node = new ConstNode(_table, ValueType.Decimal, str);
                                break;
                            case Tokens.Float:
                                str = new string(_text, _start, _pos - _start);
                                node = new ConstNode(_table, ValueType.Float, str);
                                break;
                            case Tokens.StringConst:
                                Debug.Assert(_text[_start] == '\'' && _text[_pos - 1] == '\'', "The expression contains an invalid string constant");
                                Debug.Assert(_pos - _start > 1, "The expression contains an invalid string constant");
                                // Store string without quotes..
                                str = new string(_text, _start + 1, _pos - _start - 2);
                                node = new ConstNode(_table, ValueType.Str, str);
                                break;
                            case Tokens.Date:
                                Debug.Assert(_text[_start] == '#' && _text[_pos - 1] == '#', "The expression contains invalid date constant.");
                                Debug.Assert(_pos - _start > 2, "The expression contains invalid date constant '{0}'.");
                                // Store date without delimiters(#s)..
                                str = new string(_text, _start + 1, _pos - _start - 2);
                                node = new ConstNode(_table, ValueType.Date, str);
                                break;
                            default:
                                Debug.Fail("unhandled token");
                                break;
                        }

                        NodePush(node);
                        goto loop;

                    case Tokens.LeftParen:
                        cParens++;
                        if (_prevOperand == Empty)
                        {
                            // Check for ( following IN/IFF. if not, we have a normal (.
                            // Peek: take a look at the operators stack

                            Debug.Assert(_topOperator > 0, "Empty operator stack!!");
                            opInfo = _ops[_topOperator - 1];

                            if (opInfo._type == Nodes.Binop && opInfo._op == Operators.In)
                            {
                                /* IN - handle as procedure call */

                                node = new FunctionNode(_table, "In");
                                NodePush(node);
                                /* Push operator decriptor */
                                _ops[_topOperator++] = new OperatorInfo(Nodes.Call, Operators.Noop, Operators.priParen);
                            }
                            else
                            {  /* Normal ( */
                                /* Push operator decriptor */
                                _ops[_topOperator++] = new OperatorInfo(Nodes.Paren, Operators.Noop, Operators.priParen);
                            }
                        }
                        else
                        {
                            // This is a procedure call or () qualification
                            // Force out any dot qualifiers; check for bomb

                            BuildExpression(Operators.priProc);
                            _prevOperand = Empty;
                            ExpressionNode nodebefore = NodePeek();

                            if (nodebefore == null || nodebefore.GetType() != typeof(NameNode))
                            {
                                // this is more like an assert, so we not care about "nice" exception text..
                                throw ExprException.SyntaxError();
                            }

                            /* Get the proc name */
                            NameNode name = (NameNode)NodePop();

                            // Make sure that we can bind the name as a Function
                            // then get the argument count and types, and parse arguments..

                            node = new FunctionNode(_table, name._name);

                            // check to see if this is an aggregate function
                            Aggregate agg = (Aggregate)(int)((FunctionNode)node).Aggregate;
                            if (agg != Aggregate.None)
                            {
                                node = ParseAggregateArgument((FunctionId)(int)agg);
                                NodePush(node);
                                _prevOperand = Expr;
                                goto loop;
                            }

                            NodePush(node);
                            _ops[_topOperator++] = new OperatorInfo(Nodes.Call, Operators.Noop, Operators.priParen);
                        }
                        goto loop;

                    case Tokens.RightParen:
                        {
                            /* Right parentheses: Build expression if we have an operand. */
                            if (_prevOperand != Empty)
                            {
                                BuildExpression(Operators.priLow);
                            }

                            /* We must have Tokens.LeftParen on stack. If no operand, must be procedure call. */
                            if (_topOperator <= 1)
                            {
                                // set error, syntax: too many right parens..
                                throw ExprException.TooManyRightParentheses();
                            }

                            Debug.Assert(_topOperator > 1, "melformed operator stack.");
                            _topOperator--;
                            opInfo = _ops[_topOperator];

                            if (_prevOperand == Empty && opInfo._type != Nodes.Call)
                            {
                                // set error, syntax: missing operand.
                                throw ExprException.MissingOperand(opInfo);
                            }

                            Debug.Assert(opInfo._priority == Operators.priParen, "melformed operator stack.");

                            if (opInfo._type == Nodes.Call)
                            {
                                /* add argument to the function call. */

                                if (_prevOperand != Empty)
                                {
                                    // read last function argument
                                    ExpressionNode argument = NodePop();

                                    /* Get the procedure name and append argument */
                                    Debug.Assert(_topNode > 0 && NodePeek().GetType() == typeof(FunctionNode), "The function node should be created on '('");

                                    FunctionNode func = (FunctionNode)NodePop();
                                    func.AddArgument(argument);
                                    func.Check();
                                    NodePush(func);
                                }
                            }
                            else
                            {
                                /* Normal parentheses: create tree node */
                                // Construct & Put the Nodes.Paren node on node stack
                                node = NodePop();
                                node = new UnaryNode(_table, Operators.Noop, node);
                                NodePush(node);
                            }

                            _prevOperand = Expr;
                            cParens--;
                            goto loop;
                        }
                    case Tokens.ListSeparator:
                        {
                            /* Comma encountered: Must be operand; force out subexpression */

                            if (_prevOperand == Empty)
                            {
                                throw ExprException.MissingOperandBefore(",");
                            }

                            /* We are be in a procedure call */

                            /* build next argument */
                            BuildExpression(Operators.priLow);

                            opInfo = _ops[_topOperator - 1];

                            if (opInfo._type != Nodes.Call)
                                throw ExprException.SyntaxError();

                            ExpressionNode argument2 = NodePop();

                            /* Get the procedure name */

                            FunctionNode func = (FunctionNode)NodePop();

                            func.AddArgument(argument2);

                            NodePush(func);

                            _prevOperand = Empty;

                            goto loop;
                        }
                    case Tokens.BinaryOp:
                        if (_prevOperand == Empty)
                        {
                            /* Check for unary plus/minus */
                            if (_op == Operators.Plus)
                            {
                                _op = Operators.UnaryPlus;
                                // fall through to UnaryOperator;
                            }
                            else if (_op == Operators.Minus)
                            {
                                /* Unary minus */
                                _op = Operators.Negative;
                                // fall through to UnaryOperator;
                            }
                            else
                            {
                                // Error missing operand:
                                throw ExprException.MissingOperandBefore(Operators.ToString(_op));
                            }
                        }
                        else
                        {
                            _prevOperand = Empty;

                            /* CNSIDER: If we are going to support BETWEEN Translate AND to special BetweenAnd if it is. */

                            /* Force out to appropriate precedence; push operator. */

                            BuildExpression(Operators.Priority(_op));

                            // PushOperator descriptor
                            _ops[_topOperator++] = new OperatorInfo(Nodes.Binop, _op, Operators.Priority(_op));
                            goto loop;
                        }
                        goto
                    case Tokens.UnaryOp; // fall through to UnaryOperator;

                    case Tokens.UnaryOp:
                        /* Must be no operand. Push it. */
                        _ops[_topOperator++] = new OperatorInfo(Nodes.Unop, _op, Operators.Priority(_op));
                        goto loop;

                    case Tokens.ZeroOp:
                        // check the we have operator on the stack
                        if (_prevOperand != Empty)
                        {
                            // set error missing operator
                            throw ExprException.MissingOperator(new string(_text, _start, _pos - _start));
                        }

                        // PushOperator descriptor
                        _ops[_topOperator++] = new OperatorInfo(Nodes.Zop, _op, Operators.priMax);
                        _prevOperand = Expr;
                        goto loop;

                    case Tokens.Dot:
                        //if there is a name on the stack append it.
                        ExpressionNode before = NodePeek();

                        if (before != null && before.GetType() == typeof(NameNode))
                        {
                            Scan();

                            if (_token == Tokens.Name)
                            {
                                NameNode nameBefore = (NameNode)NodePop();
                                string newName = nameBefore._name + "." + NameNode.ParseName(_text, _start, _pos);
                                NodePush(new NameNode(_table, newName));
                                goto loop;
                            }
                        }
                        // fall through to default
                        goto default;
                    default:
                        throw ExprException.UnknownToken(new string(_text, _start, _pos - _start), _start + 1);
                }
            }
            goto end_loop;
        end_loop:
            Debug.Assert(_topNode == 1 || _topNode == 0, "Invalid Node Stack");
            _expression = _nodeStack[0];

            return _expression;
        }

        /// <summary>
        /// Parse the argument to an Aggregate function. The syntax is
        ///      Func(child[(relation_name)].column_name)
        /// When the function is called we have already parsed the Aggregate name, and open paren
        /// </summary>
        private ExpressionNode ParseAggregateArgument(FunctionId aggregate)
        {
            Debug.Assert(_token == Tokens.LeftParen, "ParseAggregateArgument(): Invalid argument, token <> '('");

            bool child;
            string relname;
            string colname;

            Scan();

            try
            {
                if (_token != Tokens.Child)
                {
                    if (_token != Tokens.Name)
                        throw ExprException.AggregateArgument();

                    colname = NameNode.ParseName(_text, _start, _pos);
                    ScanToken(Tokens.RightParen);
                    return new AggregateNode(_table, aggregate, colname);
                }

                child = (_token == Tokens.Child);
                _prevOperand = Scalar;

                // expecting an '(' or '.'
                Scan();

                if (_token == Tokens.LeftParen)
                {
                    //read the relation name
                    ScanToken(Tokens.Name);
                    relname = NameNode.ParseName(_text, _start, _pos);
                    ScanToken(Tokens.RightParen);
                    ScanToken(Tokens.Dot);
                }
                else
                {
                    relname = null;
                    CheckToken(Tokens.Dot);
                }

                ScanToken(Tokens.Name);
                colname = NameNode.ParseName(_text, _start, _pos);
                ScanToken(Tokens.RightParen);
            }
            catch (Exception e) when (Common.ADP.IsCatchableExceptionType(e))
            {
                throw ExprException.AggregateArgument();
            }
            return new AggregateNode(_table, aggregate, colname, !child, relname);
        }

        /// <summary>
        ///     NodePop - Pop an operand node from the node stack.
        /// </summary>
        private ExpressionNode NodePop()
        {
            Debug.Assert(_topNode > 0, "NodePop(): Corrupted node stack");
            ExpressionNode node = _nodeStack[--_topNode];
            Debug.Assert(null != node, "null NodePop");
            return node;
        }

        /// <summary>
        ///     NodePeek - Peek at the top node.
        /// </summary>
        private ExpressionNode NodePeek()
        {
            if (_topNode <= 0)
                return null;

            return _nodeStack[_topNode - 1];
        }

        /// <summary>
        ///     Push an operand node onto the node stack
        /// </summary>
        private void NodePush(ExpressionNode node)
        {
            Debug.Assert(null != node, "null NodePush");

            if (_topNode >= MaxPredicates - 2)
            {
                throw ExprException.ExpressionTooComplex();
            }
            _nodeStack[_topNode++] = node;
        }

        /// <summary>
        ///     Builds expression tree for higher-precedence operator to be used as left
        ///     operand of current operator. May cause errors - always do ErrorCheck() upin return.
        /// </summary>

        private void BuildExpression(int pri)
        {
            ExpressionNode expr = null;

            Debug.Assert(pri > Operators.priStart && pri <= Operators.priMax, "Invalid priority value");

            /* For all operators of higher or same precedence (we are always
            left-associative) */
            while (true)
            {
                Debug.Assert(_topOperator > 0, "Empty operator stack!!");
                OperatorInfo opInfo = _ops[_topOperator - 1];

                if (opInfo._priority < pri)
                    goto end_loop;

                Debug.Assert(opInfo._priority >= pri, "Invalid prioriry value");
                _topOperator--;

                ExpressionNode nodeLeft;
                ExpressionNode nodeRight;
                switch (opInfo._type)
                {
                    case Nodes.Binop:
                        {
                            // get right, left operands. Bind them.

                            nodeRight = NodePop();
                            nodeLeft = NodePop();

                            /* This is the place to do type and other checks */

                            switch (opInfo._op)
                            {
                                case Operators.Between:
                                case Operators.BetweenAnd:
                                case Operators.BitwiseAnd:
                                case Operators.BitwiseOr:
                                case Operators.BitwiseXor:
                                case Operators.BitwiseNot:
                                    throw ExprException.UnsupportedOperator(opInfo._op);

                                case Operators.Is:
                                case Operators.Or:
                                case Operators.And:
                                case Operators.EqualTo:
                                case Operators.NotEqual:
                                case Operators.Like:
                                case Operators.LessThen:
                                case Operators.LessOrEqual:
                                case Operators.GreaterThen:
                                case Operators.GreaterOrEqual:
                                case Operators.In:
                                    break;

                                default:
                                    Debug.Assert(opInfo._op == Operators.Plus ||
                                                 opInfo._op == Operators.Minus ||
                                                 opInfo._op == Operators.Multiply ||
                                                 opInfo._op == Operators.Divide ||
                                                 opInfo._op == Operators.Modulo,
                                                 "Invalud Binary operation");

                                    break;
                            }
                            Debug.Assert(nodeLeft != null, "Invalid left operand");
                            Debug.Assert(nodeRight != null, "Invalid right operand");

                            if (opInfo._op == Operators.Like)
                            {
                                expr = new LikeNode(_table, opInfo._op, nodeLeft, nodeRight);
                            }
                            else
                            {
                                expr = new BinaryNode(_table, opInfo._op, nodeLeft, nodeRight);
                            }

                            break;
                        }
                    case Nodes.Unop:
                        /* Unary operator: Pop and bind right op. */
                        nodeLeft = null;
                        nodeRight = NodePop();

                        /* Check for special cases */
                        switch (opInfo._op)
                        {
                            case Operators.Not:
                                break;

                            case Operators.BitwiseNot:
                                throw ExprException.UnsupportedOperator(opInfo._op);

                            case Operators.Negative:
                                break;
                        }

                        Debug.Assert(nodeLeft == null, "Invalid left operand");
                        Debug.Assert(nodeRight != null, "Invalid right operand");

                        expr = new UnaryNode(_table, opInfo._op, nodeRight);
                        break;

                    case Nodes.Zop:
                        /* Intrinsic constant: just create node. */
                        expr = new ZeroOpNode(opInfo._op);
                        break;

                    default:
                        Debug.Fail("Unhandled operator type");
                        goto end_loop;
                }
                Debug.Assert(expr != null, "Failed to create expression");

                NodePush(expr);
                // countinue while loop;
            }
        end_loop:
            ;
        }

        internal void CheckToken(Tokens token)
        {
            if (_token != token)
            {
                throw ExprException.UnknownToken(token, _token, _pos);
            }
        }

        internal Tokens Scan()
        {
            char ch;
            char[] text = _text;

            _token = Tokens.None;

            while (true)
            {
            loop:
                _start = _pos;
                _op = Operators.Noop;
                ch = text[_pos++];
                switch (ch)
                {
                    case (char)0:
                        _token = Tokens.EOS;
                        goto end_loop;

                    case ' ':
                    case '\t':
                    case '\n':
                    case '\r':
                        ScanWhite();
                        goto loop;

                    case '(':
                        _token = Tokens.LeftParen;
                        goto end_loop;

                    case ')':
                        _token = Tokens.RightParen;
                        goto end_loop;

                    case '#':
                        ScanDate();
                        CheckToken(Tokens.Date);
                        goto end_loop;

                    case '\'':
                        ScanString('\'');
                        CheckToken(Tokens.StringConst);
                        goto end_loop;

                    case '=':
                        _token = Tokens.BinaryOp;
                        _op = Operators.EqualTo;
                        goto end_loop;

                    case '>':
                        _token = Tokens.BinaryOp;
                        ScanWhite();
                        if (text[_pos] == '=')
                        {
                            _pos++;
                            _op = Operators.GreaterOrEqual;
                        }
                        else
                            _op = Operators.GreaterThen;
                        goto end_loop;
                    case '<':
                        _token = Tokens.BinaryOp;
                        ScanWhite();
                        if (text[_pos] == '=')
                        {
                            _pos++;
                            _op = Operators.LessOrEqual;
                        }
                        else if (text[_pos] == '>')
                        {
                            _pos++;
                            _op = Operators.NotEqual;
                        }
                        else
                            _op = Operators.LessThen;
                        goto end_loop;

                    case '+':
                        _token = Tokens.BinaryOp;
                        _op = Operators.Plus;
                        goto end_loop;

                    case '-':
                        _token = Tokens.BinaryOp;
                        _op = Operators.Minus;
                        goto end_loop;

                    case '*':
                        _token = Tokens.BinaryOp;
                        _op = Operators.Multiply;
                        goto end_loop;

                    case '/':
                        _token = Tokens.BinaryOp;
                        _op = Operators.Divide;
                        goto end_loop;

                    case '%':
                        _token = Tokens.BinaryOp;
                        _op = Operators.Modulo;
                        goto end_loop;

                    /* Beginning of bitwise operators */
                    case '&':
                        _token = Tokens.BinaryOp;
                        _op = Operators.BitwiseAnd;
                        goto end_loop;

                    case '|':
                        _token = Tokens.BinaryOp;
                        _op = Operators.BitwiseOr;
                        goto end_loop;
                    case '^':
                        _token = Tokens.BinaryOp;
                        _op = Operators.BitwiseXor;
                        goto end_loop;
                    case '~':
                        _token = Tokens.BinaryOp;
                        _op = Operators.BitwiseNot;
                        goto end_loop;

                    /* we have bracketed identifier */
                    case '[':
                        // BUG: special case
                        ScanName(']', _escape, "]\\");
                        CheckToken(Tokens.Name);
                        goto end_loop;

                    case '`':
                        ScanName('`', '`', "`");
                        CheckToken(Tokens.Name);
                        goto end_loop;

                    default:
                        /* Check for list separator */

                        if (ch == _listSeparator)
                        {
                            _token = Tokens.ListSeparator;
                            goto end_loop;
                        }

                        if (ch == '.')
                        {
                            if (_prevOperand == Empty)
                            {
                                ScanNumeric();
                            }
                            else
                            {
                                _token = Tokens.Dot;
                            }
                            goto end_loop;
                        }

                        /* Check for binary constant */
                        if (ch == '0' && (text[_pos] == 'x' || text[_pos] == 'X'))
                        {
                            ScanBinaryConstant();
                            _token = Tokens.BinaryConst;
                            goto end_loop;
                        }

                        /* Check for number: digit is always good; . or - only if osNil. */
                        if (IsDigit(ch))
                        {
                            ScanNumeric();
                            goto end_loop;
                        }

                        /* Check for reserved word */
                        ScanReserved();
                        if (_token != Tokens.None)
                        {
                            goto end_loop;
                        }

                        /* Alpha means identifier */

                        if (IsAlphaNumeric(ch))
                        {
                            ScanName();
                            if (_token != Tokens.None)
                            {
                                CheckToken(Tokens.Name);
                                goto end_loop;
                            }
                        }

                        /* Don't understand that banter at all. */
                        _token = Tokens.Unknown;
                        throw ExprException.UnknownToken(new string(text, _start, _pos - _start), _start + 1);
                }
            }
        end_loop:
            return _token;
        }

        /// <summary>
        ///     ScanNumeric - parse number.
        ///     In format: [digit|.]*{[e|E]{[+|-]}{digit*}}
        ///     Further checking is done by constant parser.
        /// </summary>
        private void ScanNumeric()
        {
            char[] text = _text;
            bool fDot = false;
            bool fSientific = false;

            Debug.Assert(_pos != 0, "We have at least one digit in the buffer, ScanNumeric()");
            Debug.Assert(IsDigit(text[_pos - 1]), "We have at least one digit in the buffer, ScanNumeric(), not a digit");

            while (IsDigit(text[_pos]))
            {
                _pos++;
            }

            if (text[_pos] == _decimalSeparator)
            {
                fDot = true;
                _pos++;
            }

            while (IsDigit(text[_pos]))
            {
                _pos++;
            }

            if (text[_pos] == _exponentL || text[_pos] == _exponentU)
            {
                fSientific = true;
                _pos++;

                if (text[_pos] == '-' || text[_pos] == '+')
                {
                    _pos++;
                }
                while (IsDigit(text[_pos]))
                {
                    _pos++;
                }
            }
            if (fSientific)
                _token = Tokens.Float;
            else if (fDot)
                _token = Tokens.Decimal;
            else
                _token = Tokens.Numeric;
        }
        /// <summary>
        ///     Just a string of alphanumeric characters.
        /// </summary>
        private void ScanName()
        {
            char[] text = _text;

            while (IsAlphaNumeric(text[_pos]))
                _pos++;

            _token = Tokens.Name;
        }

        /// <summary>
        ///      recognize bracketed identifiers.
        ///      Special case: we are using '\' character to escape '[' and ']' only, so '\' by itself  is not an escape
        /// </summary>
        private void ScanName(char chEnd, char esc, string charsToEscape)
        {
            char[] text = _text;

            Debug.Assert(chEnd != '\0', "Invalid bracket value");
            Debug.Assert(esc != '\0', "Invalid escape value");
            do
            {
                if (text[_pos] == esc)
                {
                    if (_pos + 1 < text.Length && charsToEscape.IndexOf(text[_pos + 1]) >= 0)
                    {
                        _pos++;
                    }
                }
                _pos++;
            } while (_pos < text.Length && text[_pos] != chEnd);

            if (_pos >= text.Length)
            {
                throw ExprException.InvalidNameBracketing(new string(text, _start, (_pos - 1) - _start));
            }

            Debug.Assert(text[_pos] == chEnd, "Invalid bracket value");

            _pos++;

            _token = Tokens.Name;
        }

        /// <summary>
        ///     Just read the string between '#' signs, and parse it later
        /// </summary>
        private void ScanDate()
        {
            char[] text = _text;

            do _pos++; while (_pos < text.Length && text[_pos] != '#');

            if (_pos >= text.Length || text[_pos] != '#')
            {
                // Bad date constant
                if (_pos >= text.Length)
                    throw ExprException.InvalidDate(new string(text, _start, (_pos - 1) - _start));
                else
                    throw ExprException.InvalidDate(new string(text, _start, _pos - _start));
            }
            else
            {
                _token = Tokens.Date;
            }
            _pos++;
        }

        private void ScanBinaryConstant()
        {
            char[] text = _text;
        }

        private void ScanReserved()
        {
            char[] text = _text;

            if (IsAlpha(text[_pos]))
            {
                ScanName();

                Debug.Assert(_token == Tokens.Name, "Exprecing an identifier.");
                Debug.Assert(_pos > _start, "Exprecing an identifier.");

                string name = new string(text, _start, _pos - _start);
                Debug.Assert(name != null, "Make sure the arguments for Compare method are OK");

                CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo;
                // binary search reserved words
                int lo = 0;
                int hi = s_reservedwords.Length - 1;
                do
                {
                    int i = (lo + hi) / 2;
                    Debug.Assert(s_reservedwords[i]._word != null, "Make sure the arguments for Compare method are OK");
                    int c = comparer.Compare(s_reservedwords[i]._word, name, CompareOptions.IgnoreCase);

                    if (c == 0)
                    {
                        // we found the reserved word..
                        _token = s_reservedwords[i]._token;
                        _op = s_reservedwords[i]._op;
                        return;
                    }
                    if (c < 0)
                    {
                        lo = i + 1;
                    }
                    else
                    {
                        hi = i - 1;
                    }
                } while (lo <= hi);

                Debug.Assert(_token == Tokens.Name, "Exprecing an identifier.");
            }
        }

        private void ScanString(char escape)
        {
            char[] text = _text;

            while (_pos < text.Length)
            {
                char ch = text[_pos++];

                if (ch == escape && _pos < text.Length && text[_pos] == escape)
                {
                    _pos++;
                }
                else if (ch == escape)
                    break;
            }

            if (_pos >= text.Length)
            {
                throw ExprException.InvalidString(new string(text, _start, (_pos - 1) - _start));
            }

            _token = Tokens.StringConst;
        }

        // scan the next token, and error if it doesn't match the requested token
        internal void ScanToken(Tokens token)
        {
            Scan();
            CheckToken(token);
        }

        private void ScanWhite()
        {
            char[] text = _text;

            while (_pos < text.Length && IsWhiteSpace(text[_pos]))
            {
                _pos++;
            }
        }

        /// <summary>
        ///     is the character a whitespace character?
        ///     Consider using CharacterInfo().IsWhiteSpace(ch) (System.Globalization)
        /// </summary>
        private bool IsWhiteSpace(char ch)
        {
            return ch <= 32 && ch != '\0';
        }

        /// <summary>
        ///     is the character an alphanumeric?
        /// </summary>
        private bool IsAlphaNumeric(char ch)
        {
            //single comparison
            switch (ch)
            {
                case 'a':
                case 'b':
                case 'c':
                case 'd':
                case 'e':
                case 'f':
                case 'g':
                case 'h':
                case 'i':
                case 'j':
                case 'k':
                case 'l':
                case 'm':
                case 'n':
                case 'o':
                case 'p':
                case 'q':
                case 'r':
                case 's':
                case 't':
                case 'u':
                case 'v':
                case 'w':
                case 'x':
                case 'y':
                case 'z':
                case 'A':
                case 'B':
                case 'C':
                case 'D':
                case 'E':
                case 'F':
                case 'G':
                case 'H':
                case 'I':
                case 'J':
                case 'K':
                case 'L':
                case 'M':
                case 'N':
                case 'O':
                case 'P':
                case 'Q':
                case 'R':
                case 'S':
                case 'T':
                case 'U':
                case 'V':
                case 'W':
                case 'X':
                case 'Y':
                case 'Z':
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                case '_':
                case '$':
                    return true;
                default:
                    if (ch > 0x7f)
                        return true;

                    return false;
            }
        }

        private bool IsDigit(char ch)
        {
            //single comparison
            switch (ch)
            {
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    return true;
                default:
                    return false;
            }
        }

        /// <summary>
        ///     is the character an alpha?
        /// </summary>
        private bool IsAlpha(char ch)
        {
            //single comparison
            switch (ch)
            {
                case 'a':
                case 'b':
                case 'c':
                case 'd':
                case 'e':
                case 'f':
                case 'g':
                case 'h':
                case 'i':
                case 'j':
                case 'k':
                case 'l':
                case 'm':
                case 'n':
                case 'o':
                case 'p':
                case 'q':
                case 'r':
                case 's':
                case 't':
                case 'u':
                case 'v':
                case 'w':
                case 'x':
                case 'y':
                case 'z':
                case 'A':
                case 'B':
                case 'C':
                case 'D':
                case 'E':
                case 'F':
                case 'G':
                case 'H':
                case 'I':
                case 'J':
                case 'K':
                case 'L':
                case 'M':
                case 'N':
                case 'O':
                case 'P':
                case 'Q':
                case 'R':
                case 'S':
                case 'T':
                case 'U':
                case 'V':
                case 'W':
                case 'X':
                case 'Y':
                case 'Z':
                case '_':
                    return true;
                default:
                    return false;
            }
        }
    }

    internal enum Tokens
    {
        None = 0,
        Name = 1, /* Identifier */
        Numeric = 2,
        Decimal = 3,
        Float = 4,
        BinaryConst = 5, /* Binary Constant e.g. 0x12ef */
        StringConst = 6,
        Date = 7,
        ListSeparator = 8, /* List Tokens.ListSeparator/Comma */
        LeftParen = 9, /* '('; */
        RightParen = 10, /* ')'; */
        ZeroOp = 11, /* 0-array operator like "NULL" */
        UnaryOp = 12,
        BinaryOp = 13,
        Child = 14,
        Parent = 15,
        Dot = 16,
        Unknown = 17, /* do not understend the token */
        EOS = 18, /* End of string */
    }

    /// <summary>
    ///     Operator stack element
    /// </summary>
    internal sealed class OperatorInfo
    {
        internal Nodes _type = 0;
        internal int _op = 0;
        internal int _priority = 0;

        internal OperatorInfo(Nodes type, int op, int pri)
        {
            _type = type;
            _op = op;
            _priority = pri;
        }
    }
}


text:
Welcome to Webpack!

              <button class="btn btn-default btn-primary" ng-click="vm.hitMe()">
                  {{vm.buttonText}}

              </button>

This is the NG6 starter

You can find me inside {{ vm.name }}.html


text:
export const description = `
Stress tests covering robustness in the presence of non-halting shaders.
`;

import { makeTestGroup } from '../../common/framework/test_group.js';
import { GPUTest } from '../../webgpu/gpu_test.js';

export const g = makeTestGroup(GPUTest);

g.test('compute')
  .desc(
    `Tests execution of compute passes with non-halting dispatch operations.

This is expected to hang for a bit, but it should ultimately result in graceful
device loss.`
  )
  .fn(async t => {
    const data = new Uint32Array([0]);
    const buffer = t.makeBufferWithContents(data, GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC);
    const module = t.device.createShaderModule({
      code: `
        struct Buffer { data: u32, };
        @group(0) @binding(0) var<storage, read_write> buffer: Buffer;
        @compute @workgroup_size(1) fn main() {
          loop {
            if (buffer.data == 1u) {
              break;
            }
            buffer.data = buffer.data + 2u;
          }
        }
      `,
    });
    const pipeline = t.device.createComputePipeline({
      layout: 'auto',
      compute: { module, entryPoint: 'main' },
    });
    const encoder = t.device.createCommandEncoder();
    const pass = encoder.beginComputePass();
    pass.setPipeline(pipeline);
    const bindGroup = t.device.createBindGroup({
      layout: pipeline.getBindGroupLayout(0),
      entries: [{ binding: 0, resource: { buffer } }],
    });
    pass.setBindGroup(0, bindGroup);
    pass.dispatch(1);
    pass.end();
    t.device.queue.submit([encoder.finish()]);
    await t.device.lost;
  });

g.test('vertex')
  .desc(
    `Tests execution of render passes with a non-halting vertex stage.

This is expected to hang for a bit, but it should ultimately result in graceful
device loss.`
  )
  .fn(async t => {
    const module = t.device.createShaderModule({
      code: `
        struct Data { counter: u32, increment: u32, };
        @group(0) @binding(0) var<uniform> data: Data;
        @vertex fn vmain() -> @builtin(position) vec4<f32> {
          var counter: u32 = data.counter;
          loop {
            if (counter % 2u == 1u) {
              break;
            }
            counter = counter + data.increment;
          }
          return vec4<f32>(1.0, 1.0, 0.0, f32(counter));
        }
        @fragment fn fmain() -> @location(0) vec4<f32> {
          return vec4<f32>(1.0);
        }
      `,
    });

    const pipeline = t.device.createRenderPipeline({
      layout: 'auto',
      vertex: { module, entryPoint: 'vmain', buffers: [] },
      primitive: { topology: 'point-list' },
      fragment: {
        targets: [{ format: 'rgba8unorm' }],
        module,
        entryPoint: 'fmain',
      },
    });
    const uniforms = t.makeBufferWithContents(new Uint32Array([0, 2]), GPUBufferUsage.UNIFORM);
    const bindGroup = t.device.createBindGroup({
      layout: pipeline.getBindGroupLayout(0),
      entries: [
        {
          binding: 0,
          resource: { buffer: uniforms },
        },
      ],
    });
    const renderTarget = t.device.createTexture({
      size: [1, 1],
      usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
      format: 'rgba8unorm',
    });
    const encoder = t.device.createCommandEncoder();
    const pass = encoder.beginRenderPass({
      colorAttachments: [
        {
          view: renderTarget.createView(),
          clearValue: [0, 0, 0, 0],
          loadOp: 'clear',
          storeOp: 'store',
        },
      ],
    });
    pass.setPipeline(pipeline);
    pass.setBindGroup(0, bindGroup);
    pass.draw(1);
    pass.end();
    t.device.queue.submit([encoder.finish()]);
    await t.device.lost;
  });

g.test('fragment')
  .desc(
    `Tests execution of render passes with a non-halting fragment stage.

This is expected to hang for a bit, but it should ultimately result in graceful
device loss.`
  )
  .fn(async t => {
    const module = t.device.createShaderModule({
      code: `
        struct Data { counter: u32, increment: u32, };
        @group(0) @binding(0) var<uniform> data: Data;
        @vertex fn vmain() -> @builtin(position) vec4<f32> {
          return vec4<f32>(0.0, 0.0, 0.0, 1.0);
        }
        @fragment fn fmain() -> @location(0) vec4<f32> {
          var counter: u32 = data.counter;
          loop {
            if (counter % 2u == 1u) {
              break;
            }
            counter = counter + data.increment;
          }
          return vec4<f32>(1.0 / f32(counter), 0.0, 0.0, 1.0);
        }
      `,
    });

    const pipeline = t.device.createRenderPipeline({
      layout: 'auto',
      vertex: { module, entryPoint: 'vmain', buffers: [] },
      primitive: { topology: 'point-list' },
      fragment: {
        targets: [{ format: 'rgba8unorm' }],
        module,
        entryPoint: 'fmain',
      },
    });
    const uniforms = t.makeBufferWithContents(new Uint32Array([0, 2]), GPUBufferUsage.UNIFORM);
    const bindGroup = t.device.createBindGroup({
      layout: pipeline.getBindGroupLayout(0),
      entries: [
        {
          binding: 0,
          resource: { buffer: uniforms },
        },
      ],
    });
    const renderTarget = t.device.createTexture({
      size: [1, 1],
      usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
      format: 'rgba8unorm',
    });
    const encoder = t.device.createCommandEncoder();
    const pass = encoder.beginRenderPass({
      colorAttachments: [
        {
          view: renderTarget.createView(),
          clearValue: [0, 0, 0, 0],
          loadOp: 'clear',
          storeOp: 'store',
        },
      ],
    });
    pass.setPipeline(pipeline);
    pass.setBindGroup(0, bindGroup);
    pass.draw(1);
    pass.end();
    t.device.queue.submit([encoder.finish()]);
    await t.device.lost;
  });