text:
namespace VisioAutomation.VDX.ShapeSheet
{
    public class CellScalar<T> : CellBase where T : struct
    {
        public T? Result { get; set; }

        public CellScalar() :
            base()
        {
        }

        public CellScalar(CellUnit unit)
            : base(unit)
        {
        }

        public override string GetResultString()
        {
            return string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}", this.Result);
        }

        public override bool HasResult
        {
            get { return this.Result.HasValue; }
        }
    }
}


text:
package main

import (
	"github.com/name5566/leaf"
	lconf "github.com/name5566/leaf/conf"
	"server/conf"
	"server/game"
	"server/gate"
	"server/login"
	"server/gamedata"
	"fmt"
	"server/mysql"
)

func main() {
	mysql.OpenDB()
	lconf.LogLevel = conf.Server.LogLevel
	lconf.LogPath = conf.Server.LogPath
	lconf.LogFlag = conf.LogFlag
	lconf.ConsolePort = conf.Server.ConsolePort
	lconf.ProfilePath = conf.Server.ProfilePath

	gamedata.LoadTables()
	testData := gamedata.GetDataByID(2)
	fmt.Println(testData.Name)

	leaf.Run(
		game.Module,
		gate.Module,
		login.Module,
	)

}

func  InitDBTable()  {

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Microsporum orientale Carol

### Remarks
null


text:
set -ex

main() {
    local cargo=cross
    if [ "$SKIP_CROSS" = "skip" ]; then
        cargo=cargo
    fi
    local release_flag=""
    if [ "$IS_DEPLOY" = "true" ]; then
        release_flag="--release"
    fi

    if [ "$NO_STD" = "true" ]; then
        cargo build --target $TARGET --no-default-features --features software-rendering $FEATURES
        return
    fi

    case $TARGET in
        wasm32-unknown-unknown)
            $cargo build -p cdylib --target $TARGET $release_flag $FEATURES
            ;;
        wasm32-wasi)
            $cargo build -p cdylib --target $TARGET $release_flag $FEATURES
            ;;
        *)
            $cargo build -p staticlib --target $TARGET $release_flag $FEATURES
            ;;
    esac
}

main


text:
package org.veripacks

import data.t1.p11.Class112
import data.t1.p12.Class121
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.FlatSpec
import org.veripacks.data.t3.p32.Class321
import org.veripacks.data.t3.p31.Class311
import org.veripacks.data.t6.p61.Class611
import org.veripacks.data.t6.p62.Class621
import org.veripacks.data.t7.Class71

class VeripacksTest extends FlatSpec with ShouldMatchers {
  it should "report export errors" in {
    // When
    val result = VeripacksBuilder.build.verify(List("org.veripacks.data.t1"))

    // Then
    verifyBrokenConstraintsOnlyFrom(result, classOf[Class112], classOf[Class121])
  }

  it should "report no export errors" in {
    // When
    val result = VeripacksBuilder.build.verify(List("org.veripacks.data.t2"))

    // Then
    result should be (VerifyResultOk)
  }

  it should "report import errors" in {
    // When
    val result = VeripacksBuilder.build.verify(List("org.veripacks.data.t3"))

    // Then
    verifyBrokenConstraintsOnlyFrom(result, classOf[Class321], classOf[Class311])
  }

  it should "report no import errors" in {
    // When
    val result = VeripacksBuilder.build.verify(List("org.veripacks.data.t4"))

    // Then
    result should be (VerifyResultOk)
  }

  it should "report no errors when verification is skipped" in {
    // When
    val result = VeripacksBuilder.build.verify(List("org.veripacks.data.t5"))

    // Then
    result should be (VerifyResultOk)
  }

  it should "report import errors basing on custom-provided metadata" in {
    // When
    val result = VeripacksBuilder
      .withCustomAccessDefinitionReader(new CustomAccessDefinitionsReader {
        override def isRequiresImport(pkg: Pkg) = pkg.name == "org.veripacks.data.t6.p62"
      })
      .build
      .verify(List("org.veripacks.data.t6"))

    // Then
    verifyBrokenConstraintsOnlyFrom(result, classOf[Class621], classOf[Class611])
  }

  it should "report import errors when 3rd party libs are checked and not imported" in {
    // When
    val result = VeripacksBuilder
      .requireImportOf("com.typesafe")
      .build
      .verify(List("org.veripacks.data.t7"))

    // Then
    verifyBrokenConstraintsOnlyFrom(result, classOf[com.typesafe.scalalogging.slf4j.Logger], classOf[Class71],
      clsSuffix = "$")
  }

  it should "report no import errors when 3rd party libs are checked and imported" in {
    // When
    val result = VeripacksBuilder
      .requireImportOf("com.typesafe")
      .build
      .verify(List("org.veripacks.data.t8"))

    // Then
    result should be (VerifyResultOk)
  }

  def verifyBrokenConstraintsOnlyFrom(result: VerifyResult, cls: Class[_], usedIn: Class[_], clsSuffix: String = "") = {
    result match {
      case VerifyResultBrokenConstraints(brokenConstraints) => {
        brokenConstraints.size should be > (0)
        brokenConstraints.map(_._1.cls).toSet should be (Set(from(cls, clsSuffix)))
        brokenConstraints.map(_._1.usedIn).toSet should be (Set(from(usedIn)))
        brokenConstraints.map(_._1.detail.sourceFileName).toSet should be (Set(s"${usedIn.getSimpleName}.scala"))
      }
      case _ => fail(s"Expected a broken constraints result, but got $result!")
    }
  }

  private def from(cls: Class[_], suffix: String = "") = new ClassName(Pkg(cls.getPackage.getName), cls.getSimpleName + suffix)
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC  "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/>
      <meta name="description" content="W3C SVG 1.1 2nd Edition Object Test Suite"/>
      <title>
	<d:testDescription href='http://www.w3.org/TR/SVG11/pservers.html#Gradients' xmlns='http://www.w3.org/1999/xhtml'>

          The purpose of this file is to test several values for focal points of radial gradients.

    </d:testDescription>
      </title>

            SVG Image - The test

            PNG Image - The reference

            <object id="test" data="http://t/core/standards/SVG/Testsuites/W3C-1_1F2/harness/htmlObjectMini/modified/svg/test/pservers-grad-13-b.svg" width="480" height="360" type="image/svg+xml"> </object>

			    Test Description

				<d:testDescription href='http://www.w3.org/TR/SVG11/pservers.html#Gradients' xmlns='http://www.w3.org/1999/xhtml'>

          The purpose of this file is to test several values for focal points of radial gradients.

    </d:testDescription>

			      Operator Script

<d:operatorScript xmlns='http://www.w3.org/1999/xhtml'>

        The UA should render a result equivalent to the referenced image.

    </d:operatorScript>


text:
module DirectedGraph
  class Vertex
    attr_reader :graph, :payload
    def initialize(graph, payload)
      @graph = graph
      @payload = payload
    end

    def incomming_edges
      graph.edges.select {|e| e.to? payload }
    end

    def outgoing_edges
      graph.edges.select {|e| e.from? payload }
    end

    def neighbours
      self.outgoing_edges.collect {|e| graph.vertex(e.to)}
    end

    def == other
      other.instance_of?(self.class) &&
        self.graph == other.graph &&
        self.payload == other.payload
    end
  end
end


text:
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Main export is the Adele object
//
var Adele = {};

Adele.random = function () {
  return randomInt(1, 13);
};

module.exports = Adele;


text:
<datasources>
	<datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
	  <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</connection-url>
	  <driver>h2</driver>
	  <security>
		<user-name>sa</user-name>
		<password>sa</password>
	  </security>
	</datasource>
	<xa-datasource jndi-name="java:jboss/datasources/CycleDS" pool-name="CycleDS" enabled="true" use-ccm="false">
	  <xa-datasource-property name="ServerName">
		${database.host}
	  </xa-datasource-property>
	  <xa-datasource-property name="PortNumber">
		50000
	  </xa-datasource-property>
	  <xa-datasource-property name="DatabaseName">
		${database.name}
	  </xa-datasource-property>
	  <xa-datasource-property name="DriverType">
		4
	  </xa-datasource-property>
	  <xa-datasource-property name="User">
		${database.user}
	  </xa-datasource-property>
	  <xa-datasource-property name="Password">
		${database.password}
	  </xa-datasource-property>
	  <driver>db2</driver>
	  <xa-pool>
		<is-same-rm-override>false</is-same-rm-override>
		<no-tx-separate-pools>true</no-tx-separate-pools>
	  </xa-pool>
	  <validation>
		<valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.db2.DB2ValidConnectionChecker"/>
		<stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.db2.DB2StaleConnectionChecker"/>
		<exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.db2.DB2ExceptionSorter"/>
	  </validation>
	</xa-datasource>
	<xa-datasource jndi-name="java:jboss/datasources/ProcessEngine" pool-name="ProcessEngine" enabled="true" use-ccm="false">
	  <xa-datasource-property name="ServerName">
		${database.host}
	  </xa-datasource-property>
	  <xa-datasource-property name="PortNumber">
		50000
	  </xa-datasource-property>
	  <xa-datasource-property name="DatabaseName">
		${database.name}
	  </xa-datasource-property>
	  <xa-datasource-property name="DriverType">
		4
	  </xa-datasource-property>
	  <xa-datasource-property name="User">
		${database.user}
	  </xa-datasource-property>
	  <xa-datasource-property name="Password">
		${database.password}
	  </xa-datasource-property>
	  <driver>db2</driver>
	  <xa-pool>
		<is-same-rm-override>false</is-same-rm-override>
		<no-tx-separate-pools>true</no-tx-separate-pools>
	  </xa-pool>
	  <validation>
		<valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.db2.DB2ValidConnectionChecker"/>
		<stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.db2.DB2StaleConnectionChecker"/>
		<exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.db2.DB2ExceptionSorter"/>
	  </validation>
	</xa-datasource>
</datasources>


text:
from __future__ import unicode_literals, print_function
from io import StringIO
from wex.output import StdOut, CHUNK_SIZE

def test_stdout_big_write_causes_flush():
    big_chunk = 'x' * (CHUNK_SIZE + 1)
    stdout = StdOut(None)
    stdout.stdout = StringIO()
    stdout.write(big_chunk)
    assert len(stdout.stdout.getvalue()) == len(big_chunk)


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using Pchp.Core;
using Pchp.Library.Resources;

namespace Pchp.Library
{
    [PhpExtension("ereg")]
    public static class RegExpPosix
    {
        #region split, spliti

        /// <summary>
        /// Splits string <c>str</c> to arrays of strings by regular expression <c>pattern</c>.
        /// Returned array contains max. <c>limit</c> elements. If there is more substrings in <c>str</c>,
        /// array contains only first <c>limit-1</c> substrings and last element contains the whole rest
        /// of input <c>string</c>.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="pattern">Regular expression matching string delimiters.</param>
        /// <param name="str">String to split according to regular expression.</param>
        /// <param name="limit">Max number of elements in returned array.</param>
        /// <returns>Array of substrings.</returns>
        [Obsolete]
        public static PhpArray split(Context ctx, string pattern, string str, int limit = -1)
        {
            PhpException.FunctionDeprecated("split");

            return DoSplit(
                ctx,
                pattern,
                str,
                limit,
                limit >= 0,   // use limit (previous parameter)
                false         // case sensitive
                );
        }

        /// <summary>
        /// Splits string <c>str</c> to arrays of strings by regular expression <c>pattern</c>
        /// in case insensitive way.
        /// Returned array contains max. <c>limit</c> elements. If there is more substrings in <c>str</c>,
        /// array contains only first <c>limit-1</c> substrings and last element contains the whole rest
        /// of input <c>string</c>.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="pattern">Regular expression matching string delimiters.</param>
        /// <param name="str">String to split according to regular expression.</param>
        /// <param name="limit">Max number of elements in returned array.</param>
        /// <returns>Array of substrings.</returns>
        [Obsolete]
        public static PhpArray spliti(Context ctx, string pattern, string str, int limit = -1)
        {
            PhpException.FunctionDeprecated("spliti");

            return DoSplit(
                ctx,
                pattern,
                str,
                limit,
                limit >= 0,   // use limit (previous parameter)
                true          // ignore case
                );
        }

        /// <summary>
        /// Implementation of functions family "split"
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="pattern">POSIX regular expression that match delimiter.</param>
        /// <param name="str">String to split.</param>
        /// <param name="limit">Maximum elements of output array.</param>
        /// <param name="useLimit">True if you want to use previous parameter.</param>
        /// <param name="ignoreCase">True if <c>str</c> is matched case insensitive, false otherwise.</param>
        /// <returns>Array containing parts of str</returns>
        private static PhpArray DoSplit(Context ctx, string pattern, string str, int limit, bool useLimit, bool ignoreCase)
        {
            System.Array sAr;

            if (useLimit)
            {
                // in PHP limit < 1 means the same as 1, no error or warning is written
                if (limit < 1)
                {
                    PhpException.Throw(PhpError.Warning, LibResources.limit_less_than_one);
                    limit = 1;
                }

                // there is no static method with parameter "limit", we must instantiate Regex
                var reg = new Regex(ConvertPosix2DotNetExpr(ctx, pattern));
                sAr = reg.Split(str, limit);
            }
            else
            {
                // we can use static method
                sAr = Regex.Split(str, ConvertPosix2DotNetExpr(ctx, pattern));
            }

            return new PhpArray(sAr, 0, sAr.Length);
        }

        #endregion

        #region BracketExpression class

        /// <summary>
        /// Class representing one bracket expression ([...]) in whole regular expression.
        /// </summary>
        /// <remarks>
        /// While converting POSIX regular expression to framework regexp if we determine start
        /// of bracket expression, characters are written to this class and it controls regexp processing.
        /// Nothing is written to output while processing, results are stored in this class and the
        /// converted bracket expression is written at once after to the output.
        /// </remarks>
        internal class BracketExpression
        {
            /* vocabulary used in function naming:
			 * COUNT sth. means get some string to appropriate input (character class name, range endpoints...)
			 * UNROLL sth. means replace some parts in buffer with COUNTED string
			 * OPTIMIZE means make some change in buffer that doesn't change meaning of reg. expr.
			 */

            // string containing partially processed regular expression
            // in this string are written several parts, which substrings are which parts indicates parts array
            private StringBuilder _buffer;

            const int initialNumberOfParts = 30;
            private int[] _parts; // -1 means no part
            private PartType[] _partTypes;
            private int currentPartNumber;

            private bool negation;

            readonly Context _ctx;

            /// <summary>
            /// indicates whether or not some failure occurs
            /// </summary>
            private bool allOK;

            public enum PartType
            {
                Normal, NormalNoRangeNext, NormalBackslash, NormalBackslashNoRangeNext,
                CollatingElement, UnrolledCollatingElement,
                CharacterClass, UnrolledCharacterClass, WordBoundary,
                EquivalenceClass, UnrolledEquivalenceClass,
                Range, UnrolledRange
            };

            /// <summary>
            /// indicates if there is a part that cannot be converted to single [...] expression, for example
            /// [xyz[.abcd.]opq]. Is set to "true" in optimization if some part is marked as <c>UnrolledCollatingElement</c>
            /// or <c>UnrolledEquivalenceClass</c>
            /// </summary>
            private bool specialTranslationNeeded;

            /// <summary>
            /// Indicates that this bracket expression has '^' as the first character.
            /// </summary>
            public bool Negation
            {
                set { negation = value; }
            }

            public PartType CurrentPartType
            {
                set
                {
                    if (value == PartType.Range)
                    {
                        StartNextPart();
                        _partTypes[currentPartNumber] = value;
                        _buffer.Append('-'); // so that the part wasn't empty and we can simply convert it to PartType.Normal
                        StartNextPart();
                    }
                    else
                    {
                        _partTypes[currentPartNumber] = value;
                    }
                }
            }

            /// <summary>
            /// According to currentPartNumber part makes some changes at the end of buffer. Assumes that
            /// currentPartNumber is last in buffer.
            /// Sets allOK to false if something is wrong.
            ///
            /// BEFORE optimization there can be:
            /// Range, Normal, NormalBackslash, CharacterClass, CollatingElement, EquivalenceClass
            ///
            /// AFTER optimization there can be:
            /// Range, UnrolledRange, Normal, NormalBackslash, NormalBackslashNoRangeNext, NormalNoRangeNext,
            /// UnrolledCharacterClass, WordBoundary, UnrolledCollatingElement, UnrolledEquivalenceClass
            /// </summary>
            private void OptimizeParts()
            {
                switch (_partTypes[currentPartNumber])
                {
                    case PartType.Range:
                        OptimizeRange(); // transformed to Range or UnrolledRange
                        break;

                    case PartType.Normal:
                        OptimizeNormal();
                        break;

                    case PartType.NormalBackslash:
                        OptimizeNormalBackslash();
                        break;

                    case PartType.CharacterClass: //transformed to UnrolledCharacterClass or WordBoundary
                        OptimizeCharacterClass();
                        break;

                    case PartType.CollatingElement: // transformed to Normal, NormalBackslash or UnrolledCollatingElement
                        OptimizeCollatingElement();
                        break;

                    case PartType.EquivalenceClass:
                        OptimizeEquivalenceClass();
                        break;

                    default:
                        Debug.Fail("Unexpected part type in OptimizeParts().");
                        break;

                        /* These possibilities cannot occur here, they arise during optimization
                         * case PartType.UnrolledRange:
                         * case PartType.NormalNoRangeNext:
                         * case PartType.NormalBackslashNoRangeNext;
                         * case PartType.UnrolledCharacterClass:
                         * case PartType.WordBoundary:
                         * case PartType.UnrolledEquivalenceClass:
                        */
                }

            }

            /// <summary>
            /// Assume that currentPartNumber is set to Range and is last in buffer.
            /// According to previous part type changes types and groups some parts.
            /// Sets allOK to false if something is wrong.
            /// </summary>
            private void OptimizeRange()
            {
                if (currentPartNumber == 0)
                {
                    _partTypes[currentPartNumber] = PartType.NormalNoRangeNext; // '-' is first character in expression
                }
                else
                {
                    switch (_partTypes[currentPartNumber - 1])
                    {
                        case PartType.Range: // replace [x-y] with correct chars
                            string countedRange = CountRangeEscaped(_buffer[_parts[currentPartNumber - 2]], '-');
                            currentPartNumber = currentPartNumber - 2;
                            _parts[currentPartNumber + 1] = -1;
                            _buffer.Remove(_parts[currentPartNumber], _buffer.Length - _parts[currentPartNumber]);
                            _buffer.Append(countedRange);
                            _partTypes[currentPartNumber] = PartType.UnrolledRange;

                            break;

                        case PartType.UnrolledRange:
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("range_shared_endpoint"));
                            allOK = false;
                            break;

                        case PartType.Normal:
                            if ((_parts[currentPartNumber] - _parts[currentPartNumber - 1]) > 1)
                            // divide part in order that we have one character before range
                            {
                                // create next part, but do not optimize to avoid infinite recursive call
                                StartNextPart(false); // currentPartNumber is now greater by 1
                                _parts[currentPartNumber] = _parts[currentPartNumber - 1];
                                _partTypes[currentPartNumber] = _partTypes[currentPartNumber - 1];
                                _parts[currentPartNumber - 1]--;
                                _partTypes[currentPartNumber - 1] = PartType.Normal;
                            }
                            break;

                        case PartType.NormalBackslash:
                            break;

                        case PartType.NormalNoRangeNext:
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("range_not_allowed"));
                            allOK = false;
                            break;

                        case PartType.NormalBackslashNoRangeNext:
                            goto case PartType.NormalNoRangeNext;

                        case PartType.UnrolledCharacterClass:
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("first_endpoint_character_class"));
                            allOK = false;
                            break;

                        case PartType.WordBoundary:
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("word_boundary_not_single_bracket_expr"));
                            allOK = false;
                            break;

                        case PartType.UnrolledCollatingElement:
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("bad_collating_el_at_first_endpoint_of_range"));
                            allOK = false;
                            break;

                        case PartType.UnrolledEquivalenceClass:
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("equivalence_class_at_first_endpoint_of_range"));
                            allOK = false;
                            break;

                        default:
                            Debug.Fail("Internal error - default in OptimizeRange().");
                            break;

                    }
                }
            }

            private void OptimizeNormal()
            {
                if (currentPartNumber == 0) // if this is the first part, there is nothing to optimize
                    return;

                switch (_partTypes[currentPartNumber - 1])
                {
                    case PartType.Range:
                        string countedRange = CountRangeEscaped(_buffer[_parts[currentPartNumber - 2]], _buffer[_parts[currentPartNumber]]);
                        string normalLeft = _buffer.ToString(_parts[currentPartNumber] + 1, _buffer.Length - _parts[currentPartNumber] - 1);

                        _parts[currentPartNumber] = -1;
                        currentPartNumber = currentPartNumber - 1;
                        _buffer.Remove(_parts[currentPartNumber - 1], _buffer.Length - _parts[currentPartNumber - 1]);
                        _buffer.Append(countedRange);
                        _partTypes[currentPartNumber - 1] = PartType.UnrolledRange;
                        _parts[currentPartNumber] = _buffer.Length;
                        _buffer.Append(normalLeft);
                        _partTypes[currentPartNumber] = PartType.Normal;
                        break;

                    case PartType.WordBoundary:
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("word_boundary_not_single_bracket_expr"));
                        allOK = false;
                        break;
                }
            }

            private void OptimizeNormalBackslash()
            {
                if (currentPartNumber == 0)
                    return;

                switch (_partTypes[currentPartNumber - 1])
                {
                    case PartType.Range:
                        string countedRange = CountRangeEscaped(_buffer[_parts[currentPartNumber - 2]], '\\');
                        currentPartNumber = currentPartNumber - 2;
                        _parts[currentPartNumber + 1] = -1;
                        _buffer.Remove(_parts[currentPartNumber], _buffer.Length - _parts[currentPartNumber]);
                        _buffer.Append(countedRange);
                        _partTypes[currentPartNumber] = PartType.UnrolledRange;
                        break;

                    case PartType.WordBoundary:
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("word_boundary_not_single_bracket_expr"));
                        allOK = false;
                        break;
                }
            }

            /// <summary>
            /// Returns string containing appropriate characters for range according to current encoding. If some
            /// characters may have special meaning in the bracket expression they are escaped.
            /// Sets private variable allOK to false if secondCharacter is before firstCharacter in current encoding
            /// or the range cannot be counted for these characters.
            /// </summary>
            /// <param name="firstCharacter">First endpoint of the range.</param>
            /// <param name="secondCharacter">Second endpoint of the range.</param>
            /// <returns>String with all range characters.</returns>
            private string CountRangeEscaped(char firstCharacter, char secondCharacter)
            {
                // error indication of range conversion
                int result;
                // range characters
                string characters;

                if (CountRange(_ctx, firstCharacter, secondCharacter, out characters, out result))
                {
                    var sb = StringBuilderUtilities.Pool.Get();
                    EscapeBracketExpressionSpecialChars(sb, characters);
                    return StringBuilderUtilities.GetStringAndReturn(sb);
                }

                // there was an error
                switch (result)
                {
                    case 1:
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("ranges_not_supported"));
                        allOK = false;
                        break;
                    case 2:
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("range_first_character_greater"));
                        allOK = false;
                        break;
                    default:
                        Debug.Fail("Unexpected result error value from CountRange().");
                        break;
                }

                return null;
            }

            /// <summary>
            /// Escapes characters that have special meaning in bracket expression to make them ordinary characters.
            /// </summary>
            /// <param name="sb"><see cref="StringBuilder"/> to output the result.</param>
            /// <param name="chars">String possibly containing characters with special meaning.</param>
            /// <returns>String with escaped characters.</returns>
            internal static void EscapeBracketExpressionSpecialChars(StringBuilder/*!*/sb, string chars)
            {
                Debug.Assert(sb != null);

                for (int i = 0; i < chars.Length; i++)
                {
                    char ch = chars[i];
                    switch (ch)
                    {
                        // case '^': // not necessary, not at the beginning have no special meaning
                        case '\\':
                        case ']':
                        case '-':
                            sb.Append('\\');
                            goto default;
                        default:
                            sb.Append(ch);
                            break;
                    }
                }
            }

            /// <summary>
            /// Takes endpoints of a range and returns string containing appropriate characters.
            /// </summary>
            /// <param name="ctx">Runtime context.</param>
            /// <param name="firstCharacter">First endpoint of a range.</param>
            /// <param name="secondCharacter">Second endpoint of a range.</param>
            /// <param name="characters">String containing all characters that are to be in the range.</param>
            /// <param name="result">Integer specifying an error. Value 1 means characters specified cannot
            /// be expressed in current encoding, value of 2 first character is greater than second.</param>
            /// <returns><B>True</B> if range was successfully counted, <B>false</B> otherwise.</returns>
            internal static bool CountRange(Context ctx, char firstCharacter, char secondCharacter, out string characters, out int result)
            {
                // initialize out parameters
                characters = null;
                result = 0;

                Encoding encoding = ctx.StringEncoding; // Configuration.Application.Globalization.PageEncoding;
                char[] chars = new char[2];
                chars[0] = firstCharacter;
                chars[1] = secondCharacter;

                byte[] two_bytes = new byte[encoding.GetMaxByteCount(2)];

                // convert endpoints and test if characters are "normal" - they can be stored in one byte
                if (encoding.GetBytes(chars, 0, 2, two_bytes, 0) != 2)
                {
                    result = 1;
                    return false;
                }

                if (two_bytes[0] > two_bytes[1])
                {
                    result = 2;
                    return false;
                }

                // array for bytes that will be converted to unicode string
                byte[] bytes = new byte[two_bytes[1] - two_bytes[0] + 1];

                int i = 0;
                for (int ch = two_bytes[0]; ch <= two_bytes[1]; i++, ch++)
                {
                    // casting to byte is OK, ch is always in byte range thanks to ch <= two_bytes[1] condition
                    bytes[i] = (byte)ch;
                }

                characters = encoding.GetString(bytes, 0, i);
                return true;
            }

            /// <summary>
            /// Takes character class name and returns string containing appropriate characters.
            /// Returns <B>null</B> if has got unknown character class name.
            /// </summary>
            /// <param name="chClassName">Character class name.</param>
            /// <returns>String containing characters from character class.</returns>
            internal static string CountCharacterClass(string chClassName)
            {
                string ret = null;

                switch (chClassName)
                {
                    case "alnum":
                        ret = @"\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}";
                        break;
                    case "digit":
                        ret = @"\p{Nd}";
                        break;
                    case "punct":
                        ret = @"\p{P}\p{S}";
                        break;
                    case "alpha":
                        ret = @"\p{Ll}\p{Lu}\p{Lt}\p{Lo}";
                        break;
                    case "graph":
                        ret = @"\p{L}\p{M}\p{N}\p{P}\p{S}";
                        break;
                    case "space":
                        ret = @"\s";
                        break;
                    case "blank":
                        ret = @" \t";
                        break;
                    case "lower":
                        ret = @"\p{Ll}";
                        break;
                    case "upper":
                        ret = @"\p{Lu}";
                        break;
                    case "cntrl":
                        ret = @"\p{Cc}";
                        break;
                    case "print":
                        ret = @"\p{L}\p{M}\p{N}\p{P}\p{S}\p{Zs}";
                        break;
                    case "xdigit":
                        ret = @"abcdefABCDEF\d";
                        break;
                    case "ascii":
                        ret = @"\u0000-\u007F";
                        break;
                    case "word":
                        ret = @"_\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}";
                        break;
                }

                return ret;
            }

            /// <summary>
            /// Replaces CharacterClass name with appropriate characters and changes type to UnrolledCharacterClass.
            /// </summary>
            /// <remarks>
            /// Assumes that currentPartNumber is last part in buffer and has type CharacterClass.
            /// </remarks>
            private void OptimizeCharacterClass()
            {
                if (currentPartNumber > 0)
                {
                    if (_partTypes[currentPartNumber - 1] == PartType.Range)
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("character_class_at_second_endpoint_of_range"));
                        allOK = false;
                        return;
                    }
                    else if (_partTypes[currentPartNumber - 1] == PartType.WordBoundary)
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("word_boundary_not_single_bracket_expr"));
                        allOK = false;
                        return;
                    }
                }

                int length = _buffer.Length - _parts[currentPartNumber];
                string oldValue = _buffer.ToString(_parts[currentPartNumber], length);

                if (currentPartNumber == 0 && (oldValue == "<" || oldValue == ">"))
                {
                    _partTypes[currentPartNumber] = PartType.WordBoundary;
                    return;
                }

                string cce = CountCharacterClass(oldValue);
                if (cce == null)
                {
                    PhpException.Throw(PhpError.Warning, LibResources.GetString("unknown_character_class"));
                    allOK = false;
                    cce = "";
                }

                _partTypes[currentPartNumber] = PartType.UnrolledCharacterClass;
                _buffer.Remove(_parts[currentPartNumber], length);
                _buffer.Append(cce);
            }

            /// <summary>
            /// Takes collating element "name" (string that was enclosed in [. and .]) and returns appropriate
            /// character(s) or the original string, if there no association exist.
            /// </summary>
            /// <param name="cElement">String that was enclosed in [. and .] (collating element).</param>
            /// <returns>String associated with cElement.</returns>
            private string CountCollatingElement(string cElement)
            {
                string ret;

                switch (cElement)
                {
                    case "NUL": ret = "\x0"; break;
                    case "SOH": ret = "\x1"; break;
                    case "STX": ret = "\x2"; break;
                    case "ETX": ret = "\x3"; break;
                    case "EOT": ret = "\x4"; break;
                    case "ENQ": ret = "\x5"; break;
                    case "ACK": ret = "\x6"; break;
                    case "BEL": ret = "\x7"; break;
                    case "alert": ret = "\x7"; break;
                    case "BS": ret = "\x8"; break;
                    case "backspace": ret = "\b"; break;
                    case "HT": ret = "\x9"; break;
                    case "tab": ret = "\t"; break;
                    case "LF": ret = "\xa"; break;
                    case "newline": ret = "\n"; break;
                    case "VT": ret = "\xb"; break;
                    case "vertical-tab": ret = "\v"; break;
                    case "FF": ret = "\xc"; break;
                    case "form-feed": ret = "\f"; break;
                    case "CR": ret = "\xd"; break;
                    case "carriage-return": ret = "\r"; break;
                    case "SO": ret = "\xe"; break;
                    case "SI": ret = "\xf"; break;
                    case "DLE": ret = "\x10"; break;
                    case "DC1": ret = "\x11"; break;
                    case "DC2": ret = "\x12"; break;
                    case "DC3": ret = "\x13"; break;
                    case "DC4": ret = "\x14"; break;
                    case "NAK": ret = "\x15"; break;
                    case "SYN": ret = "\x16"; break;
                    case "ETB": ret = "\x17"; break;
                    case "CAN": ret = "\x18"; break;
                    case "EM": ret = "\x19"; break;
                    case "SUB": ret = "\x1a"; break;
                    case "ESC": ret = "\x1b"; break;
                    case "IS4": ret = "\x1c"; break;
                    case "FS": ret = "\x1c"; break;
                    case "IS3": ret = "\x1d"; break;
                    case "GS": ret = "\x1d"; break;
                    case "IS2": ret = "\x1e"; break;
                    case "RS": ret = "\x1e"; break;
                    case "IS1": ret = "\x1f"; break;
                    case "US": ret = "\x1f"; break;
                    case "space": ret = " "; break;
                    case "exclamation-mark": ret = "!"; break;
                    case "quotation-mark": ret = "\""; break;
                    case "number-sign": ret = "#"; break;
                    case "dollar-sign": ret = "$"; break;
                    case "percent-sign": ret = "%"; break;
                    case "ampersand": ret = "&"; break;
                    case "apostrophe": ret = "\'"; break;
                    case "left-parenthesis": ret = "("; break;
                    case "right-parenthesis": ret = ")"; break;
                    case "asterisk": ret = "*"; break;
                    case "plus-sign": ret = "+"; break;
                    case "comma": ret = ","; break;
                    case "hyphen": ret = "-"; break;
                    case "hyphen-minus": ret = "-"; break;
                    case "period": ret = "."; break;
                    case "full-stop": ret = "."; break;
                    case "slash": ret = "/"; break;
                    case "solidus": ret = "/"; break;
                    case "zero": ret = "0"; break;
                    case "one": ret = "1"; break;
                    case "two": ret = "2"; break;
                    case "three": ret = "3"; break;
                    case "four": ret = "4"; break;
                    case "five": ret = "5"; break;
                    case "six": ret = "6"; break;
                    case "seven": ret = "7"; break;
                    case "eight": ret = "8"; break;
                    case "nine": ret = "9"; break;
                    case "colon": ret = ":"; break;
                    case "semicolon": ret = ";"; break;
                    case "less-than-sign": ret = "<"; break;
                    case "equals-sign": ret = "="; break;
                    case "greater-than-sign": ret = ">"; break;
                    case "question-mark": ret = "?"; break;
                    case "commercial-at": ret = "@"; break;
                    case "left-square-bracket": ret = "["; break;
                    case "backslash": ret = "\\"; break;
                    case "reverse-solidus": ret = "\\"; break;
                    case "right-square-bracket": ret = "]"; break;
                    case "circumflex": ret = "^"; break;
                    case "circumflex-accent": ret = "^"; break;
                    case "underscore": ret = "_"; break;
                    case "low-line": ret = "_"; break;
                    case "grave-accent": ret = "`"; break;
                    case "left-brace": ret = "{"; break;
                    case "left-curly-bracket": ret = "{"; break;
                    case "vertical-line": ret = "|"; break;
                    case "right-brace": ret = "}"; break;
                    case "right-curly-bracket": ret = "}"; break;
                    case "tilde": ret = "~"; break;
                    case "DEL": ret = "\x7f"; break;
                    case "NULL": ret = "\x0"; break;
                    default:
                        ret = cElement;
                        break;
                }
                return ret;
            }

            /// <summary>
            /// Assumes that currentPartNumber is last part in buffer and has type CollatingElement.
            /// Changes it to Normal, NormalBackslash or UnrolledCollatingElement.
            /// </summary>
            private void OptimizeCollatingElement()
            {
                if (currentPartNumber > 0 && (_partTypes[currentPartNumber - 1] == PartType.WordBoundary))
                {
                    PhpException.Throw(PhpError.Warning, LibResources.GetString("word_boundary_not_single_bracket_expr"));
                    allOK = false;
                    return;
                }
                int length = _buffer.Length - _parts[currentPartNumber];
                string cce = CountCollatingElement(_buffer.ToString(_parts[currentPartNumber], length));
                _buffer.Remove(_parts[currentPartNumber], length);
                _buffer.Append(cce);

                if (cce.Length == 1)
                {
                    _partTypes[currentPartNumber] = PartType.Normal;
                    OptimizeNormal();
                }
                else if (cce == @"\\")
                {
                    cce = @"\";
                    _partTypes[currentPartNumber] = PartType.NormalBackslash;
                    OptimizeNormalBackslash();
                }
                else
                {
                    _partTypes[currentPartNumber] = PartType.UnrolledCollatingElement;
                    specialTranslationNeeded = true;
                }
            }

            /// <summary>
            /// Calls OptimizeCollatingElement() and sets current part type to UnrolledEquivalenceClass.
            /// </summary>
            private void OptimizeEquivalenceClass()
            {
                if (currentPartNumber > 0)
                {
                    if (_partTypes[currentPartNumber - 1] == PartType.Range)
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("equivalence_class_at_second_endpoint_of_range"));
                        allOK = false;
                        return;
                    }
                    else if (_partTypes[currentPartNumber - 1] == PartType.WordBoundary)
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("word_boundary_not_single_bracket_expr"));
                        allOK = false;
                        return;
                    }
                }

                // we have no equivalence classes defined, so [= =] is the same as [. .] according to specification
                OptimizeCollatingElement();

                switch (_partTypes[currentPartNumber])
                {
                    case PartType.UnrolledCollatingElement:
                        _partTypes[currentPartNumber] = PartType.UnrolledEquivalenceClass;
                        break;
                    case PartType.Normal:
                        _partTypes[currentPartNumber] = PartType.NormalNoRangeNext;
                        break;
                    case PartType.NormalBackslash:
                        _partTypes[currentPartNumber] = PartType.NormalBackslashNoRangeNext;
                        break;
                }
            }

            /// <summary>
            /// If something was written to current part, creates next empty part.
            /// </summary>
            /// <remarks>
            /// Important to easy automaton implementation: if current part is empty, does nothing!
            /// Appending new parts is unlimited, arrays are enlarged if needed.
            /// </remarks>
            public bool StartNextPart()
            {
                return StartNextPart(true);
            }

            /// <summary>
            /// If something was written to current part, creates next empty part.
            /// </summary>
            /// <remarks>
            /// Important to easy automaton implementation: if current part is empty, does nothing!
            /// Appending new parts is unlimited, arrays are enlarged if needed.
            /// </remarks>
            /// <param name="optimize">Whether call OptimizeParts().</param>
            /// <returns>True if everything is OK.</returns>
            private bool StartNextPart(bool optimize)
            {
                if (!allOK)
                    return false;

                if (_parts[currentPartNumber] == _buffer.Length)
                    // we don't need to make new part, current part is empty
                    return true;

                if (optimize)
                    OptimizeParts();

                currentPartNumber++;
                if (currentPartNumber == _parts.Length) // array is full, enlarge it
                {
                    int[] tempArray = _parts;
                    _parts = new int[_parts.Length * 2];
                    System.Array.Copy(tempArray, _parts, tempArray.Length);

                    PartType[] tempArray2 = _partTypes;
                    _partTypes = new PartType[_parts.Length * 2];
                    System.Array.Copy(tempArray2, _partTypes, tempArray2.Length);
                }

                _parts[currentPartNumber] = _buffer.Length; // set position after last character in buffer
                _partTypes[currentPartNumber] = PartType.Normal;
                _parts[currentPartNumber + 1] = -1;

                return true;
            }

            /// <summary>
            /// Constructor. Sets all fields to appropriate empty values.
            /// </summary>
            public BracketExpression(Context ctx)
            {
                _ctx = ctx;

                _buffer = new StringBuilder();
                _parts = new int[initialNumberOfParts];
                _partTypes = new PartType[initialNumberOfParts];

                Reset();
            }

            /// <summary>
            /// Sets inner state as if the object was created.
            /// </summary>
            public void Reset()
            {
                _buffer.Remove(0, _buffer.Length);
                currentPartNumber = 0;

                _parts[0] = 0;
                _parts[1] = -1;
                _partTypes[0] = PartType.Normal;
                // if these arrays were enlarged, we keep the same lenght, shortening is pointless

                negation = false;
                allOK = true;
                specialTranslationNeeded = false;
            }

            /// <summary>
            /// Appends one character to current part of bracket expression.
            /// </summary>
            /// <param name="ch">Character to append.</param>
            public void Append(char ch)
            {
                _buffer.Append(ch);
            }

            /// <summary>
            /// Appends two characters to current part of bracket expression.
            /// </summary>
            /// <param name="ch1">First character to append.</param>
            /// <param name="ch2">Second character to append.</param>
            public void Append(char ch1, char ch2)
            {
                _buffer.Append(ch1);
                _buffer.Append(ch2);
            }

            /// <summary>
            /// Appends three characters to current part of bracket expression.
            /// </summary>
            /// <param name="ch1">First character to append.</param>
            /// <param name="ch2">Second character to append.</param>
            /// <param name="ch3">Third character to append.</param>
            public void Append(char ch1, char ch2, char ch3)
            {
                _buffer.Append(ch1);
                _buffer.Append(ch2);
                _buffer.Append(ch3);
            }

            /// <summary>
            ///
            /// </summary>
            /// <param name="output"></param>
            private void WriteOutNoSpecial(ref StringBuilder output)
            {
                for (int i = 0; i < currentPartNumber; i++)
                {
                    if (_partTypes[i] == PartType.NormalBackslash || _partTypes[i] == PartType.NormalBackslashNoRangeNext)
                        output.Append(@"\");
                    else
                        output.Append(_buffer.ToString(_parts[i], _parts[i + 1] - _parts[i]));
                }

                // last iteration - we count part length otherwise
                if (_partTypes[currentPartNumber] == PartType.NormalBackslash
                  || _partTypes[currentPartNumber] == PartType.NormalBackslashNoRangeNext)
                    output.Append(@"\\");
                else
                    output.Append(_buffer.ToString(_parts[currentPartNumber], _buffer.Length - _parts[currentPartNumber]));
            }

            /// <summary>
            ///
            /// </summary>
            /// <param name="output"></param>
            private void WriteOutSpecial(ref StringBuilder output)
            {
                int length;

                for (int i = 0; i <= currentPartNumber; i++)
                {
                    if (i == currentPartNumber)
                        length = _buffer.Length - _parts[i];
                    else
                        length = _parts[i + 1] - _parts[i];

                    switch (_partTypes[i])
                    {
                        case PartType.Normal:
                            output.Append('[');
                            output.Append(_buffer.ToString(_parts[i], length));
                            output.Append(']');
                            break;
                        case PartType.Range: // can be only last part
                            Debug.Assert(i != currentPartNumber, "internal error WriteOutSpecial() Range isn't last.");
                            goto case PartType.Normal;
                        case PartType.UnrolledRange:
                            goto case PartType.Normal;
                        case PartType.NormalBackslash:
                            output.Append(@"[\\]");
                            break;
                        case PartType.NormalBackslashNoRangeNext:
                            goto case PartType.NormalBackslash;
                        case PartType.NormalNoRangeNext:
                            goto case PartType.Normal;
                        case PartType.UnrolledCharacterClass:
                            goto case PartType.Normal;
                        case PartType.WordBoundary:
                            Debug.Fail("internal error WriteOutSpecial() Word boundary.");
                            break;
                        case PartType.UnrolledCollatingElement:
                            output.Append(_buffer.ToString(_parts[i], length));
                            break;
                        case PartType.UnrolledEquivalenceClass:
                            goto case PartType.UnrolledCollatingElement;
                    }
                    output.Append('|');
                } // for()

                output.Remove(output.Length - 1, 1); // remove last '|' character
            }

            /// <summary>
            /// Writes to <c>output</c> Framework regular expression for beginning or end of word,
            /// according to first part in <c>parts</c> array.
            /// </summary>
            /// <param name="output"><c>StringBuilder</c> to write out.</param>
            private void WriteOutWordBoundary(ref StringBuilder output)
            {
                if (_buffer[_parts[0]] == '<')
                {   // beginning of word
                    output.Append(@"\b(?=\w)");
                }
                else
                {   // end of word
                    output.Append(@"\b(?<=\w)");
                }
            }

            /// <summary>
            /// Compose all parts and creates .NET Framework compatible regular expression.
            /// </summary>
            /// <returns>.NET Framework compatible regular expression</returns>
            public bool WriteOut(ref StringBuilder retString)
            {
                // some failure occured, nothing is written
                if (!allOK)
                    return false;

                // creates new empty part - causes optimization of previous part (the last one, that was not optimized,
                // previous parts were optimized while calling StartNextPart()).
                StartNextPart();

                StringBuilder output = new StringBuilder(2 * _buffer.Length); // estimated indigent length

                if (_partTypes[0] == PartType.WordBoundary)
                {
                    // writes word boundary and ends, if it is word boundary, nothing can follow
                    WriteOutWordBoundary(ref output);
                }
                else if (!specialTranslationNeeded)
                {
                    // regular expression can be written to single framework bracket expression [..]
                    output.Append('[');

                    if (negation)
                        output.Append('^');
                    WriteOutNoSpecial(ref output);

                    output.Append(']');
                }
                else
                {
                    // regular expression cannot be written to single framework expression,
                    // we enclose whole expression to (? .. ) parentheses and inside can be more
                    // complicated expression that match one single POSIX bracket expression
                    if (negation)
                    {
                        output.Append("(?(");
                        WriteOutSpecial(ref output);
                        output.Append(@")\b\B|.)"); // \b\B always fails
                    }
                    else
                    {
                        output.Append("(?:");
                        WriteOutSpecial(ref output);
                        output.Append(')');
                    }
                }

                retString.Append(output.ToString());
                return allOK;
            }
        }// class BracketExpression

        #endregion

        #region Regular expression conversion functions

        /// <summary>
        /// <c>CharMap</c> containing characters that must be prepended by '\'.
        /// </summary>
        private static readonly CharMap controlCharsMap = new CharMap(new uint[] { 0x0, 0x8f20001, 0x1a, 0x18 });

        /// <summary>
        /// Converts POSIX regular expression to .NET Framework regular expression
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="expr">POSIX 1003.2 regular expression</param>
        /// <returns>.NET Framework compatible regular expression</returns>
        // WORKING: change to private!
        private static string ConvertPosix2DotNetExpr(Context ctx, string expr)
        {
            if (expr == null) return "";

            // number that is not used in automaton
            const int errorState = 99;

            // 0 == initial state
            int state = 0;

            // iterator for iterating in strings
            var ch = ((IEnumerable<char>)expr).GetEnumerator();
            // true if we are at the end of bracket expression
            bool eOfExpr = false;

            // true if we have read next character and this character is not applicable for current state,
            // we change state with lambda step and there is character scanned again
            // true if we are changing state and the character should be scanned again
            bool lambdaStep = false;

            // into this StringBuilder is converted regular expression written
            // 2*expr.Length is estimated necessary length of output string
            StringBuilder output = new StringBuilder(2 * expr.Length);

            // bracket expressions are very complicated, we have made separate class for managing them
            // if we need to create bracket expression class instance, we store it in this variable
            // and reuse it after Reset() call
            BracketExpression be = null;

            eOfExpr = !ch.MoveNext();
            while (!eOfExpr)
            {
                switch (state)
                {
                    case 0: // initial state
                        switch (ch.Current)
                        {
                            case '\\':
                                state = 1;
                                break;

                            case '[':
                                state = 2;
                                if (be != null) // bracket expr. already exists, reset it only
                                    be.Reset();
                                else
                                    be = new BracketExpression(ctx);
                                break;

                            case '(':
                                state = 15;
                                break;

                            default:
                                output.Append(ch.Current);
                                break;
                        }
                        break;

                    case 1:
                        if (controlCharsMap.Contains(ch.Current))
                        {   // control character - must be preppended by '\'
                            output.Append('\\');
                        }

                        output.Append(ch.Current);
                        state = 0;
                        break;

                    case 2:
                        switch (ch.Current)
                        {
                            case '^':
                                be.Negation = true;
                                state = 3;
                                break;

                            case ']':
                                be.Append(']');
                                state = 4;
                                break;

                            default:
                                lambdaStep = true;
                                state = 4;
                                break;
                        }
                        break;

                    case 3:
                        if (ch.Current == ']')
                            be.Append(']');
                        else
                            lambdaStep = true;

                        state = 4;
                        break;

                    case 4:
                        switch (ch.Current)
                        {
                            case '[':
                                state = 5;
                                break;

                            case '\\':
                                be.StartNextPart();
                                be.Append('\\');
                                be.CurrentPartType = BracketExpression.PartType.NormalBackslash;
                                be.StartNextPart();
                                break;

                            case ']':
                                state = 0;
                                if (!be.WriteOut(ref output))
                                    state = errorState;
                                break;

                            case '-':
                                be.CurrentPartType = BracketExpression.PartType.Range;
                                break;

                            default:
                                be.Append(ch.Current);
                                break;
                        }
                        break;

                    case 5:
                        switch (ch.Current)
                        {
                            case '.':
                                be.StartNextPart();
                                be.CurrentPartType = BracketExpression.PartType.CollatingElement;
                                state = 6;
                                break;

                            case ':':
                                be.StartNextPart();
                                be.CurrentPartType = BracketExpression.PartType.CharacterClass;
                                state = 7;
                                break;

                            case '=':
                                be.StartNextPart();
                                be.CurrentPartType = BracketExpression.PartType.EquivalenceClass;
                                state = 8;
                                break;

                            case '\\':
                                be.Append('\\', '\\');
                                state = 4;
                                break;
                            default:

                                be.Append('[', ch.Current);
                                state = 4;
                                break;
                        }
                        break;

                    case 6:
                        if (ch.Current == '\\')
                            be.Append('\\', '\\');
                        else
                            be.Append(ch.Current);
                        state = 9;
                        break;

                    case 7:
                        if (ch.Current == '\\')
                            be.Append('\\', '\\');
                        else
                            be.Append(ch.Current);
                        state = 10;
                        break;

                    case 8:
                        if (ch.Current == '\\')
                            be.Append('\\', '\\');
                        else
                            be.Append(ch.Current);
                        state = 11;
                        break;

                    case 9:
                        switch (ch.Current)
                        {
                            case '\\':
                                be.Append('\\', '\\');
                                break;

                            case '.':
                                state = 12;
                                break;

                            default:
                                be.Append(ch.Current);
                                break;
                        }
                        break;

                    case 10:
                        switch (ch.Current)
                        {
                            case '\\':
                                be.Append('\\', '\\');
                                break;

                            case ':':
                                state = 13;
                                break;

                            default:
                                be.Append(ch.Current);
                                break;
                        }
                        break;

                    case 11:
                        switch (ch.Current)
                        {
                            case '\\':
                                be.Append('\\', '\\');
                                break;

                            case '=':
                                state = 14;
                                break;

                            default:
                                be.Append(ch.Current);
                                break;
                        }
                        break;

                    case 12:
                        switch (ch.Current)
                        {
                            case ']':
                                be.StartNextPart();
                                state = 4;
                                break;

                            case '\\':
                                be.Append('.', '\\', '\\');
                                state = 9;
                                break;

                            default:
                                be.Append('.', ch.Current);
                                state = 9;
                                break;
                        }
                        break;

                    case 13:
                        switch (ch.Current)
                        {
                            case ']':
                                be.StartNextPart();
                                state = 4;
                                break;

                            case '\\':
                                be.Append(':', '\\', '\\');
                                state = 10;
                                break;

                            default:
                                be.Append(':', ch.Current);
                                state = 10;
                                break;
                        }
                        break;

                    case 14:
                        switch (ch.Current)
                        {
                            case ']':
                                be.StartNextPart();
                                state = 4;
                                break;

                            case '\\':
                                be.Append('=', '\\', '\\');
                                state = 11;
                                break;

                            default:
                                be.Append('=', ch.Current);
                                state = 11;
                                break;
                        }
                        break;

                    case 15:
                        switch (ch.Current)
                        {
                            case '?':
                                PhpException.Throw(PhpError.Warning, LibResources.question_mark_folowing_nothing);
                                state = errorState;
                                break;

                            default:
                                output.Append('(');
                                output.Append(ch.Current);
                                state = 0;
                                break;
                        }
                        break;

                    default: // catch the ErrorState
                        eOfExpr = true;
                        output.Remove(0, output.Length);
                        break;
                }

                // we can eliminate this, but without lambda steps will be an automaton much more complicated
                // other solution is calling ch.MoveNext() in each case statement, this would bring error liability
                // but can save a few instructions in each iteration
                if (!eOfExpr && !lambdaStep)
                    eOfExpr = !ch.MoveNext();

                lambdaStep = false;
            }

            // check where an automaton has finished
            switch (state)
            {
                case 0:
                    return output.ToString();

                case 1:
                    PhpException.Throw(PhpError.Warning, LibResources.regexp_cannot_end_with_two_backslashes);
                    return null;

                case 15:
                    PhpException.Throw(PhpError.Warning, LibResources.regexp_cannot_end_with_open_bracket);
                    return null;

                default:
                    PhpException.Throw(PhpError.Warning, LibResources.unenclosed_bracket_expression);
                    return null;
            }
        }

        /// <summary>
        /// Converts string that represents replacement and can be used with regular expression and
        /// contain references to parenthesized substrings in that regular expression.
        /// </summary>
        /// <param name="replacement">String to convert</param>
        /// <param name="substrNumbers">Array containig numbers of parenthesized substrings in matching regular expression.</param>
        /// <returns>Converted .NET Framework compatible regular expression to replacement.</returns>
        private static string ConvertPosix2DotNetRepl(string replacement, int[] substrNumbers)
        {
            if (replacement == null) return "";

            int state = 0;
            StringBuilder output = new StringBuilder((int)(replacement.Length * 1.5));

            foreach (char ch in replacement)
            {
                switch (state)
                {
                    case 0:
                        switch (ch)
                        {
                            case '\\':
                                state = 1;
                                break;

                            case '$':
                                // 'normal' dollar must be doubled to prevent back reference meaning
                                output.Append("$$");
                                break;

                            default:
                                output.Append(ch);
                                break;
                        }
                        break;

                    case 1:
                        state = 0; // always return to state 0
                        if (ch == '$')
                        {
                            // 'normal' dollar must be doubled to prevent back reference meaning
                            output.Append("\\$$");
                        }
                        else if (ch >= '0' && ch <= '9')
                        {
                            // back reference number 0 .. 9

                            // write back reference only if exists
                            if (((System.Collections.IList)substrNumbers).Contains(Int32.Parse(ch.ToString())))
                                output.Append('$');
                            else
                                output.Append('\\');

                            output.Append(ch);
                        }
                        else
                        {
                            // other characters - leave unchanged
                            output.Append('\\');
                            output.Append(ch);
                        }
                        break;
                }
            }

            if (state == 1)
                output.Append('\\');

            return output.ToString();
        }

        #endregion
    }
}


text:
<!doctype html>
<!-- Copyright (c) 2014 Google Inc. All rights reserved. -->
<html>
<head>

  <script src="../platform/platform.js"></script>
  <link rel="import" href="../core-component-page/core-component-page.html">

</head>
<body unresolved>

  <core-component-page></core-component-page>

</body>
</html>


text:
/*
 * contrasttest.c
 *
 *   This appplies @factor contrast enhancement to the input image.
 *   It also plots atan curves for different width parameters.
 */

#include <math.h>
#include "allheaders.h"

int main(int    argc,
         char **argv)
{
char        *filein, *fileout;
char         buf[512];
l_int32      iplot;
l_float32    factor;    /* scaled width of atan curve */
l_float32    fact[] = {0.2f, 0.4f, 0.6f, 0.8f, 1.0f, -1.0f};
GPLOT       *gplot;
NUMA        *na, *nax;
PIX         *pixs;
static char  mainName[] = "contrasttest";

    if (argc != 4)
        return ERROR_INT(" Syntax:  contrasttest filein factor fileout",
               mainName, 1);
    filein = argv[1];
    factor = atof(argv[2]);
    fileout = argv[3];

    setLeptDebugOK(1);
    lept_mkdir("lept/contrast");

    if ((pixs = pixRead(filein)) == NULL)
        return ERROR_INT("pixs not made", mainName, 1);

    na = numaContrastTRC(factor);
    gplotSimple1(na, GPLOT_PNG, "/tmp/lept/contrast/trc1", "contrast trc");
    l_fileDisplay("/tmp/lept/contrast/trc1.png", 0, 100, 1.0);
    numaDestroy(&na);

         /* Plot contrast TRC maps */
    nax = numaMakeSequence(0.0, 1.0, 256);
    gplot = gplotCreate("/tmp/lept/contrast/trc2", GPLOT_PNG,
        "Atan mapping function for contrast enhancement",
        "value in", "value out");
    for (iplot = 0; fact[iplot] >= 0.0; iplot++) {
        na = numaContrastTRC(fact[iplot]);
        snprintf(buf, sizeof(buf), "factor = %3.1f", fact[iplot]);
        gplotAddPlot(gplot, nax, na, GPLOT_LINES, buf);
        numaDestroy(&na);
    }
    gplotMakeOutput(gplot);
    gplotDestroy(&gplot);
    l_fileDisplay("/tmp/lept/contrast/trc2.png", 600, 100, 1.0);
    numaDestroy(&nax);

        /* Apply the input contrast enhancement */
    pixContrastTRC(pixs, pixs, factor);
    pixWrite(fileout, pixs, IFF_PNG);
    pixDestroy(&pixs);
    return 0;
}


text:
package com.twitter.finagle.http.filter

import com.twitter.finagle._
import com.twitter.finagle.http.{Response, Request, Status}
import com.twitter.finagle.service.RetryPolicy
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.io.Buf
import com.twitter.util.Future

/**
 * When a server fails with retryable failures, it sends back a
 * `NackResponse`, i.e. a 503 response code with "finagle-http-nack"
 * header.
 *
 * Clients who recognize the header convert the response to a
 * restartable failure, which can be retried. Clients who don't
 * recognize the header treat the response the same way as other
 * 503 response.
 */
private[finagle] object HttpNackFilter {
  val role: Stack.Role = Stack.Role("HttpNack")

  val Header: String = "finagle-http-nack"
  val ResponseStatus: Status = Status.ServiceUnavailable

  private val NackResponse: Response = {
    val rep = Response(ResponseStatus)
    rep.headers.set(Header, "true")
    rep.content = Buf.Utf8("Request was not processed by the server due to an error and is safe to retry")
    rep
  }

  def isNack(rep: Response): Boolean =
    rep.status == ResponseStatus && rep.headerMap.contains(Header)

  def module: Stackable[ServiceFactory[Request, Response]] =
    new Stack.Module1[param.Stats,ServiceFactory[Request, Response]] {
      val role = HttpNackFilter.role
      val description = "Return 503 http response upon retryable failures"

      def make(_stats: param.Stats, next: ServiceFactory[Request, Response]) = {
        val param.Stats(stats) = _stats
        (new HttpNackFilter(stats)).andThen(next)
      }
    }
}

private[finagle] class HttpNackFilter(statsReceiver: StatsReceiver)
  extends SimpleFilter[Request, Response] {
  import HttpNackFilter._

  private[this] val nackCounts = statsReceiver.counter("nacks")

  def apply(request: Request, service: Service[Request, Response]): Future[Response] = {
    service(request).handle {
      case RetryPolicy.RetryableWriteException(_) =>
        nackCounts.incr()
        NackResponse
    }
  }
}


text:
def main():
    '''
    ansible oc module for approving certificate signing requests
    '''

    module = AnsibleModule(
        argument_spec=dict(
            kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
            state=dict(default='approve', type='str',
                       choices=['approve', 'deny', 'list']),
            debug=dict(default=False, type='bool'),
            nodes=dict(default=None, type='list'),
            timeout=dict(default=30, type='int'),
            approve_all=dict(default=False, type='bool'),
            service_account=dict(default='system:serviceaccount:openshift-infra:node-bootstrapper', type='str'),
            fail_on_timeout=dict(default=False, type='bool'),
        ),
        supports_check_mode=True,
        mutually_exclusive=[['approve_all', 'nodes']],
    )

    if module.params['nodes'] == []:
        module.fail_json(**dict(failed=True, msg='Please specify hosts.'))

    rval = OCcsr.run_ansible(module.params, module.check_mode)

    # If we timed out then we weren't finished. Fail if user requested to fail.
    if (module.params['timeout'] > 0 and
            module.params['fail_on_timeout'] and
            rval['timeout']):
        return module.fail_json(msg='Timed out accepting certificate signing requests. Failing as requested.', **rval)

    if 'failed' in rval:
        return module.fail_json(**rval)

    return module.exit_json(**rval)

if __name__ == '__main__':
    main()


text:
using System;

namespace SummerCamp.WaterStock.Services.Areas.HelpPage.ModelDescriptions
{
    public class ParameterAnnotation
    {
        public Attribute AnnotationAttribute { get; set; }

        public string Documentation { get; set; }
    }
}


text:
require "minitest/autorun"
require "mocha/minitest"
require "annotate_gem"
require "pry"

module TestHelpers

  def gemfile_path
    File.join(File.dirname(__FILE__), "fixtures", "Gemfile")
  end

  def annotated_gemfile_path
    File.join(File.dirname(__FILE__), "fixtures", "Gemfile_annotated")
  end

  def with_gemfile(content)
    file = Tempfile.new('gemfile')
    file.write(content)
    file.close
    yield(file.path)
    file.unlink
  end

  def unindent(str)
    str.gsub(/^#{str.scan(/^[ ]+(?=\S)/).min}/, "")
  end

end

class Minitest::Test
  include TestHelpers
end


text:
package com.intellij.notification;

import com.intellij.openapi.extensions.ExtensionPointName;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

/**
 * @author gregsh
 */
public abstract class EventLogCategory {
  public static final ExtensionPointName<EventLogCategory> EP_NAME = ExtensionPointName.create("com.intellij.eventLogCategory");

  private final @Nls String myDisplayName;

  protected EventLogCategory(@NotNull @Nls String displayName) {
    myDisplayName = displayName;
  }

  @NotNull
  @Nls
  public final String getDisplayName() {
    return myDisplayName;
  }

  public abstract boolean acceptsNotification(@NotNull String groupId);
}


text:
title: 'I have seen the Futurama'
published: true
date: '08-02-2004 00:00'
taxonomy:
    category:
        - blog
    tag:
        - General
process:
    markdown: true
child_type: default
routable: true
cache_enable: true
visible: true
header_image: '0'
summary:
    enabled: '1'
    format: short
---

![Petronas by night](Petronas.png) {.center}

From the 26th floor of the Dynasty Hotel one has a pretty good view of the Kuala Lumpur skyline, and what it looks most like is a scene from the Dan Dare comics of my youth. All that's missing are the personal space vehicles zipping overhead. And the one-eyed babes in purple.


text:
package com.breakidea.noah.dao;

import java.util.Map;

public interface MonitorDao {

    public void insert(Map<String, Object> param);

}


text:
/**************************     REVISION HISTORY    **************************
 * 07/09/2014 - Minh Duc Cao: Created
 *
 ****************************************************************************/

package japsa.bio.hts;

import japsa.bio.np.MultinomialCI;
import japsa.seq.SequenceReader;
import japsa.util.DoubleArray;

import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author minhduc
 *
 */
public class SpeciesCoverageIdenfication {
	private static final Logger LOG = LoggerFactory.getLogger(SpeciesCoverageIdenfication.class);

	private double qual = 0;
	private MultinomialCI rengine;

	private int currentReadCount = 0;
	private int currentReadAligned = 0;
	//private long currentBaseCount = 0;
	//private long currentBaseAligned= 0;

	//int arrayIndex = 0;
	//String prefix;

	//public SequenceOutputStream countsOS;
	private PrintStream outOS;

	public SpeciesCoverageIdenfication(String outputFile, double minQual) throws IOException{

		rengine = new MultinomialCI(0.05);

		//countsOS = SequenceOutputStream.makeOutputStream(outputFile);
		if (outputFile.equals("-"))
			outOS = System.out;
		else
			outOS = new PrintStream (new FileOutputStream(outputFile));

		this.qual = minQual;
	}

	public void close() throws IOException{
		outOS.close();
		//rengine.end();
	}

	static class SpeciesCount implements Comparable<SpeciesCount>{
		String species;
		int count = 0;

		SpeciesCount (String s){
			species = s;
		}

		/* (non-Javadoc)
		 * @see java.lang.Comparable#compareTo(java.lang.Object)
		 */
		@Override
		public int compareTo(SpeciesCount o) {
			return o.count - count;
		}

	}

	HashMap<String, String> seq2Species = new HashMap<String, String>();
	HashMap<String, SpeciesCount> species2Count = new HashMap<String, SpeciesCount>();
	ArrayList<String> speciesList = new ArrayList<String>();

	public void preTyping(String indexFile)throws IOException{
		BufferedReader bf = SequenceReader.openFile(indexFile);
		String line = "";
		while ( (line = bf.readLine())!=null){
			if (line.startsWith("#"))
				continue;

			String [] toks = line.split(" ");
			String sp =  toks[0];
			String seq = toks[1].substring(1);

			if (seq2Species.put(seq, sp) != null)
				throw new RuntimeException("sequence " + seq +" presents multiple time");

			if (species2Count.get(sp) == null){
				species2Count.put(sp,new SpeciesCount(sp));
			}
		}//while
		bf.close();
		LOG.info(seq2Species.size() + "   " + species2Count.size());
		speciesList.addAll(species2Count.keySet());

		//Write header
		outOS.println("Species\tProportion\tError\tRead Count\tTotal Reads Aligned\tTotal Reads");
		//for (String species:speciesList){
		//	countsOS.print("\t" + species);
		//}
		//countsOS.println();
	}

	private void simpleAnalysisCurrent() throws IOException{

		int sum = 0;
		double [] count = new double[speciesList.size()];
		for (int i = 0; i < count.length;i++){
			count[i] = species2Count.get(speciesList.get(i)).count;
			sum += count[i];
		}
		DoubleArray countArray = new DoubleArray();
		ArrayList<String> speciesArray = new ArrayList<String> ();

		int minCount = Math.max(1,sum/50);

		for (int i = 0; i < count.length;i++){
			if (count[i] >= minCount){
				countArray.add(count[i]);
				speciesArray.add(speciesList.get(i));
			}
		}

		countArray.add(1);
		speciesArray.add("others");

		rengine.assignCount(countArray.toArray());
		rengine.eval();
	//	REXP tab  = rengine.eval("tab",true);
		double [][] results = rengine.tab();

		for (int i = 0; i < results.length;i++){
			if (results[i][0] <= 0.00001)
				continue;

			double mid = (results[i][0] + results[i][1])/2;
			double err = mid - results[i][0];

			//Species
			outOS.printf("%s\t%.4f\t%.4f\t%d\t%d\t%d\n", speciesArray.get(i).replaceAll("_"," "), mid, err, (int) countArray.get(i),currentReadAligned, currentReadCount);

		}
		outOS.flush();
		//LOG.info(step+"  " + countArray.size());
	}

	public void typing(String bamFile) throws IOException, InterruptedException{

		//Read the bam file
		SamReaderFactory.setDefaultValidationStringency(ValidationStringency.SILENT);
		SamReader samReader;
		if ("-".equals(bamFile))
			samReader = SamReaderFactory.makeDefault().open(SamInputResource.of(System.in));
		else
			samReader = SamReaderFactory.makeDefault().open(new File(bamFile));

		SAMRecordIterator samIter = samReader.iterator();

		while (samIter.hasNext()){
			SAMRecord sam = samIter.next();
			currentReadCount ++;

			//int readLength = sam.getReadLength();
			//currentBaseCount += readLength;

			if (sam.getReadUnmappedFlag()){
				continue;
			}

			if (sam.getMappingQuality() < this.qual)
				continue;

			currentReadAligned ++;
			//currentBaseAligned  += readLength;

			String refSequence = sam.getReferenceName();
			String species = seq2Species.get(refSequence);
			if (species == null){
				throw new RuntimeException(" Can find species with ref " + refSequence + " line " + currentReadCount );
			}
			SpeciesCount sCount = species2Count.get(species);
			if (sCount == null){
				throw new RuntimeException(" Can find record with species " + species + " line " + currentReadCount );
			}
			sCount.count ++;

		}

		//final run
		simpleAnalysisCurrent();

		samIter.close();
		samReader.close();
	}
}


text:
import { warning } from '../warning';

describe('warning', () => {
  test('calls console.warn() when the condition is false', () => {
    const spy = jest.spyOn(console, 'warn').mockImplementation(() => {});
    warning(false, 'The message');

    expect(spy).toHaveBeenCalledWith('Warning: The message');
    spy.mockRestore();
  });

  test('does not call console.warn() when the condition is true', () => {
    const spy = jest.spyOn(console, 'warn').mockImplementation(() => {});

    warning(true, 'The message');

    expect(spy).not.toHaveBeenCalled();
    spy.mockRestore();
  });

  test('throws an error when no message is provided', () => {
    expect(() => {
      warning(true);
    }).toThrow();
  });

  test('substitutes extra arguments in the message', () => {
    const spy = jest.spyOn(console, 'warn').mockImplementation(() => {});

    warning(false, '%s %s %s', 'a', 'b', 'c');

    expect(spy).toHaveBeenCalledWith('Warning: a b c');
    spy.mockRestore();
  });
});


text:
package org.apache.blur.store.blockcache;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Random;

import org.apache.blur.store.buffer.BufferStore;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.junit.Before;
import org.junit.Test;

import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;

public class BlockDirectoryTest {
  private static final File TMPDIR = new File(System.getProperty("blur.tmp.dir", "/tmp"));

  private class MapperCache implements Cache {
    public Map<String, byte[]> map = new ConcurrentLinkedHashMap.Builder<String, byte[]>().maximumWeightedCapacity(8).build();

    @Override
    public void update(String name, long blockId, int blockOffset, byte[] buffer, int offset, int length) {
      byte[] cached = map.get(name + blockId);
      if (cached != null) {
        int newlen = Math.max(cached.length, blockOffset + length);
        byte[] b = new byte[newlen];
        System.arraycopy(cached, 0, b, 0, cached.length);
        System.arraycopy(buffer, offset, b, blockOffset, length);
        cached = b;
      } else {
        cached = copy(blockOffset, buffer, offset, length);
      }
      map.put(name + blockId, cached);
    }

    private byte[] copy(int blockOffset, byte[] buffer, int offset, int length) {
      byte[] b = new byte[length + blockOffset];
      System.arraycopy(buffer, offset, b, blockOffset, length);
      return b;
    }

    @Override
    public boolean fetch(String name, long blockId, int blockOffset, byte[] b, int off, int lengthToReadInBlock) {
      // return false;
      byte[] data = map.get(name + blockId);
      if (data == null) {
        return false;
      }
      System.arraycopy(data, blockOffset, b, off, lengthToReadInBlock);
      return true;
    }

    @Override
    public void delete(String name) {

    }

    @Override
    public long size() {
      return map.size();
    }

    @Override
    public void renameCacheFile(String source, String dest) {
    }
  }

  private static final int MAX_NUMBER_OF_WRITES = 10000;
  private static final int MIN_FILE_SIZE = 100;
  private static final int MAX_FILE_SIZE = 100000;
  private static final int MIN_BUFFER_SIZE = 1;
  private static final int MAX_BUFFER_SIZE = 12000;
  private static final int MAX_NUMBER_OF_READS = 20000;
  private Directory directory;
  private File file;
  private long seed;
  private Random random;
  private MapperCache mapperCache;

  @Before
  public void setUp() throws IOException {
    BufferStore.init(128, 128);
    file = new File(TMPDIR, "blockdirectorytest");
    rm(file);
    file.mkdirs();
    FSDirectory dir = FSDirectory.open(new File(file, "base"));
    mapperCache = new MapperCache();
    directory = new BlockDirectory("test", dir, mapperCache);
    seed = new Random().nextLong();
    System.out.println("Seed is " + seed);
    random = new Random(seed);
  }

  @Test
  public void testEOF() throws IOException {
    Directory fsDir = FSDirectory.open(new File(file, "normal"));
    String name = "test.eof";
    createFile(name, fsDir, directory);
    long fsLength = fsDir.fileLength(name);
    long hdfsLength = directory.fileLength(name);
    assertEquals(fsLength, hdfsLength);
    testEof(name, fsDir, fsLength);
    testEof(name, directory, hdfsLength);
  }

  private void testEof(String name, Directory directory, long length) throws IOException {
    IndexInput input = directory.openInput(name, IOContext.DEFAULT);
    input.seek(length);
    try {
      input.readByte();
      fail("should throw eof");
    } catch (IOException e) {
    }
  }

  @Test
  public void testRandomAccessWrites() throws IOException {
    long t1 = System.nanoTime();

    int i = 0;
    try {
      for (; i < 10; i++) {
        Directory fsDir = FSDirectory.open(new File(file, "normal"));
        String name = getName();
        createFile(name, fsDir, directory);
        assertInputsEquals(name, fsDir, directory);
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail("Test failed with seed [" + seed + "] on pass [" + i + "]");
    }
    long t2 = System.nanoTime();
    System.out.println("Total time is " + ((t2 - t1)/1000000) + "ms");
  }

  @Test
  public void testRandomAccessWritesLargeCache() throws IOException {
    mapperCache.map = new ConcurrentLinkedHashMap.Builder<String, byte[]>().maximumWeightedCapacity(10000).build();
    testRandomAccessWrites();
  }

  private void assertInputsEquals(String name, Directory fsDir, Directory hdfs) throws IOException {
    int reads = random.nextInt(MAX_NUMBER_OF_READS);
    IndexInput fsInput = fsDir.openInput(name, IOContext.DEFAULT);
    IndexInput hdfsInput = hdfs.openInput(name, IOContext.DEFAULT);
    assertEquals(fsInput.length(), hdfsInput.length());
    int fileLength = (int) fsInput.length();
    if (fileLength != 0) {
      for (int i = 0; i < reads; i++) {
        byte[] fsBuf = new byte[random.nextInt(Math.min(MAX_BUFFER_SIZE - MIN_BUFFER_SIZE, fileLength)) + MIN_BUFFER_SIZE];
        byte[] hdfsBuf = new byte[fsBuf.length];
        int offset = random.nextInt(fsBuf.length);
        int length = random.nextInt(fsBuf.length - offset);
        int pos = random.nextInt(fileLength - length);
        fsInput.seek(pos);
        fsInput.readBytes(fsBuf, offset, length);
        hdfsInput.seek(pos);
        hdfsInput.readBytes(hdfsBuf, offset, length);
        for (int f = offset; f < length; f++) {
          if (fsBuf[f] != hdfsBuf[f]) {
            fail(Long.toString(seed) + " read [" + i + "]");
          }
        }
      }
    }
    fsInput.close();
    hdfsInput.close();
  }

  private void createFile(String name, Directory fsDir, Directory hdfs) throws IOException {
    int writes = random.nextInt(MAX_NUMBER_OF_WRITES);
    int fileLength = random.nextInt(MAX_FILE_SIZE - MIN_FILE_SIZE) + MIN_FILE_SIZE;
    IndexOutput fsOutput = fsDir.createOutput(name, IOContext.DEFAULT);
    IndexOutput hdfsOutput = hdfs.createOutput(name, IOContext.DEFAULT);
    for (int i = 0; i < writes; i++) {
      byte[] buf = new byte[random.nextInt(Math.min(MAX_BUFFER_SIZE - MIN_BUFFER_SIZE, fileLength)) + MIN_BUFFER_SIZE];
      random.nextBytes(buf);
      int offset = random.nextInt(buf.length);
      int length = random.nextInt(buf.length - offset);
      fsOutput.writeBytes(buf, offset, length);
      hdfsOutput.writeBytes(buf, offset, length);
    }
    fsOutput.close();
    hdfsOutput.close();
  }

  private String getName() {
    return Long.toString(Math.abs(random.nextLong()));
  }

  public static void rm(File file) {
    if (!file.exists()) {
      return;
    }
    if (file.isDirectory()) {
      for (File f : file.listFiles()) {
        rm(f);
      }
    }
    file.delete();
  }

}


text:
namespace content {

void SharedFileSwitchValueBuilder::AddEntry(const std::string& key_str,
                                            int key_id) {
  if (!switch_value_.empty()) {
    switch_value_ += ",";
  }
  switch_value_ += key_str, switch_value_ += ":";
  switch_value_ += base::NumberToString(key_id);
}

absl::optional<std::map<int, std::string>> ParseSharedFileSwitchValue(
    const std::string& value) {
  std::map<int, std::string> values;
  std::vector<std::string> string_pairs = base::SplitString(
      value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  for (const auto& pair : string_pairs) {
    size_t colon_position = pair.find(":");
    if (colon_position == std::string::npos || colon_position == 0 ||
        colon_position == pair.size() - 1) {
      DLOG(ERROR) << "Found invalid entry parsing shared file string value:"
                  << pair;
      return absl::nullopt;
    }
    std::string key = pair.substr(0, colon_position);
    std::string number_string =
        pair.substr(colon_position + 1, std::string::npos);
    int key_int;
    if (!base::StringToInt(number_string, &key_int)) {
      DLOG(ERROR) << "Found invalid entry parsing shared file string value:"
                  << number_string << " (not an int).";
      return absl::nullopt;
    }

    values[key_int] = key;
  }
  return absl::make_optional(std::move(values));
}

}  // namespace content


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-3389',
  templateUrl: './comp-3389.component.html',
  styleUrls: ['./comp-3389.component.css']
})
export class Comp3389Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
var path = require('path');
var fs = require('fs');

var execute = function(pluginName, configFilePathStr, callback) {
  if (!pluginName) {
    callback(new Error('Input the plugin name'));
    return;
  }
  if (!configFilePathStr) {
    callback(new Error('Input the config file path'));
    return;
  }

  var configFilePath = path.normalize(configFilePathStr);
  if (!fs.existsSync(configFilePath)) {
    callback(new Error('Not found "' + configFilePath + '"'));
    return;
  }

  var plugin;
  try {
    plugin = require('delevts-plugin-' + pluginName);
  } catch (err) {
    callback(new Error('Not found module "delevts-plugin-' + pluginName + '"'));
    return;
  }

  var config;
  try {
    config = JSON.parse(fs.readFileSync(configFilePath));
  } catch (err) {
    callback(new Error('Config file is invalid syntax'));
    return;
  }

  plugin.deleteEvents(config, callback);
};

exports.execute = execute;


text:
package ex2;

/**
 * La classe Word estende la classe Token. Un Token e una coppia costituita da
 * un nome e un valore di un attributo opzionale Il nome del token è un simbolo
 * astratto che rappresenta uno specifico tipo di unita lessicale. Pe esempio
 * una particolare parola chiave oppure una sequenza di caratteri che denota un
 * identificatore
 *
 * Una lessema e un'instanza di un token Per esempio: per il Token <ID>
 * corrispondono i lessemi: pi, score, D2 per il Token <NUMBER> corrispondono i
 * lessemi: 3.12, 345, 0.54
 *
 * @see Grammatica
 * @author UNITO
 */
public class Word extends Token {

    /**
     * lexeme e un'istanza di un Token
     */
    public String lexeme = "";

    /**
     *
     * @param tag Il nome del Token
     * @param s lessema
     */
    public Word(int tag, String s) {
        super(tag);
        lexeme = s;
    }

    public String toString() {
        return "<" + Tag.print(tag) + ", '" + lexeme + "'>";
    }
    public static final Word and = new Word(Tag.AND, "&&"),
            or = new Word(Tag.OR, "||"),
            eq = new Word(Tag.EQ, "=="),
            le = new Word(Tag.LE, "<="),
            ne = new Word(Tag.NE, "<>"),
            ge = new Word(Tag.GE, ">="),
            assign = new Word(Tag.ASSIGN, ":=");
}