text:
require 'optparse'
require File.join(File.dirname(__FILE__), 'thread-pool')
include Java
import org.apache.hadoop.hbase.HConstants
import org.apache.hadoop.hbase.HBaseConfiguration
import org.apache.hadoop.hbase.client.HBaseAdmin
import org.apache.hadoop.hbase.client.Get
import org.apache.hadoop.hbase.client.Scan
import org.apache.hadoop.hbase.client.HTable
import org.apache.hadoop.hbase.client.HConnectionManager
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
import org.apache.hadoop.hbase.util.Bytes
import org.apache.hadoop.hbase.util.Writables
import org.apache.hadoop.conf.Configuration
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.hadoop.hbase.protobuf.ProtobufUtil
import org.apache.hadoop.hbase.ServerName
import org.apache.hadoop.hbase.HRegionInfo

# Name of this script
NAME = "region_mover"

# Get meta table reference
def getMetaTable(config)
  # Keep meta reference in ruby global
  if not $META
    $META = HTable.new(config, HConstants::META_TABLE_NAME)
  end
  return $META
end

# Get table instance.
# Maintains cache of table instances.
def getTable(config, name)
  # Keep dictionary of tables in ruby global
  if not $TABLES
    $TABLES = {}
  end
  key = name.toString()
  if not $TABLES[key]
    $TABLES[key] = HTable.new(config, name)
  end
  return $TABLES[key]
end

def closeTables()
  if not $TABLES
    return
  end

  $LOG.info("Close all tables")
  $TABLES.each do |name, table|
    $TABLES.delete(name)
    table.close()
  end
end

# Returns true if passed region is still on 'original' when we look at hbase:meta.
def isSameServer(admin, r, original)
  server = getServerNameForRegion(admin, r)
  return false unless server and original
  return server == original
end

class RubyAbortable
  include org.apache.hadoop.hbase.Abortable
  def abort(why, e)
    puts "ABORTED! why=" + why + ", e=" + e.to_s
  end
end

# Get servername that is up in hbase:meta; this is hostname + port + startcode comma-delimited.
# Can return nil
def getServerNameForRegion(admin, r)
  return nil unless admin.isTableEnabled(r.getTableName)
  if r.isMetaRegion()
    # Hack
    zkw = org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher.new(admin.getConfiguration(), "region_mover", nil)
    mtl = org.apache.hadoop.hbase.zookeeper.MetaTableLocator.new()
    begin
      while not mtl.isLocationAvailable(zkw)
        sleep 0.1
      end
      # Make a fake servername by appending ','
      metaServer = mtl.getMetaRegionLocation(zkw).toString() + ","
      return metaServer
    ensure
      zkw.close()
    end
  end
  table = nil
  table = getMetaTable(admin.getConfiguration())
  g = Get.new(r.getRegionName())
  g.addColumn(HConstants::CATALOG_FAMILY, HConstants::SERVER_QUALIFIER)
  g.addColumn(HConstants::CATALOG_FAMILY, HConstants::STARTCODE_QUALIFIER)
  result = table.get(g)
  return nil unless result
  server = result.getValue(HConstants::CATALOG_FAMILY, HConstants::SERVER_QUALIFIER)
  startcode = result.getValue(HConstants::CATALOG_FAMILY, HConstants::STARTCODE_QUALIFIER)
  return nil unless server
  return java.lang.String.new(Bytes.toString(server)).replaceFirst(":", ",")  + "," + Bytes.toLong(startcode).to_s
end

# Trys to scan a row from passed region
# Throws exception if can't
def isSuccessfulScan(admin, r)
  scan = Scan.new(r.getStartKey())
  scan.setBatch(1)
  scan.setCaching(1)
  scan.setFilter(FirstKeyOnlyFilter.new())
  begin
    table = getTable(admin.getConfiguration(), r.getTableName())
    scanner = table.getScanner(scan)
  rescue org.apache.hadoop.hbase.TableNotFoundException,
      org.apache.hadoop.hbase.TableNotEnabledException => e
    $LOG.warn("Region " + r.getEncodedName() + " belongs to recently " +
      "deleted/disabled table. Skipping... " + e.message)
    return
  end
  begin
    results = scanner.next()
    # We might scan into next region, this might be an empty table.
    # But if no exception, presume scanning is working.
  ensure
    scanner.close()
    # Do not close the htable. It is cached in $TABLES and
    # may be reused in moving another region of same table.
    # table.close()
  end
end

# Check region has moved successful and is indeed hosted on another server
# Wait until that is the case.
def move(admin, r, newServer, original)
  # Now move it. Do it in a loop so can retry if fail.  Have seen issue where
  # we tried move region but failed and retry put it back on old location;
  # retry in this case.

  retries = admin.getConfiguration.getInt("hbase.move.retries.max", 5)
  count = 0
  same = true
  start = Time.now
  while count < retries and same
    if count > 0
      $LOG.info("Retry " + count.to_s + " of maximum " + retries.to_s)
    end
    count = count + 1
    begin
      admin.move(Bytes.toBytes(r.getEncodedName()), Bytes.toBytes(newServer))
    rescue java.lang.reflect.UndeclaredThrowableException,
        org.apache.hadoop.hbase.UnknownRegionException => e
      $LOG.info("Exception moving "  + r.getEncodedName() +
        "; split/moved? Continuing: " + e)
      return
    end
    # Wait till its up on new server before moving on
    maxWaitInSeconds = admin.getConfiguration.getInt("hbase.move.wait.max", 60)
    maxWait = Time.now + maxWaitInSeconds
    while Time.now < maxWait
      same = isSameServer(admin, r, original)
      break unless same
      sleep 0.1
    end
  end
  raise RuntimeError, "Region stuck on #{original}, newserver=#{newServer}" if same
  # Assert can Scan from new location.
  isSuccessfulScan(admin, r)
  $LOG.info("Moved region " + r.getRegionNameAsString() + " cost: " +
    java.lang.String.format("%.3f", (Time.now - start)))
end

# Return the hostname:port out of a servername (all up to second ',')
def getHostPortFromServerName(serverName)
  return serverName.split(',')[0..1]
end

# Return array of servernames where servername is hostname+port+startcode
# comma-delimited
def getServers(admin)
  serverInfos = admin.getClusterStatus().getServerInfo()
  servers = []
  for server in serverInfos
    servers << server.getServerName()
  end
  return servers
end

# Remove the servername whose hostname portion matches from the passed
# array of servers.  Returns as side-effect the servername removed.
def stripServer(servers, hostname, port)
  count = servers.length
  servername = nil
  for server in servers
    hostFromServerName, portFromServerName = getHostPortFromServerName(server)
    if hostFromServerName == hostname and portFromServerName == port
      servername = servers.delete(server)
    end
  end
  # Check server to exclude is actually present
  raise RuntimeError, "Server %s:%d not online" % [hostname, port] unless servers.length < count
  return servername
end

# Returns a new serverlist that excludes the servername whose hostname portion
# matches from the passed array of servers.
def stripExcludes(servers, excludefile)
  excludes = readExcludes(excludefile)
  servers =  servers.find_all{|server|
      !excludes.contains(getHostPortFromServerName(server).join(":"))
  }
  # return updated servers list
  return servers
end

# Return servername that matches passed hostname and port
def getServerName(servers, hostname, port)
  servername = nil
  for server in servers
    hostFromServerName, portFromServerName = getHostPortFromServerName(server)
    if hostFromServerName == hostname and portFromServerName == port
      servername = server
      break
    end
  end
  raise ArgumentError, "Server %s:%d not online" % [hostname, port] unless servername
  return servername
end

# Create a logger and disable the DEBUG-level annoying client logging
def configureLogging(options)
  apacheLogger = LogFactory.getLog(NAME)
  # Configure log4j to not spew so much
  unless (options[:debug])
    logger = org.apache.log4j.Logger.getLogger("org.apache.hadoop.hbase.client")
    logger.setLevel(org.apache.log4j.Level::INFO)
  end
  return apacheLogger
end

# Get configuration instance
def getConfiguration()
  config = HBaseConfiguration.create()
  # No prefetching on hbase:meta This is for versions pre 0.99. Newer versions do not prefetch.
  config.setInt("hbase.client.prefetch.limit", 1)
  # Make a config that retries at short intervals many times
  config.setInt("hbase.client.pause", 500)
  config.setInt("hbase.client.retries.number", 100)
  return config
end

# Now get list of regions on targetServer
def getRegions(config, servername)
  connection = HConnectionManager::getConnection(config);
  return ProtobufUtil::getOnlineRegions(connection.getAdmin(ServerName.valueOf(servername)));
end

def deleteFile(filename)
  f = java.io.File.new(filename)
  f.delete() if f.exists()
end

# Write HRegionInfo to file
# Need to serialize in case non-printable characters.
# Format is count of regionnames followed by serialized regionnames.
def writeFile(filename, regions)
  fos = java.io.FileOutputStream.new(filename)
  dos = java.io.DataOutputStream.new(fos)
  # Write out a count of region names
  dos.writeInt(regions.size())
  # Write actual region names.
  for r in regions
    Bytes.writeByteArray(dos, r.toByteArray())
  end
  dos.close()
end

# See writeFile above.
# Returns array of HRegionInfos
def readFile(filename)
  f = java.io.File.new(filename)
  return java.util.ArrayList.new() unless f.exists()
  fis = java.io.FileInputStream.new(f)
  dis = java.io.DataInputStream.new(fis)
  # Read count of regions
  count = dis.readInt()
  regions = java.util.ArrayList.new(count)
  index = 0
  while index < count
    regions.add(HRegionInfo.parseFromOrNull(Bytes.readByteArray(dis)))
    index = index + 1
  end
  dis.close()
  return regions
end

# Move regions off the passed hostname:port
def unloadRegions(options, hostname, port)
  # Clean up any old files.
  filename = getFilename(options, hostname, port)
  deleteFile(filename)
  # Get configuration
  config = getConfiguration()
  # Get an admin instance
  admin = HBaseAdmin.new(config)
  servers = getServers(admin)
  # Remove the server we are unloading from from list of servers.
  # Side-effect is the servername that matches this hostname
  servername = stripServer(servers, hostname, port)

  # Remove the servers in our exclude list from list of servers.
  servers = stripExcludes(servers, options[:excludesFile])
  puts "Valid region move targets: ", servers
  if servers.length == 0
    puts "No regions were moved - there was no server available"
    exit 4
  end
  movedRegions = java.util.ArrayList.new()
  while true
    rs = getRegions(config, servername)
    # Remove those already tried to move
    rs.removeAll(movedRegions)
    break if rs.length == 0
    $LOG.info("Moving " + rs.length.to_s + " region(s) from " + servername +
      " on " + servers.length.to_s + " servers using " + options[:maxthreads].to_s + " threads.")
    counter = 0
    pool = ThreadPool.new(options[:maxthreads])
    server_index = 0
    while counter < rs.length do
      pool.launch(rs,counter,server_index) do |_rs,_counter,_server_index|
        $LOG.info("Moving region " + _rs[_counter].getEncodedName() + " (" + (_counter + 1).to_s +
        " of " + _rs.length.to_s + ") to server=" + servers[_server_index] + " for " + servername)
        # Assert we can scan region in its current location
        isSuccessfulScan(admin, _rs[_counter])
        # Now move it.
        move(admin, _rs[_counter], servers[_server_index], servername)
        movedRegions.add(_rs[_counter])
      end
      counter += 1
      server_index = (server_index + 1) % servers.length
    end
    $LOG.info("Waiting for the pool to complete")
    pool.stop
    $LOG.info("Pool completed")
  end
  if movedRegions.size() > 0
    # Write out file of regions moved
    writeFile(filename, movedRegions)
    $LOG.info("Wrote list of moved regions to " + filename)
  end
end

# Move regions to the passed hostname
def loadRegions(options, hostname, port)
  # Get configuration
  config = getConfiguration()
  # Get an admin instance
  admin = HBaseAdmin.new(config)
  filename = getFilename(options, hostname, port)
  regions = readFile(filename)
  return if regions.isEmpty()
  servername = nil
  # Wait till server is up
  maxWaitInSeconds = admin.getConfiguration.getInt("hbase.serverstart.wait.max", 180)
  maxWait = Time.now + maxWaitInSeconds
  while Time.now < maxWait
    servers = getServers(admin)
    begin
      servername = getServerName(servers, hostname, port)
    rescue ArgumentError => e
      $LOG.info("hostname=" + hostname.to_s + ":" + port.to_s + " is not up yet, waiting");
    end
    break if servername
    sleep 0.5
  end
  $LOG.info("Moving " + regions.size().to_s + " regions to " + servername)
  # sleep 20s to make sure the rs finished initialization.
  sleep 20
  counter = 0
  pool = ThreadPool.new(options[:maxthreads])
  while counter < regions.length do
    r = regions[counter]
    exists = false
    begin
      isSuccessfulScan(admin, r)
      exists = true
    rescue org.apache.hadoop.hbase.NotServingRegionException => e
      $LOG.info("Failed scan of " + e.message)
    end
    next unless exists
    currentServer = getServerNameForRegion(admin, r)
    if currentServer and currentServer == servername
      $LOG.info("Region " + r.getRegionNameAsString() + " (" + counter.to_s +
        " of " + regions.length.to_s + ") already on target server=" + servername)
      counter = counter + 1
      next
    end
    pool.launch(r,currentServer,counter) do |_r,_currentServer,_counter|
      $LOG.info("Moving region " + _r.getRegionNameAsString() + " (" + (_counter + 1).to_s +
        " of " + regions.length.to_s + ") from " + _currentServer.to_s + " to server=" +
        servername);
      move(admin, _r, servername, _currentServer)
    end
    counter = counter + 1
  end
  pool.stop
end

# Returns an array of hosts to exclude as region move targets
def readExcludes(filename)
  if filename == nil
    return java.util.ArrayList.new()
  end
  if ! File.exist?(filename)
      puts "Error: Unable to read host exclude file: ", filename
      raise RuntimeError
  end

  f = File.new(filename, "r")
  # Read excluded hosts list
  excludes = java.util.ArrayList.new()
  while (line = f.gets)
    line.strip! # do an inplace drop of pre and post whitespaces
    excludes.add(line) unless line.empty? # exclude empty lines
  end
  puts "Excluding hosts as region move targets: ", excludes
  f.close

  return excludes
end

def getFilename(options, targetServer, port)
  filename = options[:file]
  if not filename
    filename = "/tmp/" + ENV['USER'] + targetServer + ":" + port
  end
  return filename
end

# Do command-line parsing
options = {}
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: #{NAME}.rb [options] load|unload [<hostname>|<hostname:port>]"
  opts.separator 'Load or unload regions by moving one at a time'
  options[:file] = nil
  options[:maxthreads] = 1
  opts.on('-f', '--filename=FILE', 'File to save regions list into unloading, or read from loading; default /tmp/<hostname:port>') do |file|
    options[:file] = file
  end
  opts.on('-h', '--help', 'Display usage information') do
    puts opts
    exit
  end
  options[:debug] = false
  opts.on('-d', '--debug', 'Display extra debug logging') do
    options[:debug] = true
  end
  opts.on('-x', '--excludefile=FILE', 'File with hosts-per-line to exclude as unload targets; default excludes only target host; useful for rack decommisioning.') do |file|
    options[:excludesFile] = file
  end
  opts.on('-m', '--maxthreads=XX', 'Define the maximum number of threads to use to unload and reload the regions') do |number|
    options[:maxthreads] = number.to_i
  end
end
optparse.parse!

# Check ARGVs
if ARGV.length < 2
  puts optparse
  exit 1
end
hostname, port = ARGV[1].split(":")
if not hostname
  opts optparse
  exit 2
end

# Get configuration
config = getConfiguration()
if not port
    port = config.getInt(HConstants::REGIONSERVER_PORT, HConstants::DEFAULT_REGIONSERVER_PORT)
end
port = port.to_s

# Create a logger and save it to ruby global
$LOG = configureLogging(options)
case ARGV[0]
  when 'load'
    loadRegions(options, hostname, port)
  when 'unload'
    unloadRegions(options, hostname, port)
  else
    puts optparse
    exit 3
end

closeTables()


text:
Reports the calls to java.sql.Connection.prepareStatement(),
java.sql.Connection.prepareCall()or any
of their variants which take a dynamically-constructed string as the statement to prepare.
Constructed SQL statements are a common source of security breaches.

Powered by InspectionGadgets

redpajama_set_name: RedPajamaGithub


text:
/*
 * Xero Payroll AU
 * This is the Xero Payroll API for orgs in Australia region.
 *
 * The version of the OpenAPI document: 2.2.4
 * Contact: api@xero.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package com.xero.models.payrollau;

import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.io.IOException;

import org.threeten.bp.OffsetDateTime;
import com.xero.api.StringUtil;

/** TimesheetLine */
public class TimesheetLine {
  StringUtil util = new StringUtil();

  @JsonProperty("EarningsRateID")
  private UUID earningsRateID;

  @JsonProperty("TrackingItemID")
  private UUID trackingItemID;

  @JsonProperty("NumberOfUnits")
  private List<Double> numberOfUnits = new ArrayList<Double>();

  @JsonProperty("UpdatedDateUTC")
  private String updatedDateUTC;

  public TimesheetLine earningsRateID(UUID earningsRateID) {
    this.earningsRateID = earningsRateID;
    return this;
  }

  /**
   * The Xero identifier for an Earnings Rate
   *
   * @return earningsRateID
   */
  @ApiModelProperty(
      example = "966c5c77-2ef0-4320-b6a9-6c27b080ecc5",
      value = "The Xero identifier for an Earnings Rate")
  public UUID getEarningsRateID() {
    return earningsRateID;
  }

  public void setEarningsRateID(UUID earningsRateID) {
    this.earningsRateID = earningsRateID;
  }

  public TimesheetLine trackingItemID(UUID trackingItemID) {
    this.trackingItemID = trackingItemID;
    return this;
  }

  /**
   * The Xero identifier for a Tracking Category. The TrackingOptionID must belong to the
   * TrackingCategory selected as TimesheetCategories under Payroll Settings.
   *
   * @return trackingItemID
   */
  @ApiModelProperty(
      example = "ae777a87-5ef3-4fa0-a4f0-d10e1f13073a",
      value =
          "The Xero identifier for a Tracking Category. The TrackingOptionID must belong to the"
              + " TrackingCategory selected as TimesheetCategories under Payroll Settings.")
  public UUID getTrackingItemID() {
    return trackingItemID;
  }

  public void setTrackingItemID(UUID trackingItemID) {
    this.trackingItemID = trackingItemID;
  }

  public TimesheetLine numberOfUnits(List<Double> numberOfUnits) {
    this.numberOfUnits = numberOfUnits;
    return this;
  }

  public TimesheetLine addNumberOfUnitsItem(Double numberOfUnitsItem) {
    if (this.numberOfUnits == null) {
      this.numberOfUnits = new ArrayList<Double>();
    }
    this.numberOfUnits.add(numberOfUnitsItem);
    return this;
  }

  /**
   * The number of units on a timesheet line
   *
   * @return numberOfUnits
   */
  @ApiModelProperty(value = "The number of units on a timesheet line")
  public List<Double> getNumberOfUnits() {
    return numberOfUnits;
  }

  public void setNumberOfUnits(List<Double> numberOfUnits) {
    this.numberOfUnits = numberOfUnits;
  }

  /**
   * Last modified timestamp
   *
   * @return updatedDateUTC
   */
  @ApiModelProperty(example = "/Date(1583967733054+0000)/", value = "Last modified timestamp")
  public String getUpdatedDateUTC() {
    return updatedDateUTC;
  }

  public OffsetDateTime getUpdatedDateUTCAsDate() {
    if (this.updatedDateUTC != null) {
      try {
        return util.convertStringToOffsetDateTime(this.updatedDateUTC);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return null;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    TimesheetLine timesheetLine = (TimesheetLine) o;
    return Objects.equals(this.earningsRateID, timesheetLine.earningsRateID)
        && Objects.equals(this.trackingItemID, timesheetLine.trackingItemID)
        && Objects.equals(this.numberOfUnits, timesheetLine.numberOfUnits)
        && Objects.equals(this.updatedDateUTC, timesheetLine.updatedDateUTC);
  }

  @Override
  public int hashCode() {
    return Objects.hash(earningsRateID, trackingItemID, numberOfUnits, updatedDateUTC);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class TimesheetLine {\n");
    sb.append("    earningsRateID: ").append(toIndentedString(earningsRateID)).append("\n");
    sb.append("    trackingItemID: ").append(toIndentedString(trackingItemID)).append("\n");
    sb.append("    numberOfUnits: ").append(toIndentedString(numberOfUnits)).append("\n");
    sb.append("    updatedDateUTC: ").append(toIndentedString(updatedDateUTC)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
  Osmoy est
       un village
       situé dans le département des Yvelines en Île-de-France. Elle totalisait 404 habitants en 2008.

À coté de Osmoy sont localisées les villes de
Septeuil située à 4 km, 2 073 habitants,
Prunay-le-Temple localisée à 3 km, 360 habitants,
Saint-Martin-des-Champs à 2 km, 321 habitants,
Béhoust à 3 km, 453 habitants,
Tacoignières localisée à 4 km, 1 023 habitants,
Flexanville à 1 km, 571 habitants,
 entre autres. De plus, Osmoy est située à seulement quatorze km de Mantes-la-Jolie.

Si vous pensez venir habiter à Osmoy, vous pourrez facilement trouver une maison à acheter.

Le parc d'habitations, à Osmoy, était réparti en 2011 en deux appartements et 152 maisons soit
 un marché plutôt équilibré.


text:
'use strict';

/* Services */

var gasPublicServices = 'https://script.google.com/macros/s/'+gasScriptId+'/exec';

var myAppServices = angular.module('myApp.services', ['ngResource']);

myAppServices.factory('gasPublicServices', ['$resource',
function ($resource) {
    return $resource('', {}, {
                   getInfo: {
                        method: 'JSONP',
                        url: gasPublicServices,
                        params: {
                            callback:'JSON_CALLBACK',
                            operation: 'getInfo'
                        },
                        isArray: false,
                        cache: false
                    },
                   findAllGroups: {
                        method: 'JSONP',
                        url: gasPublicServices,
                        params: {
                            callback:'JSON_CALLBACK',
                            operation: 'findAllGroups'
                        },
                        isArray: true,
                        cache: false
                   },
                   getAllInventory: {
                        method: 'JSONP',
                        url: gasPublicServices,
                        params: {
                            callback:'JSON_CALLBACK',
                            operation: 'getAllInventory'
                        },
                        isArray: true,
                        cache: false
                    }
    })}
]);

myAppServices.factory('googleApi', ['$resource',
function ($resource) {
    return $resource('', {}, {
                   getInfo: {
                        method: 'JSONP',
                        url: gasPublicServices,
                        params: {
                            callback:'JSON_CALLBACK',
                            operation: 'getInfo'
                        },
                        isArray: false,
                        cache: false
                   },
                   findAllGroups: {
                        method: 'JSONP',
                        url: gasPublicServices,
                        params: {
                            callback:'JSON_CALLBACK',
                            operation: 'findAllGroups'
                        },
                        isArray: false,
                        cache: false
                   },
                   getAllInventory: {
                        method: 'JSONP',
                        url: gasPublicServices,
                        params: {
                            callback:'JSON_CALLBACK',
                            operation: 'getAllInventory'
                        },
                        isArray: true,
                        cache: false
                   }
    })}
]);


text:
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {RouterModule} from '@angular/router';

import {CategoryListComponent} from './category-list.component';
import {CategoryCardComponent} from './category-card.component';
import {CategorySlideComponent} from './category-slide.component';

import {CategoryService} from './category.service';

@NgModule({
    imports: [CommonModule, FormsModule, RouterModule],
    declarations: [CategoryListComponent, CategoryCardComponent, CategorySlideComponent],
    exports: [CategoryListComponent, CategoryCardComponent, CategorySlideComponent],
    providers: [CategoryService]
})
export class CategoryModule {}


text:
<tool id="bed2genetrack" name="Visualize BED file">

  <description> - creates a visualization from a bed file</description>

  <command interpreter="python">
    genetrack_indexer.py -i $input -o $output -s $shift -v 0 -f BED -x
  </command>

  <inputs>

    <param format="bed" name="input" type="data" help="Input data">
      Select input bed file
    </param>

    <param name="shift" size="4" type="integer" value="0" help="distance in basepairs">
        Shift at 5' end
    </param>

  </inputs>

  <outputs>
    <data format="genetrack" name="output" />
  </outputs>

<help>
**Help**

This tool will create a visualization of the bed file that is selected.

**Parameters**

- **Shift at 5' end** should be used when the location of interest is at a fixed distance from
  the 5' end for **all sequenced fragments**!

  For example if the sequenced sample consists
  mono-nucleosomal DNA (146bp) we should expect that
  each nucleosome midpoint is located at 73 bp from the 5' end of the fragment.
  Therefore we would enter 73 as the shift parameter. Once corrected the reads
  on each strand will coincide and indicate the actual midpoints
  of the nucleosomes.

  When shifting the averaging process in GeneTrack is able correct for longer or shorter
  than expected fragment sizes as long as the errors are reasonably random.

</help>

</tool>


text:
package at.forsyte.apalache.tla.bmcmt

import java.io.{File, FileWriter, PrintWriter, StringWriter}

import at.forsyte.apalache.tla.bmcmt.analyses.{ExprGradeStore, FormulaHintsStore}
import at.forsyte.apalache.tla.bmcmt.rewriter.{ConstSimplifierForSmt, MetricProfilerListener, RewriterConfig}
import at.forsyte.apalache.tla.bmcmt.rules.aux.{CherryPick, MockOracle, Oracle}
import at.forsyte.apalache.tla.bmcmt.search.SearchStrategy
import at.forsyte.apalache.tla.bmcmt.search.SearchStrategy._
import at.forsyte.apalache.tla.bmcmt.smt.{SolverConfig, SolverContext, Z3SolverContext}
import at.forsyte.apalache.tla.bmcmt.types._
import at.forsyte.apalache.tla.bmcmt.util.TlaExUtil
import at.forsyte.apalache.tla.imp.src.SourceStore
import at.forsyte.apalache.tla.lir._
import at.forsyte.apalache.tla.lir.convenience.tla
import at.forsyte.apalache.tla.lir.io._
import at.forsyte.apalache.tla.lir.storage.{ChangeListener, SourceLocator}
import at.forsyte.apalache.tla.lir.values.TlaBool
import com.typesafe.scalalogging.LazyLogging

import scala.collection.immutable.SortedMap
import scala.collection.mutable.ListBuffer

/**
  * A bounded model checker using SMT. The checker itself does not implement a particular search. Instead,
  * it queries a search strategy, e.g., DfsStrategy or BfsStrategy.
  *
  * We expect the invariant to be negated and written over prime variables.
  *
  * @author Igor Konnov
  */
class ModelChecker(typeFinder: TypeFinder[CellT],
                   formulaHintsStore: FormulaHintsStore,
                   changeListener: ChangeListener,
                   exprGradeStore: ExprGradeStore, sourceStore: SourceStore, checkerInput: CheckerInput,
                   searchStrategy: SearchStrategy,
                   tuningOptions: Map[String, String],
                   debug: Boolean = false, profile: Boolean = false, checkRuntime: Boolean = false)
  extends Checker with LazyLogging {

  import Checker._

  class CancelSearchException(val outcome: Outcome.Value) extends Exception

  /**
    * A stack of the symbolic states that might constitute a counterexample (the last state is on top).
    */
  private var stack: List[(SymbState, Oracle)] = List()
  private var typesStack: Seq[SortedMap[String, CellT]] = Seq()
  private val solverContext: SolverContext =
    new Z3SolverContext(SolverConfig(debug, profile,
      randomSeed = tuningOptions.getOrElse("smt.randomSeed", "0").toInt))
  // TODO: figure out why the preprocessor slows down invariant checking. Most likely, there is a bug.
  //      new PreproSolverContext(new Z3SolverContext(debug, profile))

  private val rewriter: SymbStateRewriterImpl =
    new SymbStateRewriterImpl(
      solverContext,
      typeFinder, exprGradeStore,
      if (profile) {
        Some(new MetricProfilerListener(sourceStore, changeListener, new File("profile.csv")))
      } else {
        None
      })

  rewriter.formulaHintsStore = formulaHintsStore
  rewriter.config = RewriterConfig(tuningOptions)

  private val stepFilters: Seq[String] =
    tuningOptions.getOrElse("search.transitionFilter", ".*").split(",")

  private val invFilter: String =
    tuningOptions.getOrElse("search.invariantFilter", "")

  private val invariantSplitByTransition: Boolean =
    tuningOptions.getOrElse("search.invariant.split", "true").toLowerCase == "true"

  private val learnTransFromUnsat: Boolean =
    tuningOptions.getOrElse("search.transition.learnFromUnsat", "").toLowerCase == "true"

  private val learnInvFromUnsat: Boolean =
    tuningOptions.getOrElse("search.invariant.learnFromUnsat", "").toLowerCase == "true"

  private val transitionTimeout: Long =
    BigInt(tuningOptions.getOrElse("search.transition.timeout", "0")).toLong

  private val invariantTimeout: Long =
    BigInt(tuningOptions.getOrElse("search.invariant.timeout", "0")).toLong

  /**
    * A list of transitions that are enabled at every step
    */
  private var enabledList: Seq[Seq[Int]] = Seq()

  /**
    * A set of CONSTANTS, which are special (rigid) variables, as they do not change in the course of execution.
    */
  private val constants = Set(checkerInput.rootModule.constDeclarations.map(_.name): _*)

  /**
    * Check all executions of a TLA+ specification up to a bounded number of steps.
    *
    * @return a verification outcome
    */
  def run(): Outcome.Value = {
    val initialArena = Arena.create(solverContext)
    val dummyState = new SymbState(initialArena.cellTrue().toNameEx, initialArena, Binding())
    val outcome =
      try {
        val initConstState = initializeConstants(dummyState)
        stack +:= (initConstState, new MockOracle(0))
        typesStack +:= typeFinder.varTypes // the type of CONSTANTS have been computed already
        applySearchStrategy()
      } catch {
        case _: CancelSearchException =>
          Outcome.Error

        case err: CheckerException =>
          // try to get any info about the problematic source location
          printRewriterSourceLoc()
          throw err
      }
    // flush the logs
    rewriter.dispose()
    outcome
  }

  /**
    * Use the provided expression to initialize the constants
    *
    * @param state an initial state
    * @return a new state with the constants initialized
    */
  private def initializeConstants(state: SymbState): SymbState = {
    val newState =
      if (checkerInput.constInitPrimed.isEmpty) {
        logger.info("No CONSTANT initializer given")
        state
      } else {
        logger.info("Initializing CONSTANTS with the provided operator")
        checkTypes(checkerInput.constInitPrimed.get)
        val nextState = rewriter.rewriteUntilDone(state.setRex(checkerInput.constInitPrimed.get))
        // importantly, assert the constraints that are imposed by the expression
        rewriter.solverContext.assertGroundExpr(nextState.ex)
        // as the initializer was defined over the primed versions of the constants, shift them back to non-primed
        shiftTypes(Set())
        nextState.setBinding(shiftBinding(nextState.binding, Set()))
      }

    val constants = checkerInput.rootModule.constDeclarations.map(_.name)
    val uninitialized = constants.filter(n => !newState.binding.contains(n))
    if (uninitialized.nonEmpty) {
      logger.error("The following CONSTANTS are not initialized: " + uninitialized.mkString(", "))
      throw new CancelSearchException(Checker.Outcome.RuntimeError)
    }
    newState
  }

  private def applySearchStrategy(): Outcome.Value = {
    searchStrategy.getCommand match {
      case Finish() => Outcome.NoError // done

      case FinishOnDeadlock() =>
        logger.error(s"Deadlock detected.")
        if (solverContext.sat()) {
          val filenames = dumpCounterexample(ValEx(TlaBool(true)) )
          logger.error(s"Check an execution leading to a deadlock state in any of ${filenames.mkString(", ")}")
        } else {
          logger.error("No model found that would describe the deadlock")
        }
        Outcome.Deadlock

      case BacktrackOnce() =>
        rewriter.pop()
        logger.debug("Backtracking to level %d".format(rewriter.contextLevel))
        stack = stack.tail
        typesStack = typesStack.tail
        searchStrategy.registerResponse(Backtracked())
        applySearchStrategy()

      case NextStep(stepNo: Int, transitionNos: Seq[Int], popContext: Boolean) =>
        def filter(trs: Seq[TlaEx]): Seq[(TlaEx, Int)] = {
          trs.zipWithIndex filter (p => transitionNos.contains(p._2))
        }

        assert(rewriter.contextLevel == stepNo)
        val (state, _) = stack.head
        val types = typesStack.head
        typeFinder.reset(types) // set the variable type as they should be at this step

        val transitions =
          if (stepNo == 0) filter(checkerInput.initTransitions) else filter(checkerInput.nextTransitions)

        // make the step
        val transWithEnabled = findEnabledOrBugs(stepNo, state, transitions.toList)
        val enabledExists = transWithEnabled.exists(_._2)
        if (!enabledExists) {
          // no push here, as the transition is disabled
          searchStrategy.registerResponse(SearchStrategy.NextStepDisabled())
        } else {
          rewriter.push() // this is needed for backtracking, LEVEL + 1
          val result = applyEnabled(stepNo, state, transWithEnabled)
          assert(result.isDefined)
          searchStrategy.registerResponse(SearchStrategy.NextStepFired())
        }

        applySearchStrategy() // next step
    }
  }

  private def findEnabledOrBugs(stepNo: Int, startingState: SymbState,
                                transitionsAndNos: List[(TlaEx, Int)]): List[((TlaEx, Int), Boolean)] = {
    // find all the feasible transitions and check the invariant for each transition
    logger.info("Step %d, level %d: checking if %d transition(s) are enabled and violate the invariant"
      .format(stepNo, rewriter.contextLevel, transitionsAndNos.length))

    def filterEnabled(state: SymbState, ts: List[(TlaEx, Int)]): List[((TlaEx, Int), Boolean)] = {
      ts match {
        case List() => List()

        case tranWithNo :: tail =>
          val (transition, transitionNo) = tranWithNo
          if (!stepMatchesFilter(stepNo, transitionNo)) {
            filterEnabled(state, tail) // just skip this transition
          } else {
            val erased = state.setBinding(forgetPrimed(state.binding))
            rewriter.push() // LEVEL + 1
            val (nextState, isEnabled) = applyTransition(stepNo, erased, transition, transitionNo, checkForErrors = true)
            rewriter.exprCache.disposeActionLevel() // leave only the constants
            rewriter.pop() // forget all the constraints that were generated by the transition, LEVEL + 0
            (tranWithNo, isEnabled) +: filterEnabled(state, tail)
          }
      }
    }

    val savedVarTypes = rewriter.typeFinder.varTypes // save the variable types before applying the transitions
    val enabled = filterEnabled(startingState, transitionsAndNos)
    /*
    enabledList :+= enabled map (_._2) // put it on stack, FIXME: this will not work well with DFS...
    dumpEnabledMap()
    */
    // restore the variable types to apply the enabled transitions once again
    rewriter.typeFinder.reset(savedVarTypes)
    enabled
  }

  private def applyEnabled(stepNo: Int, startingState: SymbState,
                           transWithEnabled: List[((TlaEx, Int), Boolean)]): Option[SymbState] = {
    // second, apply the enabled transitions and collect their effects
    logger.info("Step %d, level %d: collecting %d enabled transition(s)"
      .format(stepNo, rewriter.contextLevel, transWithEnabled.count(_._2)))
    assert(transWithEnabled.nonEmpty)
    val simplifier = new ConstSimplifierForSmt()

    def applyTrans(state: SymbState, ts: List[((TlaEx, Int), Boolean)]): List[SymbState] =
      ts match {
        case List() =>
          List(state) // the final state may contain additional cells, add it

        case (tranWithNo, isEnabled) :: tail =>
          if (!isEnabled && !learnTransFromUnsat) {
            applyTrans(state, tail) // ignore the disabled transition, without any rewriting
          } else {
            val (transition, transitionNo) = tranWithNo
            val erased = state.setBinding(forgetPrimed(state.binding))
            // note that the constraints are added at the current level, without an additional push
            var (nextState, _) = applyTransition(stepNo, erased, transition, transitionNo, checkForErrors = false)
            rewriter.exprCache.disposeActionLevel() // leave only the constants
            if (isEnabled && learnInvFromUnsat && invariantSplitByTransition) {
              nextState = assumeInvariant(stepNo, nextState)
            }
            if (isEnabled) {
              // collect the variables of the enabled transition
              nextState +: applyTrans(nextState, tail)
            } else {
              assert(learnTransFromUnsat)
              // Do not collect the variables from the disabled transition, but remember that it was disabled.
              // Note that the constraints are propagated via nextState
              solverContext.assertGroundExpr(simplifier.simplifyShallow(tla.not(nextState.ex)))
              applyTrans(nextState, tail)
            }
          }
      }

    val nextAndLastStates = applyTrans(startingState, transWithEnabled)
    val lastState = nextAndLastStates.last
    val nextStates = nextAndLastStates.slice(0, nextAndLastStates.length - 1)

    val picker = new CherryPick(rewriter)
    // pick an index j \in { 0..k } of the fired transition
    val (oracleState, oracle) = picker.oracleFactory.newDefaultOracle(lastState, nextStates.length)

    if (nextStates.isEmpty) {
      throw new IllegalArgumentException("enabled must be non-empty")
    } else if (nextStates.lengthCompare(1) == 0) {
      val resultingState = oracleState.setBinding(shiftBinding(lastState.binding, constants))
      solverContext.assertGroundExpr(lastState.ex)
      if (!invariantSplitByTransition) { checkAllInvariants(stepNo, 0, resultingState) }
      stack +:= (resultingState, oracle) // in this case, oracle is always zero
      shiftTypes(constants)
      typesStack = typeFinder.varTypes +: typesStack
      Some(resultingState)
    } else {
      // if oracle = i, then the ith transition is enabled
      solverContext.assertGroundExpr(oracle.caseAssertions(oracleState, nextStates.map(_.ex)))

      // glue the computed states S_0, ..., S_k together:
      // for every variable x', pick c_x from { S_1[x'], ..., S_k[x'] }
      //   and require \A i \in { 0.. k-1}. j = i => c_x = S_i[x']
      // Then, the final state binds x' -> c_x for every x' \in Vars'
      def getAssignedVars(st: SymbState) = forgetNonPrimed(st.binding, Set()).toMap.keySet

      val primedVars = getAssignedVars(nextStates.head) // only VARIABLES, not CONSTANTS
      var finalState = oracleState
      if (nextStates.exists(getAssignedVars(_) != primedVars)) {
        val index = nextStates.indexWhere(getAssignedVars(_) != primedVars)
        val otherSet = getAssignedVars(nextStates(index))
        val diff = otherSet.union(primedVars).diff(otherSet.intersect(primedVars))
        val msg =
          "[Step %d] Next states 0 and %d disagree on the set of assigned variables: %s"
            .format(stepNo, index, diff.mkString(", "))
        throw new InternalCheckerError(msg, finalState.ex)
      }

      def pickVar(x: String): ArenaCell = {
        val toPickFrom = nextStates map (_.binding(x))
        finalState = picker.pickByOracle(finalState,
          oracle, toPickFrom, finalState.arena.cellFalse().toNameEx) // no else case
        finalState.asCell
      }

      val finalVarBinding = Binding(primedVars.toSeq map (n => (n, pickVar(n))): _*) // variables only
      val constBinding = oracleState.binding.toMap.filter(p => constants.contains(p._1))
      finalState = finalState.setBinding(Binding(finalVarBinding.toMap ++ constBinding))
      if (debug && !solverContext.sat()) {
        throw new InternalCheckerError(s"Error picking next variables (step $stepNo). Report a bug.", finalState.ex)
      }
      // check the invariant, if search invariant.split=false
      if (!invariantSplitByTransition) { checkAllInvariants(stepNo, 0, finalState) }
      if (learnInvFromUnsat && !invariantSplitByTransition) {
        finalState = assumeInvariant(stepNo, finalState)
      }
      // finally, shift the primed variables to non-primed
      finalState = finalState.setBinding(shiftBinding(finalState.binding, constants))
      // that is the result of this step
      stack +:= (finalState, oracle)
      // here we save the transition index, not the oracle, which will be shown to the user
      shiftTypes(constants)
      typesStack = typeFinder.varTypes +: typesStack
      Some(finalState)
    }
  }

  // This method adds constraints right in the current context, without doing push
  private def applyTransition(stepNo: Int, state: SymbState, transition: TlaEx,
                              transitionNo: Int, checkForErrors: Boolean): (SymbState, Boolean) = {
    logger.debug("Step #%d, transition #%d, SMT context level %d."
      .format(stepNo, transitionNo, rewriter.contextLevel))
    logger.debug("Finding types of the variables...")
    checkTypes(transition)
    solverContext.log("; ------- STEP: %d, STACK LEVEL: %d TRANSITION: %d {"
      .format(stepNo, rewriter.contextLevel, transitionNo))
    logger.debug("Applying rewriting rules...")
    var nextState = rewriter.rewriteUntilDone(state.setRex(transition))
    rewriter.flushStatistics()
    if (checkForErrors && debug) {
      // This is a debugging feature that allows us to find incorrect rewriting rules.
      // Disable it in production.
      logger.debug("Finished rewriting. Checking satisfiability of the pushed constraints.")
      solverContext.satOrTimeout(transitionTimeout) match {
        case Some(false) =>
          // this is a clear sign of a bug in one of the translation rules
          logger.debug("UNSAT after pushing transition constraints")
          throw new CheckerException("A contradiction introduced in rewriting. Report a bug.", state.ex)

        case Some(true) => () // SAT
          logger.debug("The transition constraints are OK.")

        case None => // interpret it as sat
          logger.debug("Timeout. Assuming the transition constraints to be OK.")
      }
    }
    if (!checkForErrors) {
      // this was an experimental feature, which did not work nicely
      // assume no failure occurs
      //      val failPreds = state.arena.findCellsByType(FailPredT())
      //      failPreds.map(fp => tla.not(fp.toNameEx)) foreach solverContext.assertGroundExpr
      // just return the state
      (nextState, true)
      // LEVEL + 0
    } else {
      rewriter.push() // LEVEL + 1
      // assume the constraint constructed by this transition
      solverContext.assertGroundExpr(nextState.ex)
      // check whether this transition violates some assertions
      logger.debug("Checking transition feasibility.")
      solverContext.satOrTimeout(transitionTimeout) match {
        case Some(true) =>
          if (invariantSplitByTransition) {
            // check the invariant as soon as one transition has been applied
            checkAllInvariants(stepNo, transitionNo, nextState)
          }
          // and then forget all these constraints!
          rewriter.pop() // LEVEL + 0
          solverContext.log("; } ------- STEP: %d, STACK LEVEL: %d".format(stepNo, rewriter.contextLevel))
          (nextState, true)
        // LEVEL + 0

        case r: Option[Boolean] => // unsat or timeout
          // the current symbolic state is not feasible
          if (r.isDefined) {
            logger.debug("Transition #%d is not feasible.".format(transitionNo))
          } else {
            logger.debug(s"Timed out when checking feasibility of transition #$transitionNo. Assuming it is infeasible.")
          }
          rewriter.pop() // LEVEL + 0
          solverContext.log("; } ------- STEP: %d, STACK LEVEL: %d TRANSITION: %d"
            .format(stepNo, rewriter.contextLevel, transitionNo))
          (nextState, false)
        // LEVEL + 0
      }
    }
  }

  private def assumeInvariant(stepNo: Int, state: SymbState): SymbState = {
    val matchesInvFilter = invFilter == "" || stepNo.toString.matches("^" + invFilter + "$")
    if (!matchesInvFilter || checkerInput.invariantsAndNegations.isEmpty) {
      state
    } else {
      // as we have checked the invariant, we assume that it holds
      val savedEx = state.ex
      val savedTypes = rewriter.typeFinder.varTypes
      val savedBinding = state.binding
      // rename x' to x, so we are reasoning about the non-primed variables
      shiftTypes(constants)
      var nextState = state.setBinding(shiftBinding(state.binding, constants))

      for (((inv, _), index) <- checkerInput.invariantsAndNegations.zipWithIndex) {
        typeFinder.inferAndSave(inv)
        logger.debug(s"Assuming that the invariant $index holds true")
        nextState = rewriter.rewriteUntilDone(nextState.setRex(inv))
        // assume that the invariant holds true
        solverContext.assertGroundExpr(nextState.ex)
      }

      // restore the expression, the types, and the bindings
      rewriter.typeFinder.reset(savedTypes) // forget about the types that were used to check the invariant
      nextState.setRex(savedEx).setBinding(savedBinding)
    }
  }

  private def checkAllInvariants(stepNo: Int, transitionNo: Int, nextState: SymbState): Unit = {
    val matchesInvFilter = invFilter == "" || stepNo.toString.matches("^" + invFilter + "$")
    if (!matchesInvFilter) {
      return // skip the check if this transition should not be checked
    }

    // if the previous step was filtered, we cannot use the unchanged optimization
    // Bugfix to #108: never filter out the initial step
    val prevMatchesInvFilter =
      stepNo > 0 && (invFilter == "" || (stepNo - 1).toString.matches("^" + invFilter + "$"))

    val invNegs = checkerInput.invariantsAndNegations.map(_._2)
    for ((notInv, invNo) <- invNegs.zipWithIndex) {
      logger.debug(s"Checking the invariant $invNo")
      val changedPrimed =
        if (prevMatchesInvFilter) {
          nextState.changed // only check the invariant if it touches the changed variables
        } else {
          nextState.binding.toMap.keySet // check the invariant in any case, as it could be violated at the previous step
        }
      val savedTypes = rewriter.typeFinder.varTypes
      // rename x' to x, so we are reasoning about the non-primed variables
      shiftTypes(constants)
      val shiftedState = nextState.setBinding(shiftBinding(nextState.binding, constants))
      rewriter.exprCache.disposeActionLevel() // renaming x' to x makes the cache inconsistent, so clean it
      // check the types and the invariant
      checkTypes(notInv)
      checkOneInvariant(stepNo, transitionNo, shiftedState, changedPrimed, notInv)
      rewriter.typeFinder.reset(savedTypes) // forget about the types that were used to check the invariant
    }
  }

  private def checkOneInvariant(stepNo: Int, transitionNo: Int, nextState: SymbState, changedPrimed: Set[String], notInv: TlaEx): Unit = {
    val used = TlaExUtil.findUsedNames(notInv).map(_ + "'") // add primes as the invariant is referring to non-primed variables
    if (stepNo != 0 && used.nonEmpty && used.intersect(changedPrimed).isEmpty) {
      // another bugfix: look at unchecked variables, except for the case when Init has been applied!
      // bugfix for #108: check the invariant over CONSTANTS, if it has not been changed before
      // XXX: it might happen that an invariant over CONSTANTS is checked multiple times. We will fix that in v0.8.0.
      logger.debug(s"The invariant is referring only to the UNCHANGED variables. Skipped.")
    } else {
      rewriter.push()
      val notInvState = rewriter.rewriteUntilDone(nextState
        .setRex(notInv))
      solverContext.assertGroundExpr(notInvState.ex)
      solverContext.satOrTimeout(invariantTimeout) match {
        case Some(true) =>
          // introduce a dummy oracle to hold the transition index, we need it for the counterexample
          val oracle = new MockOracle(transitionNo)
          stack = (notInvState, oracle) +: stack
          val filenames = dumpCounterexample(notInv)
          logger.error(s"Invariant is violated at depth $stepNo. Check the counterexample in any of ${filenames.mkString(", ")}")
          if (debug) {
            logger.warn(s"Dumping the arena into smt.log. This may take some time...")
            // dump everything in the log
            val writer = new StringWriter()
            new SymbStateDecoder(solverContext, rewriter).dumpArena(notInvState, new PrintWriter(writer))
            solverContext.log(writer.getBuffer.toString)
          }
          // cancel the search
          throw new CancelSearchException(Outcome.Error)

        case Some(false) =>
          logger.debug("The invariant holds true.")

        case None =>
          logger.debug("Timeout. Assuming that the invariant holds true.")
      }
      rewriter.pop()
    }
  }

  // returns a list of files with counterexample written
  private def dumpCounterexample(notInv: TlaEx): List[String] = {
    val states = new ListBuffer[NextState]()
    for (((state, oracle), i) <- stack.reverse.zipWithIndex) {
      val decoder = new SymbStateDecoder(solverContext, rewriter)
      val transition = oracle.evalPosition(solverContext, state)
      val binding = decoder.decodeStateVariables(state)
      states += ((transition.toString, binding))
    }
    CounterexampleWriter.writeAllFormats(checkerInput.rootModule, notInv, states.toList)
  }

  private def checkTypes(expr: TlaEx): Unit = {
    typeFinder.inferAndSave(expr)
    if (typeFinder.typeErrors.nonEmpty) {
      def print_error(e: TypeInferenceError): Unit = {
        val sourceLocator: SourceLocator = SourceLocator(sourceStore.makeSourceMap, changeListener)

        val locInfo =
          sourceLocator.sourceOf(e.origin) match {
            case Some(loc) => loc.toString
            case None => "<unknown origin>"
          }
        val exStr = e.origin match {
          case OperEx(op, _*) => op.name + "(...)"
          case ex@_ => ex.toString()
        }
        logger.error("%s, %s, type error: %s".format(locInfo, exStr, e.explanation))
      }

      typeFinder.typeErrors foreach print_error
      throw new CancelSearchException(Outcome.Error)
    }
  }

  /**
    * Remove the non-primed variables (except provided constants)
    * and rename the primed variables to their non-primed versions.
    * After that, remove the type finder to contain the new types only.
    */
  private def shiftTypes(constants: Set[String]): Unit = {
    val types = typeFinder.varTypes
    val nextTypes =
      types.filter(p => p._1.endsWith("'") || constants.contains(p._1))
        .map(p => (p._1.stripSuffix("'"), p._2))
    typeFinder.reset(nextTypes)
  }

  private def forgetPrimedTypes(): Unit = {
    val types = typeFinder.varTypes
    val unprimedTypes = types.filter(!_._1.endsWith("'"))
    typeFinder.reset(unprimedTypes)
  }

  // remove non-primed variables and rename primed variables to non-primed
  private def shiftBinding(binding: Binding, constants: Set[String]): Binding = {
    Binding(forgetNonPrimed(binding, constants).toMap
      .map(p => (p._1.stripSuffix("'"), p._2)))
  }

  // remove primed variables
  private def forgetPrimed(binding: Binding): Binding = {
    Binding(binding.toMap.filter(p => !p._1.endsWith("'")))
  }

  // remove non-primed variables, except the provided constants
  private def forgetNonPrimed(binding: Binding, constants: Set[String]): Binding = {
    Binding(binding.toMap.filter(p => p._1.endsWith("'") || constants.contains(p._1)))
  }

  // does the transition number satisfy the given filter at the given step?
  private def stepMatchesFilter(stepNo: Int, transitionNo: Int): Boolean = {
    if (stepFilters.size <= stepNo) {
      true // no filter applied
    } else {
      transitionNo.toString.matches("^%s$".format(stepFilters(stepNo)))
    }
  }

  private def dumpEnabledMap(): Unit = {
    val filename = "enabled-map.txt"
    val writer = new PrintWriter(new FileWriter(filename, false))
    val transitionsCnt = checkerInput.nextTransitions.size
    writer.println("The map of enabled transitions:")
    val hrule = "----%s".format((0 until transitionsCnt map (_ => "-")) mkString "")
    writer.println(hrule)
    writer.println("    %s".format(0 until transitionsCnt map (i => ((i / 100) % 10).toString) mkString ""))
    writer.println("    %s".format(0 until transitionsCnt map (i => ((i / 10) % 10).toString) mkString ""))
    writer.println("    %s".format(0 until transitionsCnt map (i => (i % 10).toString) mkString ""))
    writer.println(hrule)
    for ((enabled, stepNo) <- enabledList.zipWithIndex) {
      val set = Set(enabled: _*)
      val line = 0 until transitionsCnt map (i => if (set.contains(i)) "*" else " ") mkString ""
      writer.println(s"%3d:%s".format(stepNo, line))
    }
    writer.println(hrule)
    writer.close()
  }

  private def printRewriterSourceLoc(): Unit = {
    //    def getSourceLocation(ex: TlaEx) = sourceStore.find(ex.ID)
    def getSourceLocation(ex: TlaEx) = {
      val sourceLocator: SourceLocator = SourceLocator(
        sourceStore.makeSourceMap,
        changeListener
      )
      sourceLocator.sourceOf(ex)
    }

    rewriter.getRewritingStack().find(getSourceLocation(_).isDefined) match {
      case None =>
        logger.error("Unable find the source of the problematic expression")

      case Some(ex) =>
        val loc = getSourceLocation(ex).get
        logger.error(s"The problem occurs around the source location $loc")
    }
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Ivan
 * Date: 25.12.2016
 * Time: 14:40
 */

namespace Group\Model;

use RuntimeException;
use Zend\Db\TableGateway\TableGatewayInterface;

class GroupTable
{
    private $tableGateway;

    public function __construct(TableGatewayInterface $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        return $this->tableGateway->select();
    }

    public function getGroup($groupId)
    {
        $groupId = (int)$groupId;
        $rowset = $this->tableGateway->select(['groupId' => $groupId]);
        $row = $rowset->current();
        if (!$row) {
            throw new RuntimeException(sprintf(
                'Could not find row with identifier %d',
                $groupId
            ));
        }

        return $row;
    }

    public function saveGroup(Group $group)
    {
        $data = [
            'groupId' => $group->groupId,
            'name'      => $group -> name
        ];

        $groupId = (int)$group->groupId;

        if ($groupId === 0) {
            $this->tableGateway->insert($data);
            return;
        }

        if (!$this->getGroup($groupId)) {
            throw new RuntimeException(sprintf(
                'Cannot update album with identifier %d; does not exist',
                $groupId
            ));
        }

        $this->tableGateway->update($data, ['groupId' => $groupId]);
    }

    public function deleteGroup($groupId)
    {
        $this->tableGateway->delete(['groupId' => (int)$groupId]);
    }

}


text:
define([
	'dojo/has',
	'dojo/has!host-node?dojo/node!fs',
	'dojo/has!host-node?dojo/node!istanbul/lib/report/common/defaults',
	'dojo/lang',
	'dojo/aspect',
	'dojo/Promise'
], function (has, fs, istanbulDefaults, lang, aspect, Promise) {
	function noop() {}

	/**
	 * A Reporter that wraps a legacy reporter definition object.
	 */
	var LegacyReporter = (function () {
		// topics that don't directly map to reporter events
		var TOPIC_TO_EVENT = {
			'/test/new': 'newTest',
			'/suite/new': 'newSuite',
			'/client/end': 'runEnd',
			'/error': 'fatalError',
			'/runner/end': 'runEnd',
			'/runner/start': 'runStart',
			'/tunnel/stop': 'tunnelEnd',
			start: 'run',
			stop: 'destroy'
		};

		/**
		 * Converts a legacy Intern 2 reporter to an Intern 3 reporter instance.
		 */
		function LegacyReporter(reporterMap) {
			var callback;
			var eventName;

			// add all of the properties on the reporterMap that look like topics or map to a known
			// reporter method (e.g., start)
			for (var topicId in reporterMap) {
				callback = reporterMap[topicId];
				eventName = null;

				if (topicId in TOPIC_TO_EVENT) {
					eventName = TOPIC_TO_EVENT[topicId];
				}
				// programmatically transform legacy topic ID to event name
				else if (topicId.charAt(0) === '/') {
					eventName = topicId.slice(1).replace(/\/(\w)/g, function (_, firstLetter) {
						return firstLetter.toUpperCase();
					});
				}
				else {
					continue;
				}

				aspect.before(this, eventName, (function (callback) {
					return function () {
						return callback.apply(reporterMap, arguments);
					};
				})(callback));
			}
		}

		return LegacyReporter;
	})();

	/**
	 * A class that manages a set of reporters
	 *
	 * Standard events:
	 *     coverage
	 *     fatalError
	 *     newSuite
	 *     newTest
	 *     proxyEnd
	 *     proxyStart
	 *     runEnd
	 *     runStart
	 *     start
	 *     stop
	 *     suiteEnd
	 *     suiteError
	 *     suiteStart
	 *     testEnd
	 *     testPass
	 *     testSkip
	 *     testStart
	 *     tunnelDownloadProgress
	 *     tunnelEnd
	 *     tunnelStart
	 *     tunnelStatus
	 */
	function ReporterManager() {
		this._earlyEvents = [];
		this._reporters = [];
	}

	function defineLazyProperty(object, property, getter) {
		Object.defineProperty(object, property, {
			get: function () {
				var value = getter.apply(this, arguments);
				Object.defineProperty(object, property, {
					value: value,
					configurable: true,
					enumerable: true
				});
				return value;
			},
			configurable: true,
			enumerable: true
		});
	}

	ReporterManager.prototype = {
		constructor: ReporterManager,
		_earlyEvents: null,
		_reporters: null,

		/**
		 * Add a reporter to the list of managed reporters.
		 *
		 * @param {string} name event name to emit
		 */
		add: function (Reporter, config) {
			var reporter;

			if (typeof Reporter === 'object') {
				reporter = new LegacyReporter(Reporter);
			}
			else {
				config = Object.create(config);
				config.console = this._getConsole();

				// https://github.com/gotwarlost/istanbul/issues/358
				if ('watermarks' in config) {
					config.watermarks = lang.mixin(istanbulDefaults.watermarks(), config.watermarks);
				}

				if (has('host-node')) {
					/* jshint node:true */
					if (config.filename) {
						// Lazily create the writable stream so we do not open an extra fd for reporters that use
						// `filename` directly and never touch `config.output`
						defineLazyProperty(config, 'output', function () {
							return fs.createWriteStream(config.filename);
						});
					}
					else {
						// See theintern/intern#454; all \r must be replaced by \x1b[1G (cursor move to column 1)
						// on Windows due to a libuv bug
						var write;
						if (process.platform === 'win32') {
							write = function (data) {
								var args;
								if (typeof data === 'string' && data.indexOf('\r') !== -1) {
									data = data.replace(/\r/g, '\x1b[1G');
									args = [ data ].concat(Array.prototype.slice.call(arguments, 1));
								}
								else {
									args = arguments;
								}

								return process.stdout.write.apply(process.stdout, args);
							};
						}
						else {
							write = process.stdout.write.bind(process.stdout);
						}

						config.output = lang.delegate(process.stdout, {
							write: write,
							// Allow reporters to call `end` regardless of whether or not they are outputting to file,
							// without an error for stdout (which cannot be closed)
							end: write
						});
					}
				}
				else if (has('host-browser')) {
					defineLazyProperty(config, 'output', function () {
						var element = document.createElement('pre');

						return {
							write: function (chunk, encoding, callback) {
								element.appendChild(document.createTextNode(chunk));
								callback();
							},
							end: function (chunk, encoding, callback) {
								element.appendChild(document.createTextNode(chunk));
								document.body.appendChild(element);
								callback();
							}
						};
					});
				}

				reporter = new Reporter(config);
			}

			var reporters = this._reporters;
			reporters.push(reporter);

			return {
				remove: function () {
					this.remove = noop;
					lang.pullFromArray(reporters, reporter);
					return reporter.destroy && reporter.destroy();
				}
			};
		},

		empty: function () {
			this._reporters.forEach(function (reporter) {
				reporter.destroy && reporter.destroy();
			});
			this._reporters = [];
		},

		/**
		 * Emit an event to all registered reporters that can respond to it.
		 *
		 * @param {string} name event name to emit
		 * @returns {Promise.<void>}
		 */
		emit: function (name) {
			if (!this._reporters.length) {
				this._earlyEvents.push(Array.prototype.slice.call(arguments, 0));
				return Promise.resolve();
			}

			var self = this;
			var allArgs = arguments;
			var args = Array.prototype.slice.call(allArgs, 1);

			return Promise.all(this._reporters.map(function (reporter) {
				var listener = reporter[name];
				var sendArgs = args;

				if (!listener && reporter.$others) {
					listener = reporter.$others;
					sendArgs = allArgs;
				}

				if (listener) {
					// In the case that a fatal error occurs and there are no reporters around that care,
					// the pre-executor will make a hail mary pass to try to get the information out by sending it to
					// the early error reporter if the error does not have a `reported` property
					if (name === 'fatalError' && args[0]) {
						args[0].reported = true;
					}

					try {
						var result = listener.apply(reporter, sendArgs);
						if (result && result.then && name !== 'reporterError') {
							return result.then(null, function (error) {
								return self.emit('reporterError', reporter, error);
							});
						}
						else {
							return result;
						}
					}
					catch (error) {
						if (name !== 'reporterError') {
							return self.emit('reporterError', reporter, error);
						}
						else {
							return Promise.reject(error);
						}
					}
				}
			})).then(noop, noop);
		},

		on: function (eventName, listener) {
			var reporter = {};
			reporter[eventName] = listener;

			var reporters = this._reporters;
			reporters.push(reporter);

			return {
				remove: function () {
					this.remove = function () {};
					lang.pullFromArray(reporters, reporter);
					reporters = reporter = null;
				}
			};
		},

		_getConsole: function () {
			if (typeof console !== 'undefined') {
				return console;
			}

			var fakeConsole = {};

			[
				'assert',
				'count',
				'dir',
				'error',
				'exception',
				'info',
				'log',
				'table',
				'time',
				'timeEnd',
				'trace',
				'warn'
			].forEach(function (key) {
				fakeConsole[key] = noop;
			});

			return fakeConsole;
		},

		run: function () {
			var self = this;

			function emitEarlyEvents() {
				var promise = Promise.all(self._earlyEvents.map(function (event) {
					return self.emit.apply(self, event);
				}));
				self._earlyEvents.splice(0, Infinity);
				return promise.then(noop, noop);
			}

			return this
				.emit('run')
				.then(emitEarlyEvents);
		}
	};

	return ReporterManager;
});


text:
package com.dtolabs.rundeck.core.jobs;

import com.dtolabs.rundeck.core.execution.workflow.StepExecutionContext;

import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * Status result returned from job lifecycle event handlers
 */
public interface JobLifecycleStatus
        extends LifecycleStatus
{

    /**
     * @return option values to use when isUseNewValues is true
     */
    default Map getOptionsValues(){ return null; }

    /**
     *
     * @return options to use when isUseNewValues is true
     */
    default SortedSet<JobOption> getOptions() {
        return new TreeSet<>();
    }
}


text:
package org.kuali.rice.krms.test;

import org.junit.Before;
import org.junit.Test;
import org.kuali.rice.core.api.criteria.QueryByCriteria;
import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
import org.kuali.rice.krms.api.repository.reference.ReferenceObjectBinding;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;
import static org.kuali.rice.core.api.criteria.PredicateFactory.equal;
import static org.kuali.rice.core.api.criteria.PredicateFactory.in;

/**
 *   RuleManagementReferenceObjectBindingTest is to test the methods of ruleManagementServiceImpl relating to ReferenceObjectBindings
 *
 *   Each test focuses on one of the methods.
 */
public class RuleManagementReferenceObjectBindingTest extends RuleManagementBaseTest {
    @Override
    @Before
    public void setClassDiscriminator() {
        // set a unique discriminator for test objects of this class
        CLASS_DISCRIMINATOR = "RMROBT";
    }

    /**
     *  Test testCreateReferenceObjectBinding()
     *
     *  This test focuses specifically on the RuleManagementServiceImpl .createTestReferenceObjectBinding(ReferenceObjectBinding) method
     */
    @Test
    public void testCreateReferenceObjectBinding() {
        // get a set of unique object names for use by this test (discriminator passed can be any unique value within this class)
        RuleManagementBaseTestObjectNames t0 =  new RuleManagementBaseTestObjectNames( CLASS_DISCRIMINATOR, "t0");

        // create a ReferenceObjectBinding entry
        ReferenceObjectBinding.Builder refObjBindingBuilder =  createTestReferenceObjectBinding(t0.object0);
        ReferenceObjectBinding refObjBinding = ruleManagementService.getReferenceObjectBinding(
                refObjBindingBuilder.getId());
        refObjBindingBuilder =  ReferenceObjectBinding.Builder.create(refObjBinding);

        // verify the Created entry
        assertNotNull("Created ReferenceObjectBinding not found", refObjBindingBuilder);
        assertEquals("Invalid CollectionName of refObjBindingBuilder found", "ParkingPolicies",
                refObjBindingBuilder.getCollectionName());
        assertEquals("Invalid KrmsObjectId of refObjBindingBuilder found",t0.agenda_Id, refObjBindingBuilder.getKrmsObjectId());
        assertEquals("Invalid KrmsDiscriminatorType of refObjBindingBuilder found",
                krmsTypeRepository.getTypeByName(t0.namespaceName, "AgendaType" + t0.object0).getId(), refObjBindingBuilder.getKrmsDiscriminatorType() );
        assertEquals("Invalid Namespace of refObjBindingBuilder found",t0.namespaceName, refObjBindingBuilder.getNamespace());
        assertEquals("Invalid ReferenceObjectId of refObjBindingBuilder found",t0.referenceObject_0_Id, refObjBindingBuilder.getReferenceObjectId());
        assertEquals("Invalid ReferenceDiscriminatorType of refObjBindingBuilder found",
                t0.referenceObject_0_DiscriminatorType, refObjBindingBuilder.getReferenceDiscriminatorType());
        assertEquals("Invalid Active value of refObjBindingBuilder found",true, refObjBindingBuilder.isActive());

        // try to create a ReferenceObjectBinding which already exists
        try {
            ruleManagementService.createReferenceObjectBinding(refObjBindingBuilder.build());
            fail("Should have thrown IllegalStateException: the ReferenceObjectBinding to create already exists");
        } catch (Exception e) {
            // throws IllegalStateException: the ReferenceObjectBinding to create already exists
        }

        // try to create a ReferenceObjectBinding entry which exists using a different Id
        refObjBindingBuilder.setId("RefObjBindIdChanged");
        try {
            ruleManagementService.createReferenceObjectBinding(refObjBindingBuilder.build());
            fail("Should have thrown DataIntegrityViolationException: OJB operation; SQL []; Duplicate entry");
        } catch (Exception e) {
            // throws DataIntegrityViolationException: OJB operation; SQL []; Duplicate entry
        }
    }

    /**
     *  Test testGetReferenceObjectBinding()
     *
     *  This test focuses specifically on the RuleManagementServiceImpl .getReferenceObjectBinding("ReferenceObjectId") method
     */
    @Test
    public void testGetReferenceObjectBinding() {
        // get a set of unique object names for use by this test (discriminator passed can be any unique value within this class)
        RuleManagementBaseTestObjectNames t1 =  new RuleManagementBaseTestObjectNames( CLASS_DISCRIMINATOR, "t1");

        ReferenceObjectBinding.Builder refObjBindingBuilder =  createTestReferenceObjectBinding(t1.object0);

        ReferenceObjectBinding refObjBinding = ruleManagementService.getReferenceObjectBinding(
                refObjBindingBuilder.getId());
        assertNotNull("ReferenceObjectBinding should have been returned",refObjBinding);
        assertEquals("Incorrect value found on returned ReferenceObjectBinding",t1.referenceObject_0_Id,refObjBinding.getReferenceObjectId());

        // try to getReferenceObjectBinding using null Id
        try {
            refObjBinding = ruleManagementService.getReferenceObjectBinding(null);
            fail("Should have thrown IllegalArgumentException: referenceObjectBindingId was null");
        } catch (Exception e) {
            // throws IllegalArgumentException: referenceObjectBindingId was null
        }

        // try to find a ReferenceObjectBinding using a non-existent Id
        assertNull("ReferenceObjectBinding should not have been found", ruleManagementService.getReferenceObjectBinding("junk_value"));
    }

    /**
     *  Test testGetReferenceObjectBindings()
     *
     *  This test focuses specifically on the RuleManagementServiceImpl .getReferenceObjectBindings(List<ReferenceObjectBinding>) method
     */
    @Test
    public void testGetReferenceObjectBindings() {
        // get a set of unique object names for use by this test (discriminator passed can be any unique value within this class)
        RuleManagementBaseTestObjectNames t2 =  new RuleManagementBaseTestObjectNames( CLASS_DISCRIMINATOR, "t2");

        List<String> referenceObjectBindingIds = new ArrayList<String>();
        referenceObjectBindingIds.add(createTestReferenceObjectBinding(t2.object0).getId());
        referenceObjectBindingIds.add(createTestReferenceObjectBinding(t2.object1).getId());
        referenceObjectBindingIds.add(createTestReferenceObjectBinding(t2.object2).getId());

        List<ReferenceObjectBinding> referenceObjectBindings = ruleManagementService.getReferenceObjectBindings(referenceObjectBindingIds);
        int objectsFound = 0;
        for ( ReferenceObjectBinding referenceObjectBinding : referenceObjectBindings) {
            if ( referenceObjectBindingIds.contains( referenceObjectBinding.getId())) {
                objectsFound++;
            } else {
                fail("Unexpected object returned");
            }
        }
        assertEquals("Expected number of objects not returned",3,objectsFound);

        // try to getReferenceObjectBindings using a null Id List
        try {
            ruleManagementService.getReferenceObjectBindings(null);
            fail("Should have thrown IllegalArgumentException: reference binding object ids must not be null");
        } catch (IllegalArgumentException e) {
            // throws IllegalArgumentException: reference binding object ids must not be null
        }

        assertEquals("Incorrect number of objects returned", 0, ruleManagementService.getReferenceObjectBindings(new ArrayList<String>()).size());

        // try requesting a list of objects with a bad value in it
        referenceObjectBindingIds.add("junkValue");
        referenceObjectBindings = ruleManagementService.getReferenceObjectBindings(referenceObjectBindingIds);
        objectsFound = 0;
        for ( ReferenceObjectBinding referenceObjectBinding : referenceObjectBindings) {
            if ( referenceObjectBindingIds.contains( referenceObjectBinding.getId())) {
                objectsFound++;
            } else {
                fail("Unexpected object returned");
            }
        }
        assertEquals("Expected number of objects not returned",3,objectsFound);
    }

    /**
     *  Test testFindReferenceObjectBindingsByReferenceObject()
     *
     *  This test focuses specifically on the RuleManagementServiceImpl .findReferenceObjectBindingsByReferenceObject("ReferenceObjectId") method
     */
    @Test
    public void testFindReferenceObjectBindingsByReferenceObject() {
        // get a set of unique object names for use by this test (discriminator passed can be any unique value within this class)
        RuleManagementBaseTestObjectNames t3 =  new RuleManagementBaseTestObjectNames( CLASS_DISCRIMINATOR, "t3");
        ReferenceObjectBinding.Builder refObjBindingBuilder =  createTestReferenceObjectBinding(t3.object0);

        //assertEquals("",refObjBindingBuilder.getId(),
        List<ReferenceObjectBinding> referenceObjectBindings = ruleManagementService.findReferenceObjectBindingsByReferenceObject(
                refObjBindingBuilder.getReferenceDiscriminatorType(), refObjBindingBuilder.getReferenceObjectId());
        assertEquals("Incorrect number of objects returned",1,referenceObjectBindings.size());

        // test findReferenceObjectBindingsByReferenceObject with null object discriminator
        try {
            ruleManagementService.findReferenceObjectBindingsByReferenceObject(null,refObjBindingBuilder.getReferenceObjectId());
            fail("should have thrown RiceIllegalArgumentException: reference binding object discriminator type must not be null");
        } catch (RiceIllegalArgumentException e) {
            // throws RiceIllegalArgumentException: reference binding object discriminator type must not be null
        }

        // test findReferenceObjectBindingsByReferenceObject with null reference object id
        try {
            ruleManagementService.findReferenceObjectBindingsByReferenceObject(refObjBindingBuilder.getReferenceDiscriminatorType(),null);
            fail("should have thrown RiceIllegalArgumentException: reference object id must not be null");
        } catch (RiceIllegalArgumentException e) {
            // throws RiceIllegalArgumentException: reference object id must not be null
        }

        // test with bad values for object discriminator and object id
        referenceObjectBindings = ruleManagementService.findReferenceObjectBindingsByReferenceObject("junkvalue","junkvalue");
        assertEquals("Incorrect number of objects returned",0,referenceObjectBindings.size());
    }

    /**
     *  Test testFindReferenceObjectBindingsByReferenceDiscriminatorType()
     *
     *  This test focuses specifically on the RuleManagementServiceImpl
     *      .findReferenceObjectBindingsByReferenceDiscriminatorType("ReferenceDiscriminatorType") method
     */
    @Test
    public void testFindReferenceObjectBindingsByReferenceDiscriminatorType() {
        // get a set of unique object names for use by this test (discriminator passed can be any unique value within this class)
        RuleManagementBaseTestObjectNames t4 =  new RuleManagementBaseTestObjectNames( CLASS_DISCRIMINATOR, "t4");

        // create two ReferenceObjectBindings with same ReferenceDiscriminatorType
        ReferenceObjectBinding.Builder refObjBindingBuilder =  createTestReferenceObjectBinding(t4.object0);
        refObjBindingBuilder.setReferenceDiscriminatorType("ParkingAffiliationType" + t4.discriminator);
        ruleManagementService.updateReferenceObjectBinding(refObjBindingBuilder.build());

        refObjBindingBuilder =  createTestReferenceObjectBinding(t4.object1);
        refObjBindingBuilder.setReferenceDiscriminatorType("ParkingAffiliationType" + t4.discriminator);
        ruleManagementService.updateReferenceObjectBinding(refObjBindingBuilder.build());

        List<ReferenceObjectBinding> referenceObjectBindings = ruleManagementService.findReferenceObjectBindingsByReferenceDiscriminatorType(
                refObjBindingBuilder.getReferenceDiscriminatorType());
        assertEquals("Incorrect number of objects returned",2,referenceObjectBindings.size());

        // check with blank ReferenceDiscriminatorType
        try {
            ruleManagementService.findReferenceObjectBindingsByReferenceDiscriminatorType("   ");
            fail("Should have thrown IllegalArgumentException: referenceDiscriminatorType is null or blank");
        } catch (IllegalArgumentException e) {
            // throws IllegalArgumentException: referenceDiscriminatorType is null or blank
        }

        // check with null ReferenceDiscriminatorType
        try {
            ruleManagementService.findReferenceObjectBindingsByReferenceDiscriminatorType(null);
            fail("Should have thrown IllegalArgumentException: referenceDiscriminatorType is null or blank");
        } catch (IllegalArgumentException e) {
            // throws IllegalArgumentException: referenceDiscriminatorType is null or blank
        }
    }

    /**
     *  Test testFindReferenceObjectBindingsByKrmsDiscriminatorType()
     *
     *  This test focuses specifically on the RuleManagementServiceImpl
     *      .findReferenceObjectBindingsByKrmsDiscriminatorType("KrmsDiscriminatorType") method
     */
    @Test
    public void testFindReferenceObjectBindingsByKrmsDiscriminatorType() {
        // get a set of unique object names for use by this test (discriminator passed can be any unique value within this class)
        RuleManagementBaseTestObjectNames t5 =  new RuleManagementBaseTestObjectNames( CLASS_DISCRIMINATOR, "t5");

        // create two ReferenceObjectBindings with same KrmsDiscriminatorType
        ReferenceObjectBinding.Builder refObjBindingBuilder6008 =  createTestReferenceObjectBinding(t5.object0);

        ReferenceObjectBinding.Builder refObjBindingBuilder6009 =  createTestReferenceObjectBinding(t5.object1);
        refObjBindingBuilder6009.setKrmsDiscriminatorType(refObjBindingBuilder6008.getKrmsDiscriminatorType());
        ruleManagementService.updateReferenceObjectBinding(refObjBindingBuilder6009.build());

        List<ReferenceObjectBinding> referenceObjectBindings = ruleManagementService.findReferenceObjectBindingsByKrmsDiscriminatorType(refObjBindingBuilder6008.getKrmsDiscriminatorType());
        assertEquals("Incorrect number of objects returned",2,referenceObjectBindings.size());

        // check with blank KrmsDiscriminatorType
        try {
            ruleManagementService.findReferenceObjectBindingsByKrmsDiscriminatorType("   ");
            fail("Should have thrown IllegalArgumentException: krmsDiscriminatorType is null or blank");
        } catch (IllegalArgumentException e) {
            // throws IllegalArgumentException: krmsDiscriminatorType is null or blank
        }

        // check with null KrmsDiscriminatorType
        try {
            ruleManagementService.findReferenceObjectBindingsByKrmsDiscriminatorType(null);
            fail("Should have thrown IllegalArgumentException: krmsDiscriminatorType is null or blank");
        } catch (IllegalArgumentException e) {
            // throws IllegalArgumentException: krmsDiscriminatorType is null or blank
        }
    }

    /**
     *  Test testFindReferenceObjectBindingsByKrmsObject()
     *
     *  This test focuses specifically on the RuleManagementServiceImpl
     *      .findReferenceObjectBindingsByKrmsObject("KrmsObjectId") method
     */
    @Test
    public void testFindReferenceObjectBindingsByKrmsObject() {
        // get a set of unique object names for use by this test (discriminator passed can be any unique value within this class)
        RuleManagementBaseTestObjectNames t6 =  new RuleManagementBaseTestObjectNames( CLASS_DISCRIMINATOR, "t6");

        // create two ReferenceObjectBindings with same KrmsObjectId
        ReferenceObjectBinding.Builder refObjBindingBuilder0 =  createTestReferenceObjectBinding(t6.object0);

        ReferenceObjectBinding.Builder refObjBindingBuilder1 =  createTestReferenceObjectBinding(t6.object1);
        refObjBindingBuilder1.setKrmsObjectId(refObjBindingBuilder0.getKrmsObjectId());
        ruleManagementService.updateReferenceObjectBinding(refObjBindingBuilder1.build());

        List<ReferenceObjectBinding> referenceObjectBindings = ruleManagementService.findReferenceObjectBindingsByKrmsObject(
                refObjBindingBuilder0.getKrmsObjectId());
        assertEquals("Incorrect number of objects returned",2,referenceObjectBindings.size());

        // check with blank KrmsObjectId
        try {
            ruleManagementService.findReferenceObjectBindingsByKrmsObject("   ");
            fail("Should have thrown IllegalArgumentException: krmsObjectId is null or blank");
        } catch (IllegalArgumentException e) {
            // throws IllegalArgumentException: krmsObjectId is null or blank
        }

        // check with null KrmsObjectId
        try {
            ruleManagementService.findReferenceObjectBindingsByKrmsObject(null);
            fail("Should have thrown IllegalArgumentException: krmsObjectId is null or blank");
        } catch (IllegalArgumentException e) {
            // throws IllegalArgumentException: krmsObjectId is null or blank
        }
    }

    /**
     *  Test testUpdateReferenceObjectBinding()
     *
     *  This test focuses specifically on the RuleManagementServiceImpl .updateReferenceObjectBinding(ReferenceObjectBinding) method
     */
    @Test
    public void testUpdateReferenceObjectBinding() {
        // get a set of unique object names for use by this test (discriminator passed can be any unique value within this class)
        RuleManagementBaseTestObjectNames t7 =  new RuleManagementBaseTestObjectNames( CLASS_DISCRIMINATOR, "t7");

        ReferenceObjectBinding.Builder refObjBindingBuilder =  createTestReferenceObjectBinding(t7.object0);

        ReferenceObjectBinding refObjBinding = ruleManagementService.getReferenceObjectBinding(refObjBindingBuilder.getId());
        refObjBindingBuilder =  ReferenceObjectBinding.Builder.create(refObjBinding);

        // verify all current values
        assertNotNull("Created ReferenceObjectBinding not found", refObjBindingBuilder);
        assertEquals("Invalid CollectionName of refObjBindingBuilder found","ParkingPolicies", refObjBindingBuilder.getCollectionName());
        assertEquals("Invalid KrmsObjectId of refObjBindingBuilder found",t7.agenda_Id, refObjBindingBuilder.getKrmsObjectId());
        assertEquals("Invalid KrmsDiscriminatorType of refObjBindingBuilder found",
                krmsTypeRepository.getTypeByName(t7.namespaceName, "AgendaType"+t7.object0).getId(),
                refObjBindingBuilder.getKrmsDiscriminatorType() );
        assertEquals("Invalid Namespace of refObjBindingBuilder found",t7.namespaceName, refObjBindingBuilder.getNamespace());
        assertEquals("Invalid ReferenceObjectId of refObjBindingBuilder found",t7.referenceObject_0_Id, refObjBindingBuilder.getReferenceObjectId());
        assertEquals("Invalid ReferenceDiscriminatorType  of refObjBindingBuilder found","ParkingAffiliationType",
                refObjBindingBuilder.getReferenceDiscriminatorType());
        assertEquals("Invalid Active value of refObjBindingBuilder found",true, refObjBindingBuilder.isActive());

        // change everything but the id and submit update
        refObjBindingBuilder.setCollectionName("ParkingPolicies6Changed");
        refObjBindingBuilder.setKrmsObjectId("AgendaId6Changed");
        refObjBindingBuilder.setKrmsDiscriminatorType("KDTtype6Changed");
        refObjBindingBuilder.setNamespace("Namespace6Changed");
        refObjBindingBuilder.setReferenceObjectId("PA6Changed");
        refObjBindingBuilder.setReferenceDiscriminatorType("ParkingAffiliationTypeChanged");
        refObjBindingBuilder.setActive(false);
        ruleManagementService.updateReferenceObjectBinding(refObjBindingBuilder.build());

        // verify updated values
        refObjBinding = ruleManagementService.getReferenceObjectBinding(refObjBindingBuilder.getId());
        refObjBindingBuilder =  ReferenceObjectBinding.Builder.create(refObjBinding);
        assertNotNull("Created ReferenceObjectBinding not found", refObjBindingBuilder);
        assertEquals("Invalid CollectionName of refObjBindingBuilder found", "ParkingPolicies6Changed",
                refObjBindingBuilder.getCollectionName());
        assertEquals("Invalid KrmsObjectId of refObjBindingBuilder found","AgendaId6Changed", refObjBindingBuilder.getKrmsObjectId());
        assertEquals("Invalid KrmsDiscriminatorType of refObjBindingBuilder found","KDTtype6Changed", refObjBindingBuilder.getKrmsDiscriminatorType() );
        assertEquals("Invalid Namespace of refObjBindingBuilder found","Namespace6Changed", refObjBindingBuilder.getNamespace());
        assertEquals("Invalid ReferenceObjectId of refObjBindingBuilder found","PA6Changed", refObjBindingBuilder.getReferenceObjectId());
        assertEquals("Invalid ReferenceDiscriminatorType  of refObjBindingBuilder found","ParkingAffiliationTypeChanged", refObjBindingBuilder.getReferenceDiscriminatorType());
        assertEquals("Invalid Active value of refObjBindingBuilder found",false, refObjBindingBuilder.isActive());

        // update a object which does not exist
        refObjBindingBuilder.setId("junkValue");
        try {
            ruleManagementService.updateReferenceObjectBinding(refObjBindingBuilder.build());
            fail("Should have thrown IllegalStateException: the ReferenceObjectBinding to update does not exists");
        } catch (IllegalStateException e) {
            // throws IllegalStateException: the ReferenceObjectBinding to update does not exists
        }
    }

    /**
     *  Test testDeleteReferenceObjectBinding()
     *
     *  This test focuses specifically on the RuleManagementServiceImpl
     *       .deleteReferenceObjectBinding("referenceObjectBinding id") method
     */
    @Test
    public void testDeleteReferenceObjectBinding() {
        // get a set of unique object names for use by this test (discriminator passed can be any unique value within this class)
        RuleManagementBaseTestObjectNames t8 =  new RuleManagementBaseTestObjectNames( CLASS_DISCRIMINATOR, "t8");

        ReferenceObjectBinding.Builder refObjBindingBuilder =  createTestReferenceObjectBinding(t8.object0);
        ReferenceObjectBinding refObjBinding = ruleManagementService.getReferenceObjectBinding(refObjBindingBuilder.getId());
        refObjBindingBuilder =  ReferenceObjectBinding.Builder.create(refObjBinding);
        assertNotNull("Created ReferenceObjectBinding not found", refObjBindingBuilder);

        // delete the ReferenceObjectBinding entry
        ruleManagementService.deleteReferenceObjectBinding(refObjBinding.getId());
        assertNull("Deleted ReferenceObjectBinding found", ruleManagementService.getReferenceObjectBinding(
                refObjBindingBuilder.getId()));

        // try to delete it a second time
        try {
            ruleManagementService.deleteReferenceObjectBinding(refObjBinding.getId());
            fail("should have thrown IllegalStateException: the ReferenceObjectBinding to delete does not exists");
        } catch (IllegalStateException e) {
            // throws IllegalStateException: the ReferenceObjectBinding to delete does not exists
        }

        // try to delete using null
        try {
            ruleManagementService.deleteReferenceObjectBinding(null);
            fail("should have thrown IllegalArgumentException: referenceObjectBindingId was null");
        } catch (IllegalArgumentException e) {
            // throws IllegalArgumentException: referenceObjectBindingId was null
        }
    }

    /**
     *  Test testFindReferenceObjectBindingIds()
     *
     *  This test focuses specifically on the RuleManagementServiceImpl
     *       .findReferenceObjectBindingIds(QueryByCriteria) method
     */
    @Test
    public void testFindReferenceObjectBindingIds() {
        // get a set of unique object names for use by this test (discriminator passed can be any unique value within this class)
        RuleManagementBaseTestObjectNames t9 =  new RuleManagementBaseTestObjectNames( CLASS_DISCRIMINATOR, "t9");

        // build three objects to search for.  Two active and one not active
        List<String> refObjBindingBuilderIds = new ArrayList<String>();
        ReferenceObjectBinding.Builder refObjBindingBuilder =  createTestReferenceObjectBinding(t9.object0);
        refObjBindingBuilderIds.add(refObjBindingBuilder.getId());
        refObjBindingBuilder =  createTestReferenceObjectBinding(t9.object1);
        refObjBindingBuilderIds.add(refObjBindingBuilder.getId());
        refObjBindingBuilder =  createTestReferenceObjectBinding(t9.object2);
        refObjBindingBuilderIds.add(refObjBindingBuilder.getId());
        refObjBindingBuilder.setActive(false);
        ruleManagementService.updateReferenceObjectBinding(refObjBindingBuilder.build());

        // Find the three ReferenceObjectBindings by id list
        QueryByCriteria.Builder query = QueryByCriteria.Builder.create();
        query.setPredicates(in("id", refObjBindingBuilderIds.toArray(new String[]{})));

        List<String> referenceObjectBindingIds = ruleManagementService.findReferenceObjectBindingIds(query.build());
        for (String referenceObjectBindingId : referenceObjectBindingIds ) {
            assertTrue(refObjBindingBuilderIds.contains(referenceObjectBindingId));
        }

        assertEquals("incorrect number of ReferenceObjectBindingIds found", 3, referenceObjectBindingIds.size());

        // find the two active ReferenceObjectBindings in the list
        query = QueryByCriteria.Builder.create();
        query.setPredicates( equal("active","Y"), in("id", refObjBindingBuilderIds.toArray(new String[]{})));

        referenceObjectBindingIds = ruleManagementService.findReferenceObjectBindingIds(query.build());
        for (String referenceObjectBindingId : referenceObjectBindingIds ) {
            assertTrue(refObjBindingBuilderIds.contains(referenceObjectBindingId));
        }

        assertEquals("incorrect number of ReferenceObjectBindingIds found", 2, referenceObjectBindingIds.size());
    }
}


text:
<?php

namespace Recover\ErecoverBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Recover\ErecoverBundle\Entity\Rubrique;
use Recover\ErecoverBundle\Form\RubriqueType;

/**
 * Rubrique controller.
 *
 */
class RubriqueController extends Controller
{

    /**
     * Lists all Rubrique entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('RecoverErecoverBundle:Rubrique')->findAll();

        return $this->render('RecoverErecoverBundle:Rubrique:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Rubrique entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new Rubrique();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('rubrique_show', array('id' => $entity->getId())));
        }

        return $this->render('RecoverErecoverBundle:Rubrique:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Rubrique entity.
     *
     * @param Rubrique $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Rubrique $entity)
    {
        $form = $this->createForm(new RubriqueType(), $entity, array(
            'action' => $this->generateUrl('rubrique_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Rubrique entity.
     *
     */
    public function newAction()
    {
        $entity = new Rubrique();
        $form   = $this->createCreateForm($entity);

        return $this->render('RecoverErecoverBundle:Rubrique:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Rubrique entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('RecoverErecoverBundle:Rubrique')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Rubrique entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('RecoverErecoverBundle:Rubrique:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Rubrique entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('RecoverErecoverBundle:Rubrique')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Rubrique entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('RecoverErecoverBundle:Rubrique:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a Rubrique entity.
    *
    * @param Rubrique $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Rubrique $entity)
    {
        $form = $this->createForm(new RubriqueType(), $entity, array(
            'action' => $this->generateUrl('rubrique_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Rubrique entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('RecoverErecoverBundle:Rubrique')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Rubrique entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('rubrique_edit', array('id' => $id)));
        }

        return $this->render('RecoverErecoverBundle:Rubrique:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Rubrique entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('RecoverErecoverBundle:Rubrique')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Rubrique entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('rubrique'));
    }

    /**
     * Creates a form to delete a Rubrique entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('rubrique_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
/**
 * Extension.ts is a lightweight wrapper around ModeHandler. It converts key
 * events to their string names and passes them on to ModeHandler via
 * handleKeyEvent().
 */
import './src/actions/include-main';

/**
 * Load configuration validator
 */

import './src/configuration/validators/inputMethodSwitcherValidator';
import './src/configuration/validators/remappingValidator';

import * as vscode from 'vscode';
import { activate as activateFunc } from './extensionBase';

// tslint:disable-next-line: no-var-requires
require('setimmediate');

export async function activate(context: vscode.ExtensionContext) {
  activateFunc(context, false);
}