text:
import {ng} from '../../utils/process';
import {expectToFail} from '../../utils/utils';

export default function() {
  return Promise.resolve()
    .then(() => expectToFail(() =>
      ng('generate', 'component', '1my-component')));
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 22(2): 365 (1985)

#### Original name
Polyporus placenta Fr., 1861

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
import * as JSRE from './JSRE';
export {JSRE};


text:
tiva-c_xtools
=============

Crosstool NG config for Tiva C microcontroller


text:
namespace _01.SinoTheWalker
{
    using System;
    using System.Globalization;

    public class SinoTheWalker
    {
        public static void Main()
        {
            DateTime time = DateTime.ParseExact(Console.ReadLine(), "HH:mm:ss", CultureInfo.InvariantCulture);
            int numberOfSteps = int.Parse(Console.ReadLine()) % 86400;
            int secondsForOneStep = int.Parse(Console.ReadLine()) % 86400;

            double tolalSeconds = numberOfSteps * secondsForOneStep;

            time = time.AddSeconds(tolalSeconds);

            Console.Write("Time Arrival: ");
            Console.WriteLine(time.ToString("HH:mm:ss"));
        }
    }
}


text:
#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
#include <ctype.h>		/* to declare isdigit(), isspace() */

LOCAL(int)
text_getc (FILE * file)
/* Read next char, skipping over any comments (# to end of line) */
/* A comment/newline sequence is returned as a newline */
{
  register int ch;

  ch = getc(file);
  if (ch == '#') {
    do {
      ch = getc(file);
    } while (ch != '\n' && ch != EOF);
  }
  return ch;
}

LOCAL(boolean)
read_text_integer (FILE * file, long * result, int * termchar)
/* Read an unsigned decimal integer from a file, store it in result */
/* Reads one trailing character after the integer; returns it in termchar */
{
  register int ch;
  register long val;

  /* Skip any leading whitespace, detect EOF */
  do {
    ch = text_getc(file);
    if (ch == EOF) {
      *termchar = ch;
      return FALSE;
    }
  } while (isspace(ch));

  if (! isdigit(ch)) {
    *termchar = ch;
    return FALSE;
  }

  val = ch - '0';
  while ((ch = text_getc(file)) != EOF) {
    if (! isdigit(ch))
      break;
    val *= 10;
    val += ch - '0';
  }
  *result = val;
  *termchar = ch;
  return TRUE;
}

GLOBAL(boolean)
read_quant_tables (j_compress_ptr cinfo, char * filename, boolean force_baseline)
/* Read a set of quantization tables from the specified file.
 * The file is plain ASCII text: decimal numbers with whitespace between.
 * Comments preceded by '#' may be included in the file.
 * There may be one to NUM_QUANT_TBLS tables in the file, each of 64 values.
 * The tables are implicitly numbered 0,1,etc.
 * NOTE: does not affect the qslots mapping, which will default to selecting
 * table 0 for luminance (or primary) components, 1 for chrominance components.
 * You must use -qslots if you want a different component->table mapping.
 */
{
  FILE * fp;
  int tblno, i, termchar;
  long val;
  unsigned int table[DCTSIZE2];

  if ((fp = fopen(filename, "r")) == NULL) {
    fprintf(stderr, "Can't open table file %s\n", filename);
    return FALSE;
  }
  tblno = 0;

  while (read_text_integer(fp, &val, &termchar)) { /* read 1st element of table */
    if (tblno >= NUM_QUANT_TBLS) {
      fprintf(stderr, "Too many tables in file %s\n", filename);
      fclose(fp);
      return FALSE;
    }
    table[0] = (unsigned int) val;
    for (i = 1; i < DCTSIZE2; i++) {
      if (! read_text_integer(fp, &val, &termchar)) {
	fprintf(stderr, "Invalid table data in file %s\n", filename);
	fclose(fp);
	return FALSE;
      }
      table[i] = (unsigned int) val;
    }
    jpeg_add_quant_table(cinfo, tblno, table, cinfo->q_scale_factor[tblno],
			 force_baseline);
    tblno++;
  }

  if (termchar != EOF) {
    fprintf(stderr, "Non-numeric data in file %s\n", filename);
    fclose(fp);
    return FALSE;
  }

  fclose(fp);
  return TRUE;
}

#ifdef C_MULTISCAN_FILES_SUPPORTED

LOCAL(boolean)
read_scan_integer (FILE * file, long * result, int * termchar)
/* Variant of read_text_integer that always looks for a non-space termchar;
 * this simplifies parsing of punctuation in scan scripts.
 */
{
  register int ch;

  if (! read_text_integer(file, result, termchar))
    return FALSE;
  ch = *termchar;
  while (ch != EOF && isspace(ch))
    ch = text_getc(file);
  if (isdigit(ch)) {		/* oops, put it back */
    if (ungetc(ch, file) == EOF)
      return FALSE;
    ch = ' ';
  } else {
    /* Any separators other than ';' and ':' are ignored;
     * this allows user to insert commas, etc, if desired.
     */
    if (ch != EOF && ch != ';' && ch != ':')
      ch = ' ';
  }
  *termchar = ch;
  return TRUE;
}

GLOBAL(boolean)
read_scan_script (j_compress_ptr cinfo, char * filename)
/* Read a scan script from the specified text file.
 * Each entry in the file defines one scan to be emitted.
 * Entries are separated by semicolons ';'.
 * An entry contains one to four component indexes,
 * optionally followed by a colon ':' and four progressive-JPEG parameters.
 * The component indexes denote which component(s) are to be transmitted
 * in the current scan.  The first component has index 0.
 * Sequential JPEG is used if the progressive-JPEG parameters are omitted.
 * The file is free format text: any whitespace may appear between numbers
 * and the ':' and ';' punctuation marks.  Also, other punctuation (such
 * as commas or dashes) can be placed between numbers if desired.
 * Comments preceded by '#' may be included in the file.
 * Note: we do very little validity checking here;
 * jcmaster.c will validate the script parameters.
 */
{
  FILE * fp;
  int scanno, ncomps, termchar;
  long val;
  jpeg_scan_info * scanptr;
#define MAX_SCANS  100		/* quite arbitrary limit */
  jpeg_scan_info scans[MAX_SCANS];

  if ((fp = fopen(filename, "r")) == NULL) {
    fprintf(stderr, "Can't open scan definition file %s\n", filename);
    return FALSE;
  }
  scanptr = scans;
  scanno = 0;

  while (read_scan_integer(fp, &val, &termchar)) {
    if (scanno >= MAX_SCANS) {
      fprintf(stderr, "Too many scans defined in file %s\n", filename);
      fclose(fp);
      return FALSE;
    }
    scanptr->component_index[0] = (int) val;
    ncomps = 1;
    while (termchar == ' ') {
      if (ncomps >= MAX_COMPS_IN_SCAN) {
	fprintf(stderr, "Too many components in one scan in file %s\n",
		filename);
	fclose(fp);
	return FALSE;
      }
      if (! read_scan_integer(fp, &val, &termchar))
	goto bogus;
      scanptr->component_index[ncomps] = (int) val;
      ncomps++;
    }
    scanptr->comps_in_scan = ncomps;
    if (termchar == ':') {
      if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
	goto bogus;
      scanptr->Ss = (int) val;
      if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
	goto bogus;
      scanptr->Se = (int) val;
      if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
	goto bogus;
      scanptr->Ah = (int) val;
      if (! read_scan_integer(fp, &val, &termchar))
	goto bogus;
      scanptr->Al = (int) val;
    } else {
      /* set non-progressive parameters */
      scanptr->Ss = 0;
      scanptr->Se = DCTSIZE2-1;
      scanptr->Ah = 0;
      scanptr->Al = 0;
    }
    if (termchar != ';' && termchar != EOF) {
bogus:
      fprintf(stderr, "Invalid scan entry format in file %s\n", filename);
      fclose(fp);
      return FALSE;
    }
    scanptr++, scanno++;
  }

  if (termchar != EOF) {
    fprintf(stderr, "Non-numeric data in file %s\n", filename);
    fclose(fp);
    return FALSE;
  }

  if (scanno > 0) {
    /* Stash completed scan list in cinfo structure.
     * NOTE: for cjpeg's use, JPOOL_IMAGE is the right lifetime for this data,
     * but if you want to compress multiple images you'd want JPOOL_PERMANENT.
     */
    scanptr = (jpeg_scan_info *)
      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
				  scanno * SIZEOF(jpeg_scan_info));
    MEMCOPY(scanptr, scans, scanno * SIZEOF(jpeg_scan_info));
    cinfo->scan_info = scanptr;
    cinfo->num_scans = scanno;
  }

  fclose(fp);
  return TRUE;
}

#endif /* C_MULTISCAN_FILES_SUPPORTED */

GLOBAL(boolean)
set_quality_ratings (j_compress_ptr cinfo, char *arg, boolean force_baseline)
/* Process a quality-ratings parameter string, of the form
 *     N[,N,...]
 * If there are more q-table slots than parameters, the last value is replicated.
 */
{
  int val = 75;			/* default value */
  int tblno;
  char ch;

  for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
    if (*arg) {
      ch = ',';			/* if not set by sscanf, will be ',' */
      if (sscanf(arg, "%d%c", &val, &ch) < 1)
	return FALSE;
      if (ch != ',')		/* syntax check */
	return FALSE;
      /* Convert user 0-100 rating to percentage scaling */
      cinfo->q_scale_factor[tblno] = jpeg_quality_scaling(val);
      while (*arg && *arg++ != ',') /* advance to next segment of arg string */
	;
    } else {
      /* reached end of parameter, set remaining factors to last value */
      cinfo->q_scale_factor[tblno] = jpeg_quality_scaling(val);
    }
  }
  jpeg_default_qtables(cinfo, force_baseline);
  return TRUE;
}

GLOBAL(boolean)
set_quant_slots (j_compress_ptr cinfo, char *arg)
/* Process a quantization-table-selectors parameter string, of the form
 *     N[,N,...]
 * If there are more components than parameters, the last value is replicated.
 */
{
  int val = 0;			/* default table # */
  int ci;
  char ch;

  for (ci = 0; ci < MAX_COMPONENTS; ci++) {
    if (*arg) {
      ch = ',';			/* if not set by sscanf, will be ',' */
      if (sscanf(arg, "%d%c", &val, &ch) < 1)
	return FALSE;
      if (ch != ',')		/* syntax check */
	return FALSE;
      if (val < 0 || val >= NUM_QUANT_TBLS) {
	fprintf(stderr, "JPEG quantization tables are numbered 0..%d\n",
		NUM_QUANT_TBLS-1);
	return FALSE;
      }
      cinfo->comp_info[ci].quant_tbl_no = val;
      while (*arg && *arg++ != ',') /* advance to next segment of arg string */
	;
    } else {
      /* reached end of parameter, set remaining components to last table */
      cinfo->comp_info[ci].quant_tbl_no = val;
    }
  }
  return TRUE;
}

GLOBAL(boolean)
set_sample_factors (j_compress_ptr cinfo, char *arg)
/* Process a sample-factors parameter string, of the form
 *     HxV[,HxV,...]
 * If there are more components than parameters, "1x1" is assumed for the rest.
 */
{
  int ci, val1, val2;
  char ch1, ch2;

  for (ci = 0; ci < MAX_COMPONENTS; ci++) {
    if (*arg) {
      ch2 = ',';		/* if not set by sscanf, will be ',' */
      if (sscanf(arg, "%d%c%d%c", &val1, &ch1, &val2, &ch2) < 3)
	return FALSE;
      if ((ch1 != 'x' && ch1 != 'X') || ch2 != ',') /* syntax check */
	return FALSE;
      if (val1 <= 0 || val1 > 4 || val2 <= 0 || val2 > 4) {
	fprintf(stderr, "JPEG sampling factors must be 1..4\n");
	return FALSE;
      }
      cinfo->comp_info[ci].h_samp_factor = val1;
      cinfo->comp_info[ci].v_samp_factor = val2;
      while (*arg && *arg++ != ',') /* advance to next segment of arg string */
	;
    } else {
      /* reached end of parameter, set remaining components to 1x1 sampling */
      cinfo->comp_info[ci].h_samp_factor = 1;
      cinfo->comp_info[ci].v_samp_factor = 1;
    }
  }
  return TRUE;
}


text:
package mvalid

import (
	"fmt"
)

type RequiredValidator struct {
	Value interface{}
	Field string
	Validator
}

func NewRequiredValidator(v interface{}, field string) *RequiredValidator {
	return &RequiredValidator{Value: v, Field: field}
}

// Validate implement Validator.
func (vd *RequiredValidator) Validate() (bool, string) {
	// valid a value.
	if vd.Field == "" {
		v := fmt.Sprintf("%v", vd.Value)
		if v == "" {
			err := ""
			return false, err
		}
	}
	// field not null.

	return true, ""
}


text: Create lessons from articles


text:
include ../Makefile.in
#LDFLAGS += -lz -liconv
#Path for SunOS
ifeq ($(findstring SunOS, $(UNIXNAME)), SunOS)
	LDFLAGS += -lz -liconv
else
	LDFLAGS += -lz
endif
ifeq ($(findstring FreeBSD, $(UNIXNAME)), FreeBSD)
	EXTLIBS += -L/usr/local/lib -liconv
endif
ifeq ($(findstring Darwin, $(UNIXNAME)), Darwin)
	EXTLIBS += -L/usr/lib -liconv
endif
PROG = http_request_manager


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
*/

"use strict";

/** @template T @typedef {function(): T} FunctionReturning */

/**
 * @template T
 * @param {FunctionReturning<T>} fn memorized function
 * @returns {FunctionReturning<T>} new function
 */
const memorize = fn => {
	let memorized = false;
	/** @type {T} */
	let result = undefined;
	return () => {
		if (memorized) {
			return result;
		} else {
			result = fn();
			memorized = true;
			// Allow to clean up memory for fn
			// and all dependent resources
			fn = undefined;
			return result;
		}
	};
};

module.exports = memorize;


text:
package lv.addresses.indexer

import org.scalatest.FunSuite

import scala.collection.mutable.ArrayBuffer
import spray.json._

import scala.io.Source

import lv.addresses.index.Index._

object IndexerTest {
  class TestAddressFinder(val addressFileName: String, val excludeList: Set[String],
                          val houseCoordFile: String, val dbConfig: Option[DbConfig]) extends AddressFinder

  val finder = new TestAddressFinder(null, Set.empty, null, None)

  object IndexJsonProtocol extends DefaultJsonProtocol {
    implicit def abFormat[T: JsonFormat] = new RootJsonFormat[ArrayBuffer[T]] {
      override def write(obj: ArrayBuffer[T]): JsValue = obj.toVector.toJson
      override def read(json: JsValue): ArrayBuffer[T] = ArrayBuffer.from(json.convertTo[Vector[T]])
    }
    implicit object NodeFormat extends RootJsonFormat[MutableIndexNode] {
      implicit val refFormat = jsonFormat2(Refs)
      override def write(obj: MutableIndexNode): JsValue = {
        import obj._

        JsObject(Map(
          "word" -> Option(word).map(JsString(_)).getOrElse(JsNull),
          "refs" -> Option(refs).map(_.toJson).getOrElse(JsNull),
          "children" -> NodeBaseFormat.write(obj)
        ))
      }

      override def read(json: JsValue): MutableIndexNode = (json: @unchecked) match {
        case JsObject(fields) =>
          new MutableIndexNode(
            fields("word").convertTo[String],
            fields("refs").convertTo[Refs],
            fields("children").convertTo[ArrayBuffer[MutableIndexNode]]
          )
      }
    }
    implicit object NodeBaseFormat extends RootJsonFormat[MutableIndexBase] {
      override def write(obj: MutableIndexBase): JsValue = {
        Option(obj.children).map(_.toJson).getOrElse(JsNull)
      }

      override def read(json: JsValue): MutableIndexBase = (json: @unchecked) match {
        case nodes => new MutableIndexBase(nodes.convertTo[ArrayBuffer[MutableIndexNode]])
      }
    }
    implicit object IndexFormat extends RootJsonFormat[MutableIndex] {
      override def write(obj: MutableIndex): JsValue = {
        import obj._
        JsObject(Map(
          "index" -> Option(children).map(_.toJson).getOrElse(JsNull),
          "repeated_words_index" ->
            Option(repeatedWordChildren).map(_.toJson).getOrElse(JsNull)
        ))
      }

      override def read(json: JsValue): MutableIndex = (json: @unchecked) match {
        case JsObject(fields) =>
          def nodes[T: JsonFormat](name: String) = fields(name).convertTo[ArrayBuffer[T]]
          new MutableIndex(nodes[MutableIndexNode]("index"),
            nodes[MutableIndexBase]("repeated_words_index"))
      }
    }
  }
}

class IndexerTest extends FunSuite {

  import IndexerTest._

  test("word stat for indexer") {
    assertResult(Map("vid" -> 1, "n" -> 1, "vidussko" -> 1, "pa" -> 1, "vall" -> 3, "vi" -> 1,
      "vecumniek" -> 1, "vecu" -> 1, "vecumn" -> 1, "viduss" -> 1, "no" -> 1, "vec" -> 1,
      "vecumnie" -> 1, "nov" -> 1, "vidusskola" -> 1,
      "vidu" -> 1, "va" -> 3, "vecumni" -> 1, "vidus" -> 1,
      "v" -> 5, "pag" -> 1, "valle" -> 3,
      "vecum" -> 1, "ve" -> 1, "vidusskol" -> 1, "vidussk" -> 1, "p" -> 1, "val" -> 3,
      "vecumnieku" -> 1, "valles" -> 2)) {
        wordStatForIndex("Valles vidusskola, Valle, Valles pag., Vecumnieku nov.")
    }
  }

  test("word stat for search") {
    assertResult(Array(("Valles", 1), ("vidusskola", 1), ("Valle", 3),
      ("Valles" ,2), ("pag", 1), ("Vecumnieku", 1), ("nov", 1)))(
      wordStatForSearch(ArrayBuffer("Valles", "vidusskola", "Valle", "Valles", "pag", "Vecumnieku", "nov")))
  }

  test("index") {
    val node = List(
      "aknas",
      "akls",
      "ak ak",
      "aknīste",
      "ak aknīste",
      "aka aka",
      "aka akācijas",
      "21 215"
    )
    .zipWithIndex
    .foldLeft(new MutableIndex(null, null)) { (node, addrWithIdx) =>
      val (addr, idx) = addrWithIdx
      val words = extractWords(addr)
      //check that duplicate word do not result in duplicate address code reference
      (if (words.exists(_ == "ak")) words ++ List("ak") else words)
        .foreach { w =>
          val exactStr = if (w.contains("*")) w.substring(w.indexOf('*') + 1) else w
          node.updateChildren(w, idx, normalize(addr).contains(exactStr))
        }
      node
    }

    val expectedResult = Source
      .fromInputStream(this.getClass.getResourceAsStream("/index_node.json"), "UTF-8")
      .mkString
      .parseJson

    import IndexJsonProtocol._
    //println(node.toJson.prettyPrint)
    assertResult(expectedResult)(node.toJson)

    assertResult(IndexStats(NodeStats(20,39),ArrayBuffer(NodeStats(5,12))))(node.statistics)
    assertResult(ArrayBuffer())(node.checkInvalidIndices)
    assertResult(ArrayBuffer())(node.checkInvalidWords)
  }

  test("index search") {
    val node = new MutableIndex(null, null)
    val idx_val = List(
      "aknas",
      "akls",
      "ak ak",
      "aknīste",
      "ak aknīste",
      "aka aka",
      "aka akācijas",
      "21 215",
      "ventspils",
      "vencīši",
      "venskalni",
      "ventilācijas",
      "kazdanga",
      "ķirši",
      "ķiršu",
      "ķirša",
      "rīga",
      "brīvības",
      "brīvības rīga",
      "brīvības iela rīga",
      "brīvības valka",
      "brīvības iela valka",
      "brīvības iela 2 valka",
      "valles vidusskola, valle"
    )
    .zipWithIndex
    .map { case (addr, idx) =>
      val words = extractWords(addr)
      words.foreach { w =>
        val exactStr = if (w.contains("*")) w.substring(w.indexOf('*') + 1) else w
        node.updateChildren(w, idx, normalize(addr).contains(exactStr))
      }
      (idx, addr)
    }.toMap

    def word(str: String) = normalize(str).head
    def search_exact(str: String) = res(node(str))
    def search_fuzzy(str: String, ed: Int) =
      res_fuzzy(node(str, ed, finder.maxEditDistance))
    def res(refs: Refs) = (refs.exact ++ refs.approx).map(idx_val(_)).toList
    def res_fuzzy(res: ArrayBuffer[FuzzyResult]) = {
      res.map { case FuzzyResult(_, r, ed, sd) => (r.map(idx_val(_)).toList, ed, sd) }.toList
    }

    def search(str: String) =
      searchCodes(normalize(str), node, finder.maxEditDistance)(1024)
        .map(r => (r.refs.map(idx_val).toList, r.editDistance)).toList

    //exact search, edit distance 0
    assertResult(List("ak ak", "ak aknīste", "aknas", "akls", "aknīste", "aka aka", "aka akācijas"))(search_exact("ak"))
    assertResult(List("ak ak", "ak aknīste", "aka aka", "aka akācijas"))(search_exact("2*ak"))
    assertResult(List("aknas"))(search_exact("akna"))
    assertResult(Nil)(search_exact("aknass"))
    assertResult(Nil)(search_exact("ziz"))

    //fuzzy search, edit distance 1
    assertResult(List((List("aka aka", "aka akācijas"), 0, 0),
      (List("ak ak", "ak aknīste"), 1, 0)))(search_fuzzy(word("aka"), 1))
    assertResult(List((List("aka akācijas"), 0, 0)))(search_fuzzy(word("akācijas"), 1))
    assertResult(List((List("aka akācijas"), 1, 0)))(search_fuzzy(word("akcijas"), 1))
    assertResult(List((List("aka akācijas"), 1, 0)))(search_fuzzy(word("akucijas"), 1))
    assertResult(List((List("aka akācijas"), 1, 0)))(search_fuzzy(word("akaicijas"), 1))
    assertResult(List((List("aka akācijas"), 1, 0)))(search_fuzzy(word("kakācijas"), 1))
    assertResult(List((List("aka akācijas"), 1, 0)))(search_fuzzy(word("ukācijas"), 1))
    assertResult(List((List("aka akācijas"), 1, 0)))(search_fuzzy(word("akācijs"), 1))
    assertResult(List((List("aka akācijas"), 1, 0)))(search_fuzzy(word("akācijaz"), 1))
    assertResult(List((List("aka akācijas"), 1, 0)))(search_fuzzy(word("akācijass"), 1))
    assertResult(List((List("akls"),1, 0), (List("aknas"),1, 0)))(search_fuzzy(word("aklas"), 1))
    assertResult(List((List("akls"), 1, 0)))(search_fuzzy(word("kakls"), 1))
    assertResult(List((List("ventspils"), 0, 0)))(search_fuzzy(word("ventspils"), 1))
    assertResult(List((List("ventspils"), 1, 0)))(search_fuzzy(word("venspils"), 1))
    assertResult(Nil)(search_fuzzy(word("vencpils"), 1))
    assertResult(Nil)(search_fuzzy(word("kaklas"), 1))

    assertResult(List((List("ventspils"), 1, 0)))(search_fuzzy(word("venspils"), 1))
    assertResult(List((List("ventspils"), 1, 0)))(search_fuzzy(word("ventpils"), 1))
    assertResult(Nil)(search_fuzzy(word("venpils"), 1))
    assertResult(List((List("kazdanga"), 1, 0)))(search_fuzzy(word("bazdanga"), 1))
    assertResult(List((List("ventspils"), 1, 0)))(search_fuzzy(word("bentspils"), 1))
    assertResult(List((List("kazdanga"), 1, 0)))(search_fuzzy(word("vazdanga"), 1))
    assertResult(List((List("ventspils"), 1, 0)))(search_fuzzy(word("kentspils"), 1))
    assertResult(List((List("ķirša"), 0, 0), (List("ķiršu"), 1, 0), (List("ķirši"), 1, 0)))(search_fuzzy(word("kirsa"), 1))
    assertResult(List((List("valles vidusskola, valle"), 1, 0)))(search_fuzzy(word("2*vallez"), 1))

    //fuzzy search, edit distance 2
    assertResult(List((List("akls"), 2, 0)))(search_fuzzy(word("akliss"), 2))
    assertResult(List((List("akls"), 2, 0), (List("aknas"), 2, 0)))(search_fuzzy(word("kaklas"), 2))
    assertResult(List((List("akls"), 2, 0)))(search_fuzzy(word("kikls"), 2))
    assertResult(List((List("akls"), 2, 0)))(search_fuzzy(word("akliss"), 2))
    assertResult(Nil)(search_fuzzy(word("kakliss"), 2))
    assertResult(List((List("ventspils"), 1, 0)))(search_fuzzy(word("ventpils"), 2))
    assertResult(List((List("ventspils"), 1, 0)))(search_fuzzy(word("venspils"), 2))
    assertResult(List((List("ventspils"), 2, 0)))(search_fuzzy(word("venpils"), 2))
    assertResult(List((List("ventspils"), 2, 0)))(search_fuzzy(word("vencpils"), 2))
    assertResult(List((List("kazdanga"), 2, 0)))(search_fuzzy(word("sbazdanga"), 2))
    assertResult(List((List("kazdanga"), 2, 0)))(search_fuzzy(word("kazdangazi"), 2))

    //fuzzy search with search string split
    //spaces are included in edit distance calculation
    assertResult(List((List("brīvības rīga", "brīvības iela rīga"), 1, 1)))(search_fuzzy(word("rigabrivibas"), 0))
    assertResult(List((List("brīvības rīga", "brīvības iela rīga"), 4, 1)))(search_fuzzy(word("riiabrvbas"), 2))
    assertResult(List((List("brīvības rīga", "brīvības iela rīga"), 2, 1)))(search_fuzzy(word("riiabriv"), 2))
    assertResult(List((List("brīvības rīga", "brīvības iela rīga"), 2, 1)))(search_fuzzy(word("riiabrivi"), 2))
    assertResult(List((List("brīvības iela rīga"), 2, 1)))(search_fuzzy(word("riiaie"), 2))
    assertResult(List((List("brīvības iela rīga"), 3, 2)))(search_fuzzy(word("riiabrivibasiela"), 2))
    assertResult(List((List("brīvības iela rīga", "brīvības iela valka", "brīvības iela 2 valka"), 3, 1)))(search_fuzzy(word("brvbasiela"), 2))
    assertResult(List((List("brīvības iela rīga"), 5, 2)))(search_fuzzy(word("riiabrvbasiela"), 2))
    assertResult(List((List("brīvības iela rīga"), 5, 2)))(search_fuzzy(word("riiaielabrvbas"), 2))
    assertResult(List((List("brīvības iela valka", "brīvības iela 2 valka"), 5, 2)))(search_fuzzy(word("vlkabrvbasiela"), 2))
    assertResult(List((List("brīvības iela 2 valka"), 5, 3),(List("brīvības iela valka", "brīvības iela 2 valka"), 5, 2)))(search_fuzzy(word("brvbasiela2valka"), 2))

    //fuzzy search merge words
    assertResult(List((List("aknas"), 1)))(search("ak nas"))
    assertResult(List((List("aknas"), 4)))(search("a k n a s"))
    //repeated word search
    assertResult(List((List("valles vidusskola, valle"), 1)))(search("vallez vallez"))
  }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\admin\models\SitesettingsSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'settings_key') ?>

    <?= $form->field($model, 'value') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
package io.github.millij.bean;

public enum Gender {

    MALE,

    FEMALE;

}


text:
module Telesignature
  module MockService
    class Railtie < ::Rails::Railtie
      initializer 'telesignature_railtie.configure_rails_initialization' do
        require 'telesignature/mock_service/spin_up'
      end
    end
  end
end


text:
![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png) 0

To use the The Couch Hunter skill, try saying...

* *Alexa, ask The Couch Hunter to tell me about the rathian*

* *Alexa, ask The Couch Hunter what the rathalos is weak to*

* *Alexa, ask The Couch Hunter about the nibelsnarf*

Just ask The Couch Hunter to tell you about any monster!

***

### Skill Details

* **Invocation Name:** the couch hunter
* **Category:** null
* **ID:** amzn1.echo-sdk-ams.app.6572f404-e6bd-412d-b087-433e65e91339
* **ASIN:** B01HFH70LM
* **Author:** aaron maus
* **Release Date:** June 27, 2016 @ 06:45:35
* **In-App Purchasing:** No


text:
package com.atlassian.maven.plugins.jgitflow.extension;

import com.atlassian.jgitflow.core.extension.impl.EmptyFeatureFinishExtension;
import com.atlassian.maven.plugins.jgitflow.extension.command.MavenBuildCommand;
import com.atlassian.maven.plugins.jgitflow.extension.command.UpdateFeaturePomsWithFinalVersionsCommand;

import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;

@Component(role = FeatureFinishPluginExtension.class)
public class FeatureFinishPluginExtension extends EmptyFeatureFinishExtension implements InitializingExtension
{
    @Requirement
    private UpdateFeaturePomsWithFinalVersionsCommand updateFeaturePomsWithFinalVersionsCommand;

    @Requirement
    private MavenBuildCommand mavenBuildCommand;

    @Override
    public void init()
    {
        addAfterTopicCheckoutCommands(
                updateFeaturePomsWithFinalVersionsCommand,
                mavenBuildCommand
        );
    }
}


text:
var should = require("should");
var sinon = require("sinon");
var when = require("when");
var clone = require("clone");
var NR_TEST_UTILS = require("nr-test-utils");
var flowUtil = NR_TEST_UTILS.require("@node-red/runtime/lib/nodes/flows/util");
var typeRegistry = NR_TEST_UTILS.require("@node-red/registry");
var redUtil = NR_TEST_UTILS.require("@node-red/util").util;

describe('flows/util', function() {
    var getType;

    before(function() {
        getType = sinon.stub(typeRegistry,"get",function(type) {
            return type!=='missing';
        });
    });
    after(function() {
        getType.restore();
    });

    describe('#mapEnvVarProperties',function() {
        before(function() {
            process.env.foo1 = "bar1";
            process.env.foo2 = "bar2";
            process.env.foo3 = "bar3";
        })
        after(function() {
            delete process.env.foo1;
            delete process.env.foo2;
            delete process.env.foo3;
        })
        it('handles ENV substitutions in an object - $()', function() {
            var foo = {a:"$(foo1)",b:"$(foo2)",c:{d:"$(foo3)"}};
            for (var p in foo) {
                if (foo.hasOwnProperty(p)) {
                    flowUtil.mapEnvVarProperties(foo,p,{getSetting: p => process.env[p]});
                }
            }
            foo.should.eql({ a: 'bar1', b: 'bar2', c: { d: 'bar3' } } );
        });
        it('handles ENV substitutions in an object - ${}', function() {
            var foo = {a:"${foo1}",b:"${foo2}",c:{d:"${foo3}"}};
            for (var p in foo) {
                if (foo.hasOwnProperty(p)) {
                    flowUtil.mapEnvVarProperties(foo,p,{getSetting: p => process.env[p]});
                }
            }
            foo.should.eql({ a: 'bar1', b: 'bar2', c: { d: 'bar3' } } );
        });

        it('gets ENV from parent flow', function() {
            var foo = {a:"$(unknown)",b:"$(foo2)",c:{d:"$(foo3)"}};
            for (var p in foo) {
                if (foo.hasOwnProperty(p)) {
                    flowUtil.mapEnvVarProperties(foo,p,{
                        getSetting: name => name[0]==='f'?name.toUpperCase():undefined
                    });
                }
            }
            foo.should.eql({ a: '$(unknown)', b: 'FOO2', c: { d: 'FOO3' } } );
        });
    });
    describe('#getEnvVar',function() {
        before(function() {
            process.env.foo1 = "bar1";
        })
        after(function() {
            delete process.env.foo1;
        })
        it('returns a known env var', function() {
            flowUtil.init({settings:{}});
            flowUtil.getEnvVar("foo1").should.equal("bar1")
        })
        it('returns undefined for an unknown env var', function() {
            flowUtil.init({settings:{}});
            (flowUtil.getEnvVar("foo2") === undefined).should.be.true()
        })
        it('returns undefined for an excluded env var', function() {
            flowUtil.init({settings:{envVarExcludes:['foo1']}});
            (flowUtil.getEnvVar("foo1") === undefined).should.be.true()
        })

    });

    describe('#diffNodes',function() {
        it('handles a null old node', function() {
            flowUtil.diffNodes(null,{}).should.be.true();
        });
        it('ignores x/y changes', function() {
            flowUtil.diffNodes({x:10,y:10},{x:20,y:10}).should.be.false();
            flowUtil.diffNodes({x:10,y:10},{x:10,y:20}).should.be.false();
        });
        it('ignores wiring changes', function() {
            flowUtil.diffNodes({wires:[]},{wires:[1,2,3]}).should.be.false();
        });
        it('spots existing property change - string', function() {
            flowUtil.diffNodes({a:"foo"},{a:"bar"}).should.be.true();
        });
        it('spots existing property change - number', function() {
            flowUtil.diffNodes({a:0},{a:1}).should.be.true();
        });
        it('spots existing property change - boolean', function() {
            flowUtil.diffNodes({a:true},{a:false}).should.be.true();
        });
        it('spots existing property change - truthy', function() {
            flowUtil.diffNodes({a:true},{a:1}).should.be.true();
        });
        it('spots existing property change - falsey', function() {
            flowUtil.diffNodes({a:false},{a:0}).should.be.true();
        });
        it('spots existing property change - array', function() {
            flowUtil.diffNodes({a:[0,1,2]},{a:[0,2,3]}).should.be.true();
        });
        it('spots existing property change - object', function() {
            flowUtil.diffNodes({a:{a:[0,1,2]}},{a:{a:[0,2,3]}}).should.be.true();
            flowUtil.diffNodes({a:{a:[0,1,2]}},{a:{b:[0,1,2]}}).should.be.true();
        });
        it('spots added property', function() {
            flowUtil.diffNodes({a:"foo"},{a:"foo",b:"bar"}).should.be.true();
        });
        it('spots removed property', function() {
            flowUtil.diffNodes({a:"foo",b:"bar"},{a:"foo"}).should.be.true();
        });

    });

    describe('#parseConfig',function() {

        it('parses a single-tab flow', function() {
            var originalConfig = [
                {id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
                {id:"t1",type:"tab"}
            ];
            var parsedConfig = flowUtil.parseConfig(originalConfig);
            var expectedConfig = {"allNodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","wires":[]},"t1":{"id":"t1","type":"tab"}},"subflows":{},"configs":{},"flows":{"t1":{"id":"t1","type":"tab","subflows":{},"configs":{},"nodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","wires":[]}}}},"missingTypes":[]};
            parsedConfig.should.eql(expectedConfig);
        });

        it('parses a single-tab flow with global config node', function() {
            var originalConfig = [
                {id:"t1-1",x:10,y:10,z:"t1",type:"test",foo:"cn", wires:[]},
                {id:"cn",type:"test"},
                {id:"t1",type:"tab"}
            ];
            var parsedConfig = flowUtil.parseConfig(originalConfig);
            var expectedConfig = {"allNodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","foo":"cn","wires":[]},"cn":{"id":"cn","type":"test"},"t1":{"id":"t1","type":"tab"}},"subflows":{},"configs":{"cn":{"id":"cn","type":"test","_users":["t1-1"]}},"flows":{"t1":{"id":"t1","type":"tab","subflows":{},"configs":{},"nodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","foo":"cn","wires":[]}}}},"missingTypes":[]};
            parsedConfig.should.eql(expectedConfig);
        });

        it('parses a multi-tab flow', function() {
            var originalConfig = [
                {id:"t1",type:"tab"},
                {id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
                {id:"t2",type:"tab"},
                {id:"t2-1",x:10,y:10,z:"t2",type:"test",wires:[]}
            ];
            var parsedConfig = flowUtil.parseConfig(originalConfig);
            var expectedConfig = {"allNodes":{"t1":{"id":"t1","type":"tab"},"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","wires":[]},"t2":{"id":"t2","type":"tab"},"t2-1":{"id":"t2-1","x":10,"y":10,"z":"t2","type":"test","wires":[]}},"subflows":{},"configs":{},"flows":{"t1":{"id":"t1","type":"tab","subflows":{},"configs":{},"nodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","wires":[]}}},"t2":{"id":"t2","type":"tab","subflows":{},"configs":{},"nodes":{"t2-1":{"id":"t2-1","x":10,"y":10,"z":"t2","type":"test","wires":[]}}}},"missingTypes":[]};
            parsedConfig.should.eql(expectedConfig);
        });

        it('parses a subflow flow', function() {
            var originalConfig = [
                {id:"t1",type:"tab"},
                {id:"t1-1",x:10,y:10,z:"t1",type:"subflow:sf1",wires:[]},
                {id:"sf1",type:"subflow"},
                {id:"sf1-1",x:10,y:10,z:"sf1",type:"test",wires:[]}
            ];
            var parsedConfig = flowUtil.parseConfig(originalConfig);
            var expectedConfig = {"allNodes":{"t1":{"id":"t1","type":"tab"},"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"subflow:sf1","wires":[]},"sf1":{"id":"sf1","type":"subflow"},"sf1-1":{"id":"sf1-1","x":10,"y":10,"z":"sf1","type":"test","wires":[]}},"subflows":{"sf1":{"id":"sf1","type":"subflow","configs":{},"nodes":{"sf1-1":{"id":"sf1-1","x":10,"y":10,"z":"sf1","type":"test","wires":[]}},"instances":[{"id":"t1-1","x":10,"y":10,"z":"t1","type":"subflow:sf1","wires":[],"subflow":"sf1"}]}},"configs":{},"flows":{"t1":{"id":"t1","type":"tab","subflows":{},"configs":{},"nodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"subflow:sf1","wires":[],"subflow":"sf1"}}}},"missingTypes":[]};
            parsedConfig.should.eql(expectedConfig);
        });

        it('parses a flow with a missing type', function() {
            var originalConfig = [
                {id:"t1",type:"tab"},
                {id:"t1-1",x:10,y:10,z:"t1",type:"sf1",wires:[]},
                {id:"t1-2",x:10,y:10,z:"t1",type:"missing",wires:[]},
            ];
            var parsedConfig = flowUtil.parseConfig(originalConfig);
            parsedConfig.missingTypes.should.eql(['missing']);
            var expectedConfig = {"allNodes":{"t1":{"id":"t1","type":"tab"},"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"sf1","wires":[]},"t1-2":{"id":"t1-2","x":10,"y":10,"z":"t1","type":"missing","wires":[]}},"subflows":{},"configs":{},"flows":{"t1":{"id":"t1","type":"tab","subflows":{},"configs":{},"nodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"sf1","wires":[]},'t1-2': { id: 't1-2', x: 10, y: 10, z: 't1', type: 'missing', wires: [] }}}},"missingTypes":["missing"]};
            redUtil.compareObjects(parsedConfig,expectedConfig).should.be.true();
        });

        it('parses a flow with a missing flow', function() {
            var originalConfig = [
                {id:"t1-1",x:10,y:10,z:"t1",type:"test",foo:"cn", wires:[]},
                {id:"cn",type:"test"},
            ];
            var parsedConfig = flowUtil.parseConfig(originalConfig);
            var expectedConfig = {"allNodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","foo":"cn","wires":[]},"cn":{"id":"cn","type":"test"}},"subflows":{},"configs":{"cn":{"id":"cn","type":"test","_users":["t1-1"]}},"flows":{"t1":{"id":"t1","type":"tab","subflows":{},"configs":{},"nodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","foo":"cn","wires":[]}}}},"missingTypes":[]};
            parsedConfig.should.eql(expectedConfig);
        });

    });

    describe('#diffConfigs', function() {

        it('handles an identical configuration', function() {
            var config = [{id:"123",type:"test",foo:"a",wires:[]}];

            var originalConfig = flowUtil.parseConfig(clone(config));
            var changedConfig = flowUtil.parseConfig(clone(config));

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);

            diffResult.added.should.have.length(0);
            diffResult.changed.should.have.length(0);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.should.have.length(0);
        });

        it('identifies nodes with changed properties, including downstream linked', function() {
            var config = [{id:"1",type:"test",foo:"a",wires:[]},{id:"2",type:"test",bar:"b",wires:[[1]]},{id:"3",type:"test",foo:"a",wires:[]}];
            var newConfig = clone(config);
            newConfig[0].foo = "b";

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.should.eql(["1"]);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.should.eql(["2"]);

        });
        it('identifies nodes with changed properties, including upstream linked', function() {
            var config = [{id:"1",type:"test",foo:"a",wires:[]},{id:"2",type:"test",bar:"b",wires:[["1"]]},{id:"3",type:"test",foo:"a",wires:[]}];
            var newConfig = clone(config);
            newConfig[1].bar = "c";

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.should.eql(["2"]);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.should.eql(["1"]);
        });

        it('identifies nodes with changed credentials, including downstream linked', function() {
            var config = [{id:"1",type:"test",wires:[]},{id:"2",type:"test",bar:"b",wires:[["1"]]},{id:"3",type:"test",foo:"a",wires:[]}];
            var newConfig = clone(config);
            newConfig[0].credentials = {};

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.should.eql(["1"]);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.should.eql(["2"]);
        });

        it('identifies nodes with changed wiring', function() {
            var config = [{id:"1",type:"test",foo:"a",wires:[]},{id:"2",type:"test",bar:"b",wires:[["1"]]},{id:"3",type:"test",foo:"a",wires:[]}];
            var newConfig = clone(config);
            newConfig[1].wires[0][0] = "3";

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.should.have.length(0);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.eql(["2"]);
            diffResult.linked.sort().should.eql(["1","3"]);
        });

        it('identifies nodes with changed wiring - second connection added', function() {
            var config = [{id:"1",type:"test",foo:"a",wires:[]},{id:"2",type:"test",bar:"b",wires:[["1"]]},{id:"3",type:"test",foo:"a",wires:[]}];
            var newConfig = clone(config);
            newConfig[1].wires[0].push("1");

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.should.have.length(0);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.eql(["2"]);
            diffResult.linked.sort().should.eql(["1"]);
        });

        it('identifies nodes with changed wiring - node connected', function() {
            var config = [{id:"1",type:"test",foo:"a",wires:[["2"]]},{id:"2",type:"test",bar:"b",wires:[[]]},{id:"3",type:"test",foo:"a",wires:[]}];
            var newConfig = clone(config);
            newConfig[1].wires.push("3");

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.should.have.length(0);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.eql(["2"]);
            diffResult.linked.sort().should.eql(["1","3"]);
        });

        it('identifies new nodes', function() {
            var config = [{id:"1",type:"test",foo:"a",wires:[]},{id:"3",type:"test",foo:"a",wires:[]}];
            var newConfig = clone(config);
            newConfig.push({id:"2",type:"test",bar:"b",wires:[["1"]]});

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.eql(["2"]);
            diffResult.changed.should.have.length(0);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["1"]);
        });

        it('identifies deleted nodes', function() {
            var config = [{id:"1",type:"test",foo:"a",wires:[["2"]]},{id:"2",type:"test",bar:"b",wires:[["3"]]},{id:"3",type:"test",foo:"a",wires:[]}];
            var newConfig = clone(config);
            newConfig.splice(1,1);
            newConfig[0].wires = [];

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.should.have.length(0);
            diffResult.removed.should.eql(["2"]);
            diffResult.rewired.should.eql(["1"]);
            diffResult.linked.sort().should.eql(["3"]);
        });

        it('identifies config nodes changes, node->config', function() {
            var config = [
                {id:"1",type:"test",foo:"configNode",wires:[["2"]]},
                {id:"2",type:"test",bar:"b",wires:[["3"]]},
                {id:"3",type:"test",foo:"a",wires:[]},
                {id:"configNode",type:"testConfig"}
            ];
            var newConfig = clone(config);
            newConfig[3].foo = "bar";

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(["1","configNode"]);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["2","3"]);
        });

        it('identifies config nodes changes, node->config->config', function() {
            var config = [
                {id:"1",type:"test",foo:"configNode1",wires:[["2"]]},
                {id:"2",type:"test",bar:"b",wires:[["3"]]},
                {id:"3",type:"test",foo:"a",wires:[]},
                {id:"configNode1",foo:"configNode2",type:"testConfig"},
                {id:"configNode2",type:"testConfig"}
            ];
            var newConfig = clone(config);
            newConfig[4].foo = "bar";

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(["1","configNode1","configNode2"]);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["2","3"]);
        });

        it('marks a parent subflow as changed for an internal property change', function() {
            var config = [
                {id:"1",type:"test",wires:[["2"]]},
                {id:"2",type:"subflow:sf1",wires:[["3"]]},
                {id:"3",type:"test",wires:[]},
                {id:"sf1",type:"subflow"},
                {id:"sf1-1",z:"sf1",type:"test",foo:"a",wires:[]},
                {id:"4",type:"subflow:sf1",wires:[]}
            ];

            var newConfig = clone(config);
            newConfig[4].foo = "b";

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(['2', '4', 'sf1']);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["1","3"]);

        });

        it('marks a parent subflow as changed for an internal wiring change', function() {
            var config = [
                {id:"1",type:"test",wires:[["2"]]},
                {id:"2",type:"subflow:sf1",wires:[["3"]]},
                {id:"3",type:"test",wires:[]},
                {id:"sf1",type:"subflow"},
                {id:"sf1-1",z:"sf1",type:"test",wires:[]},
                {id:"sf1-2",z:"sf1",type:"test",wires:[]}
            ];

            var newConfig = clone(config);
            newConfig[4].wires = [["sf1-2"]];

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(['2', 'sf1']);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["1","3"]);
        });

        it('marks a parent subflow as changed for an internal node add', function() {
            var config = [
                {id:"1",type:"test",wires:[["2"]]},
                {id:"2",type:"subflow:sf1",wires:[["3"]]},
                {id:"3",type:"test",wires:[]},
                {id:"sf1",type:"subflow"},
                {id:"sf1-1",z:"sf1",type:"test",wires:[]},
                {id:"sf1-2",z:"sf1",type:"test",wires:[]}
            ];

            var newConfig = clone(config);
            newConfig.push({id:"sf1-3",z:"sf1",type:"test",wires:[]});

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(['2', 'sf1']);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["1","3"]);

        });

        it('marks a parent subflow as changed for an internal node delete', function() {
            var config = [
                {id:"1",type:"test",wires:[["2"]]},
                {id:"2",type:"subflow:sf1",wires:[["3"]]},
                {id:"3",type:"test",wires:[]},
                {id:"sf1",type:"subflow"},
                {id:"sf1-1",z:"sf1",type:"test",wires:[]},
                {id:"sf1-2",z:"sf1",type:"test",wires:[]}
            ];

            var newConfig = clone(config);
            newConfig.splice(5,1);

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(['2', 'sf1']);
            diffResult.removed.should.have.length(1);
            diffResult.removed.sort().should.eql(['sf1-2']);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["1","3"]);

        });

        it('marks a parent subflow as changed for an internal subflow wiring change - input removed', function() {
            var config = [
                {id:"1",type:"test",wires:[["2"]]},
                {id:"2",type:"subflow:sf1",wires:[["3"]]},
                {id:"3",type:"test",wires:[]},
                {id:"sf1",type:"subflow","in": [{"wires": [{"id": "sf1-1"}]}],"out": [{"wires": [{"id": "sf1-2","port": 0}]}]},
                {id:"sf1-1",z:"sf1",type:"test",wires:[]},
                {id:"sf1-2",z:"sf1",type:"test",wires:[]}
            ];

            var newConfig = clone(config);
            newConfig[3].in[0].wires = [];

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(['2', 'sf1']);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["1","3"]);
        });

        it('marks a parent subflow as changed for an internal subflow wiring change - input added', function() {
            var config = [
                {id:"1",type:"test",wires:[["2"]]},
                {id:"2",type:"subflow:sf1",wires:[["3"]]},
                {id:"3",type:"test",wires:[]},
                {id:"sf1",type:"subflow","in": [{"wires": [{"id": "sf1-1"}]}],"out": [{"wires": [{"id": "sf1-2","port": 0}]}]},
                {id:"sf1-1",z:"sf1",type:"test",wires:[]},
                {id:"sf1-2",z:"sf1",type:"test",wires:[]}
            ];

            var newConfig = clone(config);
            newConfig[3].in[0].wires.push({"id":"sf1-2"});

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(['2', 'sf1']);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["1","3"]);
        });

        it('marks a parent subflow as changed for an internal subflow wiring change - output added', function() {
            var config = [
                {id:"1",type:"test",wires:[["2"]]},
                {id:"2",type:"subflow:sf1",wires:[["3"]]},
                {id:"3",type:"test",wires:[]},
                {id:"sf1",type:"subflow","in": [{"wires": [{"id": "sf1-1"}]}],"out": [{"wires": [{"id": "sf1-2","port": 0}]}]},
                {id:"sf1-1",z:"sf1",type:"test",wires:[]},
                {id:"sf1-2",z:"sf1",type:"test",wires:[]}
            ];

            var newConfig = clone(config);
            newConfig[3].out[0].wires.push({"id":"sf1-2","port":0});

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(['2', 'sf1']);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["1","3"]);
        });

        it('marks a parent subflow as changed for an internal subflow wiring change - output removed', function() {
            var config = [
                {id:"1",type:"test",wires:[["2"]]},
                {id:"2",type:"subflow:sf1",wires:[["3"]]},
                {id:"3",type:"test",wires:[]},
                {id:"sf1",type:"subflow","in": [{"wires": [{"id": "sf1-1"}]}],"out": [{"wires": [{"id": "sf1-2","port": 0}]}]},
                {id:"sf1-1",z:"sf1",type:"test",wires:[]},
                {id:"sf1-2",z:"sf1",type:"test",wires:[]}
            ];

            var newConfig = clone(config);
            newConfig[3].out[0].wires = [];

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(['2', 'sf1']);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["1","3"]);
        });

        it('marks a parent subflow as changed for a global config node change', function() {
            var config = [
                {id:"1",type:"test",wires:[["2"]]},
                {id:"2",type:"subflow:sf1",wires:[["3"]]},
                {id:"3",type:"test",wires:[]},
                {id:"sf1",type:"subflow"},
                {id:"sf1-1",z:"sf1",prop:"configNode",type:"test",wires:[]},
                {id:"sf1-2",z:"sf1",type:"test",wires:[]},
                {id:"configNode",a:"foo",type:"test",wires:[]}
            ];

            var newConfig = clone(config);
            newConfig[6].a = "bar";

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(['2', "configNode", 'sf1']);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["1","3"]);
        });

        it('marks a parent subflow as changed for an internal subflow instance change', function() {
            var config = [
                {id:"1",type:"test",wires:[["2"]]},
                {id:"2",type:"subflow:sf1",wires:[["3"]]},
                {id:"3",type:"test",wires:[]},
                {id:"sf1",type:"subflow"},
                {id:"sf2",type:"subflow"},
                {id:"sf1-1",z:"sf1",type:"test",wires:[]},
                {id:"sf1-2",z:"sf1",type:"subflow:sf2",wires:[]},
                {id:"sf2-1",z:"sf2",type:"test",wires:[]},
                {id:"sf2-2",z:"sf2",type:"test",wires:[]},
            ];

            var newConfig = clone(config);
            newConfig[8].a = "bar";

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.sort().should.eql(['2', 'sf1', 'sf2']);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
            diffResult.linked.sort().should.eql(["1","3"]);
        });

        it('ignores tab changes that are immaterial', function() {
            var config = [{id:"1",type:"tab",label:"fred"},{id:"2",type:"test",bar:"b",wires:[["1"]],z:"1"}];
            var newConfig = clone(config);
            newConfig[0].label = "barney";

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.should.have.length(0);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
        });

        it('marks a deleted tab as removed', function() {
            var config = [{id:"f1",type:"tab",label:"fred"},{id:"n1",type:"test",bar:"b",wires:[["1"]],z:"f1"},
                          {id:"f2",type:"tab",label:"fred"},{id:"n2",type:"test",bar:"b",wires:[["1"]],z:"f2"}];
            var newConfig = clone(config);
            newConfig = newConfig.slice(0,2);

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
            diffResult.added.should.have.length(0);
            diffResult.changed.should.have.length(0);
            diffResult.removed.sort().should.eql(['f2', 'n2']);
            diffResult.rewired.should.have.length(0);
        });

        it('marks all nodes as added when tab state changes disabled to enabled', function() {
            var config = [{id:"1",type:"tab",disabled:true,label:"fred"},{id:"2",type:"test",bar:"b",wires:[["1"]],z:"1"},{id:"3",type:"test"}];
            var newConfig = clone(config);
            newConfig[0].disabled = false;

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);

            diffResult.added.should.have.length(2);
            diffResult.added.sort().should.eql(["1","2"]);
            diffResult.changed.should.have.length(0);
            diffResult.removed.should.have.length(0);
            diffResult.rewired.should.have.length(0);
        });
        it('marks all nodes as removed when tab state changes enabled to disabled', function() {
            var config = [{id:"1",type:"tab",disabled:false,label:"fred"},{id:"2",type:"test",bar:"b",wires:[["1"]],z:"1"},{id:"3",type:"test"}];
            var newConfig = clone(config);
            newConfig[0].disabled = true;

            var originalConfig = flowUtil.parseConfig(config);
            var changedConfig = flowUtil.parseConfig(newConfig);

            originalConfig.missingTypes.should.have.length(0);

            var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);

            diffResult.added.should.have.length(0);
            diffResult.changed.should.have.length(0);
            diffResult.removed.should.have.length(2);
            diffResult.removed.sort().should.eql(["1","2"]);
            diffResult.rewired.should.have.length(0);
        });
    });
});


text:
<?php

namespace Doctrine\Tests\DBAL\Functional\Driver\OCI8;

use Doctrine\DBAL\Driver\OCI8\Driver;
use Doctrine\DBAL\Schema\Table;
use Doctrine\Tests\DbalFunctionalTestCase;

class OCI8ConnectionTest extends DbalFunctionalTestCase
{
    /**
     * @var \Doctrine\DBAL\Driver\OCI8\OCI8Connection
     */
    protected $driverConnection;

    protected function setUp()
    {
        if (! extension_loaded('oci8')) {
            $this->markTestSkipped('oci8 is not installed.');
        }

        parent::setUp();

        if (! $this->_conn->getDriver() instanceof Driver) {
            $this->markTestSkipped('oci8 only test.');
        }

        $this->driverConnection = $this->_conn->getWrappedConnection();
    }

    /**
     * @group DBAL-2595
     */
    public function testLastInsertIdAcceptsFqn()
    {
        $platform = $this->_conn->getDatabasePlatform();
        $schemaManager = $this->_conn->getSchemaManager();

        $table = new Table('DBAL2595');
        $table->addColumn('id', 'integer', array('autoincrement' => true));
        $table->addColumn('foo', 'integer');

        $schemaManager->dropAndCreateTable($table);

        $this->_conn->executeUpdate('INSERT INTO DBAL2595 (foo) VALUES (1)');

        $schema = $this->_conn->getDatabase();
        $sequence = $platform->getIdentitySequenceName($schema . '.DBAL2595', 'id');

        self::assertSame(1, $this->driverConnection->lastInsertId($sequence));
    }
}


text:
using System;
using System.Collections.Generic;
using Acceleratio.SPDG.Generator.SPModel;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;

namespace Acceleratio.SPDG.Generator.Server.SPModel
{
    class SPDGServerWeb : SPDGWeb
    {
        private readonly SPWeb _spWeb;

        public SPDGServerWeb(SPWeb spWeb)
        {
            _spWeb = spWeb;
        }

        public override string Url
        {
            get { return _spWeb.Url; }
        }

        public override bool HasUniqueRoleAssignments
        {
            get { return _spWeb.HasUniqueRoleAssignments; }
        }

        public override void Dispose()
        {
            _spWeb.Dispose();
        }

        public override SPDGWeb AddWeb(string url, string siteName, string description, uint lcid, string templateName, bool useUniquePermissions, bool convertIfThere)
        {
            var spWeb=_spWeb.Webs.Add(url, siteName, description, lcid, templateName, useUniquePermissions, convertIfThere);
            return new SPDGServerWeb(spWeb);
        }

        public override string Title
        {
            get { return _spWeb.Title; }
        }
        public override string ServerRelativeUrl {
            get { return _spWeb.ServerRelativeUrl; }

        }

        public override IEnumerable<SPDGWeb> Webs
        {
            get
            {
                foreach (SPWeb spWeb in _spWeb.Webs)
                {
                    yield return new SPDGServerWeb(spWeb);
                }
            }
        }

        public override SPDGWeb ParentWeb
        {
            get
            {
                if (_spWeb.ParentWeb != null)
                {
                    return new SPDGServerWeb(_spWeb.ParentWeb);
                }
                else
                {
                    return null;
                }
            }
        }

        public override void AddNavigationNode(string title, string url, NavigationNodeLocation location)
        {
            SPNavigationNodeCollection topnav = null;
            SPNavigationNode node = new SPNavigationNode(title, url);
            if (_spWeb.Navigation.GetNodeByUrl(node.Url) != null)
            {
                return;
            }
            switch (location)
            {
                case NavigationNodeLocation.TopNavigationBar:
                    topnav = _spWeb.Navigation.TopNavigationBar;
                    topnav.AddAsLast(node);
                    break;
                case NavigationNodeLocation.QuickLaunchLists:
                    _spWeb.Navigation.AddToQuickLaunch(node, SPQuickLaunchHeading.Lists);
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(location), location, null);
            }
        }

        public override string Name
        {
            get { return _spWeb.Name; }
        }

        public override Guid ID
        {
            get { return _spWeb.ID; }
        }

        public override IEnumerable<SPDGList> Lists
        {
            get
            {
                foreach (SPList spList in _spWeb.Lists)
                {
                    yield return new SPDGServerList(spList);
                }
            }
        }

        public override Guid AddList(string title, string description, int templateId)
        {
            return _spWeb.Lists.Add(title, description, (SPListTemplateType) templateId);
        }

        public override SPDGList GetList(Guid id)
        {
            return new SPDGServerList(_spWeb.Lists[id]);
        }
        public override SPDGList GetList(string listName)
        {
            return new SPDGServerList(_spWeb.Lists[listName]);
        }
        public override SPDGList TryGetList(string title)
        {
           var lst=_spWeb.Lists.TryGetList(title);
            if (lst == null)
            {
                return null;
            }
            else
            {
                return new SPDGServerList(lst);
            }
        }

        public override SPDGRoleAssignment GetRoleAssignmentByPrincipal(SPDGPrincipal principal)
        {
            return ServerRoleAssignmentHelper.GetRoleAssignmentByPrincipal(_spWeb, principal);

        }

        public override void AddRoleAssignment(SPDGPrincipal principal, IEnumerable<SPDGRoleDefinition> roledefinitions)
        {
           ServerRoleAssignmentHelper.AddRoleAssignment(_spWeb, principal, roledefinitions);
        }

        public override void BreakRoleInheritance(bool copyRoleAssignments)
        {
            _spWeb.BreakRoleInheritance(copyRoleAssignments);
        }

        public override SPDGUser EnsureUser(string loginName)
        {
            var spUser = _spWeb.EnsureUser(loginName);

            return new SPDGServerUser(spUser);
        }

        public override void AddSiteGroup(string name, SPDGUser owner, SPDGUser defaultUser, string description)
        {
            var spOwner =((SPDGServerUser)owner).SPUser;
            var spDefaultUser = ((SPDGServerUser)defaultUser).SPUser;

            _spWeb.SiteGroups.Add(name, spOwner, spDefaultUser, description);
        }

        public override SPDGUser CurrentUser
        {
            get
            {
                return new SPDGServerUser(_spWeb.CurrentUser);
            }
        }

        public override IEnumerable<SPDGGroup> SiteGroups
        {
            get
            {

                foreach (SPGroup spGroup in _spWeb.SiteGroups)
                {
                    yield return  new SPDGServerGroup(spGroup);
                }
            }
        }

        public override IEnumerable<SPDGUser> SiteUsers
        {
            get
            {
                foreach (SPUser siteUser in _spWeb.SiteUsers)
                {
                    yield return new SPDGServerUser(siteUser);
                }
            }
        }

        public override IEnumerable<SPDGRoleDefinition> RoleDefinitions
        {
            get
            {
                foreach (SPRoleDefinition roleDefinition in _spWeb.RoleDefinitions)
                {
                    yield return new SPDGServerRoleDefinition(roleDefinition);
                }
            }
        }

        public override SPDGFolder GetFolder(string folderUrl)
        {
            return new SPDGServerFolder(_spWeb.GetFolder(folderUrl));
        }

        public override IEnumerable<SPDGWebTemplate> GetWebTemplates(uint lcid)
        {
            foreach (SPWebTemplate template in _spWeb.GetAvailableWebTemplates(lcid))
            {
                yield return new SPDGWebTemplate(template.Name, template.Title);
            }
        }

        public override uint Language
        {
            get { return _spWeb.Language; }
        }
    }
}


text:
package de.datareply

import org.scalatest._

class JenkinsTest extends FlatSpec with Matchers {
  val jenkins = new Jenkins

  "A Jenkins" should "return square" in {
    val in = 2
    jenkins.square(in) shouldBe(in * in)
  }

  it should "work with 0" in {
    val in = 0
    jenkins.square(in) shouldBe(in * in)
  }

  it should "work with maxInt" in {
    val in = Int.MaxValue
    jenkins.square(in) shouldBe(in * in)
  }

}


text:
import glob
import os
import re
import shutil
import subprocess
import sys
import unittest
from contextlib import contextmanager
from dataclasses import dataclass
from operator import eq, ne
from threading import Lock
from typing import Any, Callable, List, Optional, Union

from colors import strip_color

from pants.base.build_environment import get_buildroot
from pants.base.build_file import BuildFile
from pants.base.exiter import PANTS_SUCCEEDED_EXIT_CODE
from pants.fs.archive import ZIP
from pants.option.config import TomlSerializer
from pants.subsystem.subsystem import Subsystem
from pants.testutil.file_test_util import check_symlinks, contains_exact_files
from pants.util.contextutil import environment_as, pushd, temporary_dir
from pants.util.dirutil import fast_relpath, safe_mkdir, safe_mkdir_for, safe_open
from pants.util.osutil import Pid
from pants.util.process_handler import SubprocessProcessHandler
from pants.util.strutil import ensure_binary

# NB: If `shell=True`, it's a single `str`.
Command = Union[str, List[str]]

@dataclass(frozen=True)
class PantsResult:
    command: Command
    returncode: int
    stdout_data: str
    stderr_data: str
    workdir: str
    pid: Pid

@dataclass(frozen=True)
class PantsJoinHandle:
    command: Command
    process: subprocess.Popen
    workdir: str

    def join(
        self, stdin_data: Optional[Union[bytes, str]] = None, tee_output: bool = False
    ) -> PantsResult:
        """Wait for the pants process to complete, and return a PantsResult for it."""

        communicate_fn = self.process.communicate
        if tee_output:
            # TODO: MyPy complains that SubprocessProcessHandler.communicate_teeing_stdout_and_stderr does
            # not have the same type signature as subprocess.Popen.communicate_teeing_stdout_and_stderr.
            # It's possibly not worth trying to fix this because the type stubs for subprocess.Popen are
            # very complex and also not very precise, given how many different configurations Popen can
            # take.
            communicate_fn = SubprocessProcessHandler(self.process).communicate_teeing_stdout_and_stderr  # type: ignore[assignment]
        if stdin_data is not None:
            stdin_data = ensure_binary(stdin_data)
        (stdout_data, stderr_data) = communicate_fn(stdin_data)

        if self.process.returncode != PANTS_SUCCEEDED_EXIT_CODE:
            render_logs(self.workdir)

        return PantsResult(
            command=self.command,
            returncode=self.process.returncode,
            stdout_data=stdout_data.decode(),
            stderr_data=stderr_data.decode(),
            workdir=self.workdir,
            pid=self.process.pid,
        )

def ensure_cached(expected_num_artifacts=None):
    """Decorator for asserting cache writes in an integration test.

    :param expected_num_artifacts: Expected number of artifacts to be in the task's
                                   cache after running the test. If unspecified, will
                                   assert that the number of artifacts in the cache is
                                   non-zero.
    """

    def decorator(test_fn):
        def wrapper(self, *args, **kwargs):
            with temporary_dir() as artifact_cache:
                cache_args = f'--cache-write-to=["{artifact_cache}"]'

                test_fn(self, *args + (cache_args,), **kwargs)

                num_artifacts = 0
                for (root, _, files) in os.walk(artifact_cache):
                    print(root, files)
                    num_artifacts += len(files)

                if expected_num_artifacts is None:
                    self.assertNotEqual(num_artifacts, 0)
                else:
                    self.assertEqual(num_artifacts, expected_num_artifacts)

        return wrapper

    return decorator

def ensure_daemon(f):
    """A decorator for running an integration test with and without the daemon enabled."""

    def wrapper(self, *args, **kwargs):
        for enable_daemon in [False, True]:
            with temporary_dir() as subprocess_dir:
                enable_daemon_str = str(enable_daemon)
                env = {
                    "HERMETIC_ENV": "PANTS_ENABLE_PANTSD,PANTS_ENABLE_V2_ENGINE,PANTS_SUBPROCESSDIR",
                    "PANTS_ENABLE_PANTSD": enable_daemon_str,
                    "PANTS_ENABLE_V2_ENGINE": enable_daemon_str,
                    "PANTS_SUBPROCESSDIR": subprocess_dir,
                }
                with environment_as(**env):
                    try:
                        f(self, *args, **kwargs)
                        if enable_daemon:
                            self.assert_success(self.run_pants(["kill-pantsd"]))
                    except Exception:
                        print(f"Test failed with enable-pantsd={enable_daemon}:")
                        if enable_daemon:
                            # If we are already raising, do not attempt to confirm that `kill-pantsd` succeeds.
                            self.run_pants(["kill-pantsd"])
                        else:
                            print(
                                "Skipping run with enable-pantsd=true because it already failed with enable-pantsd=false."
                            )
                        raise

    return wrapper

def render_logs(workdir):
    """Renders all potentially relevant logs from the given workdir to stdout."""
    filenames = list(glob.glob(os.path.join(workdir, "logs/exceptions*log"))) + list(
        glob.glob(os.path.join(workdir, "pantsd/pantsd.log"))
    )
    for filename in filenames:
        rel_filename = fast_relpath(filename, workdir)
        print(f"{rel_filename} +++ ")
        for line in _read_log(filename):
            print(f"{rel_filename} >>> {line}")
        print(f"{rel_filename} --- ")

def read_pantsd_log(workdir):
    """Yields all lines from the pantsd log under the given workdir."""
    # Surface the pantsd log for easy viewing via pytest's `-s` (don't capture stdio) option.
    for line in _read_log(f"{workdir}/pantsd/pantsd.log"):
        yield line

def _read_log(filename):
    with open(filename, "r") as f:
        for line in f:
            yield line.rstrip()

class PantsRunIntegrationTest(unittest.TestCase):
    """A base class useful for integration tests for targets in the same repo."""

    class InvalidTestEnvironmentError(Exception):
        """Raised when the external environment is not set up properly to run integration tests."""

    @classmethod
    def use_pantsd_env_var(cls):
        """Subclasses may override to acknowledge that the tests cannot run when pantsd is enabled,
        or they want to configure pantsd themselves.

        In those cases, --enable-pantsd will not be added to their configuration.
        This approach is coarsely grained, meaning we disable pantsd in some tests that actually run
        when pantsd is enabled. However:
          - The number of mislabeled tests is currently small (~20 tests).
          - Those tests will still run, just with pantsd disabled.

        N.B. Currently, this doesn't interact with test hermeticity.
        This means that, if the test coordinator has set PANTS_ENABLE_PANTSD, and a test is not marked
        as hermetic, it will run under pantsd regardless of the value of this function.
        """
        should_pantsd = os.getenv("USE_PANTSD_FOR_INTEGRATION_TESTS")
        return should_pantsd in ["True", "true", "1"]

    @classmethod
    def hermetic(cls):
        """Subclasses may override to acknowledge that they are hermetic.

        That is, that they should run without reading the real pants.toml.
        """
        return False

    @classmethod
    def hermetic_env_whitelist(cls):
        """A whitelist of environment variables to propagate to tests when hermetic=True."""
        return [
            # Used in the wrapper script to locate a rust install.
            "HOME",
            # Needed to find python interpreters and other binaries.
            "PATH",
            "PANTS_PROFILE",
            # Ensure that the underlying ./pants invocation doesn't run from sources
            # (and therefore bootstrap) if we don't want it to.
            "RUN_PANTS_FROM_PEX",
        ]

    def setUp(self):
        super().setUp()
        # Some integration tests rely on clean subsystem state (e.g., to set up a DistributionLocator).
        Subsystem.reset()

    def temporary_workdir(self, cleanup=True):
        # We can hard-code '.pants.d' here because we know that will always be its value
        # in the pantsbuild/pants repo (e.g., that's what we .gitignore in that repo).
        # Grabbing the pants_workdir config would require this pants's config object,
        # which we don't have a reference to here.
        root = os.path.join(get_buildroot(), ".pants.d", "tmp")
        safe_mkdir(root)
        return temporary_dir(root_dir=root, cleanup=cleanup, suffix=".pants.d")

    def temporary_cachedir(self):
        return temporary_dir(suffix="__CACHEDIR")

    def temporary_sourcedir(self):
        return temporary_dir(root_dir=get_buildroot())

    @contextmanager
    def source_clone(self, source_dir):
        with self.temporary_sourcedir() as clone_dir:
            target_spec_dir = os.path.relpath(clone_dir)

            for dir_path, dir_names, file_names in os.walk(source_dir):
                clone_dir_path = os.path.join(clone_dir, os.path.relpath(dir_path, source_dir))
                for dir_name in dir_names:
                    os.mkdir(os.path.join(clone_dir_path, dir_name))
                for file_name in file_names:
                    with open(os.path.join(dir_path, file_name), "r") as f:
                        content = f.read()
                    if BuildFile._is_buildfile_name(file_name):
                        content = content.replace(source_dir, target_spec_dir)
                    with open(os.path.join(clone_dir_path, file_name), "w") as f:
                        f.write(content)

            yield clone_dir

    # Incremented each time we spawn a pants subprocess.
    # Appended to PANTS_PROFILE in the called pants process, so that each subprocess
    # writes to its own profile file, instead of all stomping on the parent process's profile.
    _profile_disambiguator = 0
    _profile_disambiguator_lock = Lock()

    @classmethod
    def _get_profile_disambiguator(cls):
        with cls._profile_disambiguator_lock:
            ret = cls._profile_disambiguator
            cls._profile_disambiguator += 1
            return ret

    def get_cache_subdir(self, cache_dir, subdir_glob="*/", other_dirs=()):
        """Check that there is only one entry of `cache_dir` which matches the glob specified by
        `subdir_glob`, excluding `other_dirs`, and return it.

        :param str cache_dir: absolute path to some directory.
        :param str subdir_glob: string specifying a glob for (one level down)
                                subdirectories of `cache_dir`.
        :param list other_dirs: absolute paths to subdirectories of `cache_dir`
                                which must exist and match `subdir_glob`.
        :return: Assert that there is a single remaining directory entry matching
                 `subdir_glob` after removing `other_dirs`, and return it.

                 This method oes not check if its arguments or return values are
                 files or directories. If `subdir_glob` has a trailing slash, so
                 will the return value of this method.
        """
        subdirs = set(glob.glob(os.path.join(cache_dir, subdir_glob)))
        other_dirs = set(other_dirs)
        self.assertTrue(other_dirs.issubset(subdirs))
        remaining_dirs = subdirs - other_dirs
        self.assertEqual(len(remaining_dirs), 1)
        return list(remaining_dirs)[0]

    def run_pants_with_workdir_without_waiting(
        self,
        command,
        workdir,
        config=None,
        extra_env=None,
        build_root=None,
        print_exception_stacktrace=True,
        **kwargs,
    ) -> PantsJoinHandle:
        args = [
            "--no-pantsrc",
            f"--pants-workdir={workdir}",
            f"--print-exception-stacktrace={print_exception_stacktrace}",
        ]
        # TODO: If the default value for `--v1` changes to False then this check will
        # Have to change to `if '--v1' in command:`.
        if "--no-v1" not in command:
            args.append("--kill-nailguns")

        if self.hermetic():
            args.extend(
                [
                    "--pants-config-files=[]",
                    # Turn off cache globally.  A hermetic integration test shouldn't rely on cache,
                    # or we have no idea if it's actually testing anything.
                    "--no-cache-read",
                    "--no-cache-write",
                    # Turn cache on just for tool bootstrapping, for performance.
                    "--cache-bootstrap-read",
                    "--cache-bootstrap-write",
                ]
            )

        if self.use_pantsd_env_var():
            args.append("--enable-pantsd=True")
            args.append("--no-shutdown-pantsd-after-run")

        if config:
            toml_file_name = os.path.join(workdir, "pants.toml")
            with safe_open(toml_file_name, mode="w") as fp:
                fp.write(TomlSerializer(config).serialize())
            args.append("--pants-config-files=" + toml_file_name)

        pants_script = [sys.executable, "-m", "pants"]

        # Permit usage of shell=True and string-based commands to allow e.g. `./pants | head`.
        if kwargs.get("shell") is True:
            assert not isinstance(
                command, list
            ), "must pass command as a string when using shell=True"
            pants_command = " ".join([*pants_script, " ".join(args), command])
        else:
            pants_command = pants_script + args + command

        # Only whitelisted entries will be included in the environment if hermetic=True.
        if self.hermetic():
            env = dict()
            # With an empty environment, we would generally get the true underlying system default
            # encoding, which is unlikely to be what we want (it's generally ASCII, still). So we
            # explicitly set an encoding here.
            env["LC_ALL"] = "en_US.UTF-8"
            for h in self.hermetic_env_whitelist():
                value = os.getenv(h)
                if value is not None:
                    env[h] = value
            hermetic_env = os.getenv("HERMETIC_ENV")
            if hermetic_env:
                for h in hermetic_env.strip(",").split(","):
                    value = os.getenv(h)
                    if value is not None:
                        env[h] = value
        else:
            env = os.environ.copy()
        if extra_env:
            env.update(extra_env)
        env.update(PYTHONPATH=os.pathsep.join(sys.path))

        # Pants command that was called from the test shouldn't have a parent.
        if "PANTS_PARENT_BUILD_ID" in env:
            del env["PANTS_PARENT_BUILD_ID"]

        # Don't overwrite the profile of this process in the called process.
        # Instead, write the profile into a sibling file.
        if env.get("PANTS_PROFILE"):
            prof = f"{env['PANTS_PROFILE']}.{self._get_profile_disambiguator()}"
            env["PANTS_PROFILE"] = prof
            # Make a note the subprocess command, so the user can correctly interpret the profile files.
            with open(f"{prof}.cmd", "w") as fp:
                fp.write(" ".join(pants_command))

        return PantsJoinHandle(
            command=pants_command,
            process=subprocess.Popen(
                pants_command,
                env=env,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                **kwargs,
            ),
            workdir=workdir,
        )

    def run_pants_with_workdir(
        self, command, workdir, config=None, stdin_data=None, tee_output=False, **kwargs
    ) -> PantsResult:
        if config:
            kwargs["config"] = config
        handle = self.run_pants_with_workdir_without_waiting(command, workdir, **kwargs)
        return handle.join(stdin_data=stdin_data, tee_output=tee_output)

    def run_pants(
        self, command, config=None, stdin_data=None, extra_env=None, cleanup_workdir=True, **kwargs
    ) -> PantsResult:
        """Runs pants in a subprocess.

        :param list command: A list of command line arguments coming after `./pants`.
        :param config: Optional data for a generated TOML file. A map of <section-name> ->
        map of key -> value.
        :param kwargs: Extra keyword args to pass to `subprocess.Popen`.
        """
        with self.temporary_workdir() as workdir:
            return self.run_pants_with_workdir(
                command, workdir, config, stdin_data=stdin_data, extra_env=extra_env, **kwargs
            )

    @contextmanager
    def pants_results(self, command, config=None, stdin_data=None, extra_env=None, **kwargs):
        """Similar to run_pants in that it runs pants in a subprocess, but yields in order to give
        callers a chance to do any necessary validations on the workdir.

        :param list command: A list of command line arguments coming after `./pants`.
        :param config: Optional data for a generated TOML file. A map of <section-name> ->
        map of key -> value.
        :param kwargs: Extra keyword args to pass to `subprocess.Popen`.
        :returns a PantsResult instance.
        """
        with self.temporary_workdir() as workdir:
            yield self.run_pants_with_workdir(
                command, workdir, config, stdin_data=stdin_data, extra_env=extra_env, **kwargs
            )

    def bundle_and_run(
        self,
        target,
        bundle_name,
        bundle_jar_name=None,
        bundle_options=None,
        args=None,
        expected_bundle_jar_content=None,
        expected_bundle_content=None,
        library_jars_are_symlinks=True,
    ):
        """Creates the bundle with pants, then does java -jar {bundle_name}.jar to execute the
        bundle.

        :param target: target name to compile
        :param bundle_name: resulting bundle filename (minus .zip extension)
        :param bundle_jar_name: monolithic jar filename (minus .jar extension), if None will be the
          same as bundle_name
        :param bundle_options: additional options for bundle
        :param args: optional arguments to pass to executable
        :param expected_bundle_content: verify the bundle zip content
        :param expected_bundle_jar_content: verify the bundle jar content
        :param library_jars_are_symlinks: verify library jars are symlinks if True, and actual
          files if False. Default `True` because we always create symlinks for both external and internal
          dependencies, only exception is when shading is used.
        :return: stdout as a string on success, raises an Exception on error
        """
        bundle_jar_name = bundle_jar_name or bundle_name
        bundle_options = bundle_options or []
        bundle_options = ["bundle.jvm"] + bundle_options + ["--archive=zip", target]
        with self.pants_results(bundle_options) as pants_run:
            self.assert_success(pants_run)

            self.assertTrue(
                check_symlinks(f"dist/{bundle_name}-bundle/libs", library_jars_are_symlinks)
            )
            # TODO(John Sirois): We need a zip here to suck in external library classpath elements
            # pointed to by symlinks in the run_pants ephemeral tmpdir.  Switch run_pants to be a
            # contextmanager that yields its results while the tmpdir workdir is still active and change
            # this test back to using an un-archived bundle.
            with temporary_dir() as workdir:
                ZIP.extract(f"dist/{bundle_name}.zip", workdir)
                if expected_bundle_content:
                    self.assertTrue(contains_exact_files(workdir, expected_bundle_content))
                if expected_bundle_jar_content:
                    with temporary_dir() as check_bundle_jar_dir:
                        bundle_jar = os.path.join(workdir, f"{bundle_jar_name}.jar")
                        ZIP.extract(bundle_jar, check_bundle_jar_dir)
                        self.assertTrue(
                            contains_exact_files(check_bundle_jar_dir, expected_bundle_jar_content)
                        )

                optional_args = []
                if args:
                    optional_args = args
                java_run = subprocess.Popen(
                    ["java", "-jar", f"{bundle_jar_name}.jar"] + optional_args,
                    stdout=subprocess.PIPE,
                    cwd=workdir,
                )

                stdout, _ = java_run.communicate()
            java_returncode = java_run.returncode
            self.assertEqual(java_returncode, 0)
            return stdout.decode()

    def assert_success(self, pants_run: PantsResult, msg=None):
        self.assert_result(pants_run, PANTS_SUCCEEDED_EXIT_CODE, expected=True, msg=msg)

    def assert_failure(self, pants_run: PantsResult, msg=None):
        self.assert_result(pants_run, PANTS_SUCCEEDED_EXIT_CODE, expected=False, msg=msg)

    def assert_result(self, pants_run: PantsResult, value, expected=True, msg=None):
        check, assertion = (eq, self.assertEqual) if expected else (ne, self.assertNotEqual)
        if check(pants_run.returncode, value):
            return

        details = [msg] if msg else []
        details.append(" ".join(pants_run.command))
        details.append(f"returncode: {pants_run.returncode}")

        def indent(content):
            return "\n\t".join(content.splitlines())

        details.append(f"stdout:\n\t{indent(pants_run.stdout_data)}")
        details.append(f"stderr:\n\t{indent(pants_run.stderr_data)}")
        error_msg = "\n".join(details)

        assertion(value, pants_run.returncode, error_msg)

    def assert_run_contains_log(self, msg, level, module, pants_run: PantsResult):
        """Asserts that the passed run's stderr contained the log message."""
        self.assert_contains_log(msg, level, module, pants_run.stderr_data, pants_run.pid)

    def assert_contains_log(self, msg, level, module, log, pid=None):
        """Asserts that the passed log contains the message logged by the module at the level.

        If pid is specified, performs an exact match including the pid of the pants process.
        Otherwise performs a regex match asserting that some pid is present.
        """
        prefix = f"[{level}] {module}:pid="
        suffix = f": {msg}"
        if pid is None:
            self.assertRegex(log, re.escape(prefix) + r"\d+" + re.escape(suffix))
        else:
            self.assertIn(f"{prefix}{pid}{suffix}", log)

    def assert_is_file(self, file_path):
        self.assertTrue(os.path.isfile(file_path), f"file path {file_path} does not exist!")

    def assert_is_not_file(self, file_path):
        self.assertFalse(os.path.isfile(file_path), f"file path {file_path} exists!")

    def normalize(self, s: str) -> str:
        """Removes escape sequences (e.g. colored output) and all whitespace from string s."""
        return "".join(strip_color(s).split())

    @contextmanager
    def file_renamed(self, prefix, test_name, real_name):
        real_path = os.path.join(prefix, real_name)
        test_path = os.path.join(prefix, test_name)
        try:
            os.rename(test_path, real_path)
            yield
        finally:
            os.rename(real_path, test_path)

    @contextmanager
    def temporary_file_content(self, path, content, binary_mode=True):
        """Temporarily write content to a file for the purpose of an integration test."""
        path = os.path.realpath(path)
        assert path.startswith(
            os.path.realpath(get_buildroot())
        ), "cannot write paths outside of the buildroot!"
        assert not os.path.exists(path), "refusing to overwrite an existing path!"
        mode = "wb" if binary_mode else "w"
        with open(path, mode) as fh:
            fh.write(content)
        try:
            yield
        finally:
            os.unlink(path)

    @contextmanager
    def with_overwritten_file_content(self, file_path, temporary_content=None):
        """A helper that resets a file after the method runs.

         It will read a file, save the content, maybe write temporary_content to it, yield, then write the
         original content to the file.

        :param file_path: Absolute path to the file to be reset after the method runs.
        :param temporary_content: Optional content to write into the file.
        """
        with open(file_path, "r") as f:
            file_original_content = f.read()

        try:
            if temporary_content is not None:
                with open(file_path, "w") as f:
                    f.write(temporary_content)
            yield

        finally:
            with open(file_path, "w") as f:
                f.write(file_original_content)

    @contextmanager
    def mock_buildroot(self, dirs_to_copy=None):
        """Construct a mock buildroot and return a helper object for interacting with it."""

        @dataclass(frozen=True)
        class Manager:
            write_file: Callable[[str, str], None]
            pushd: Any
            new_buildroot: str

        # N.B. BUILD.tools, contrib, 3rdparty needs to be copied vs symlinked to avoid
        # symlink prefix check error in v1 and v2 engine.
        files_to_copy = ("BUILD.tools",)
        files_to_link = (
            "BUILD_ROOT",
            ".isort.cfg",
            ".pants.d",
            "build-support",
            # NB: when running with --chroot or the V2 engine, `pants` refers to the source root-stripped
            # directory src/python/pants, not the script `./pants`.
            "pants",
            "pants.pex",
            "pants-plugins",
            "pants.toml",
            "pants.travis-ci.toml",
            "pyproject.toml",
            "rust-toolchain",
            "src",
        )
        dirs_to_copy = ("3rdparty", "contrib") + tuple(dirs_to_copy or [])

        with self.temporary_workdir() as tmp_dir:
            for filename in files_to_copy:
                shutil.copy(
                    os.path.join(get_buildroot(), filename), os.path.join(tmp_dir, filename)
                )

            for dirname in dirs_to_copy:
                shutil.copytree(
                    os.path.join(get_buildroot(), dirname), os.path.join(tmp_dir, dirname)
                )

            for filename in files_to_link:
                link_target = os.path.join(get_buildroot(), filename)
                if os.path.exists(link_target):
                    os.symlink(link_target, os.path.join(tmp_dir, filename))

            def write_file(file_path, contents):
                full_file_path = os.path.join(tmp_dir, *file_path.split(os.pathsep))
                safe_mkdir_for(full_file_path)
                with open(full_file_path, "w") as fh:
                    fh.write(contents)

            @contextmanager
            def dir_context():
                with pushd(tmp_dir):
                    yield

            yield Manager(write_file, dir_context, tmp_dir)

    def do_command(self, *args, **kwargs) -> PantsResult:
        """Wrapper around run_pants method.

        :param args: command line arguments used to run pants
        """
        cmd = list(args)
        success = kwargs.pop("success", True)
        pants_run = self.run_pants(cmd, **kwargs)
        if success:
            self.assert_success(pants_run)
        else:
            self.assert_failure(pants_run)
        return pants_run

    @contextmanager
    def do_command_yielding_workdir(self, *args, **kwargs):
        cmd = list(args)
        success = kwargs.pop("success", True)
        with self.pants_results(cmd, **kwargs) as pants_run:
            if success:
                self.assert_success(pants_run)
            else:
                self.assert_failure(pants_run)
            yield pants_run