text:
from __future__ import print_function, division, absolute_import, unicode_literals
from grako.parsing import graken, Parser

__version__ = (2015, 2, 17, 0, 8, 14, 1)

__all__ = [
    'dependenciesParser',
    'dependenciesSemantics',
    'main'
]

class dependenciesParser(Parser):
    def __init__(self, whitespace=None, nameguard=True, **kwargs):
        super(dependenciesParser, self).__init__(
            whitespace=whitespace,
            nameguard=nameguard,
            **kwargs
        )

    @graken()
    def _number_(self):
        self._pattern(r'[0-9]+')

    @graken()
    def _identifier_(self):
        self._ident_start_()

        def block0():
            self._ident_cont_()
        self._closure(block0)

    @graken()
    def _ident_start_(self):
        self._pattern(r'[a-zA-Z_\ ]')

    @graken()
    def _ident_cont_(self):
        with self._choice():
            with self._option():
                self._ident_start_()
            with self._option():
                self._pattern(r'[0-9]')
            self._error('expecting one of: [0-9]')

    @graken()
    def _spacing_(self):

        def block0():
            self._space_()
        self._closure(block0)

    @graken()
    def _space_(self):
        with self._choice():
            with self._option():
                self._token(' ')
            with self._option():
                self._token('\t')
            with self._option():
                self._check_eof()
            self._error('expecting one of: \t  ')

    @graken()
    def _eol_(self):
        with self._choice():
            with self._option():
                self._token('\r\n')
            with self._option():
                self._token('\n')
            with self._option():
                self._token('\r')
            self._error('expecting one of: \n \r \r\n')

    @graken()
    def _option_path_(self):
        with self._choice():
            with self._option():
                self._identifier_()
                self.ast['@'] = self.last_node
                self._token('.')
                self._option_path_()
                self.ast['@'] = self.last_node
            with self._option():
                self._identifier_()
            self._error('no available options')

    @graken()
    def _boolexp_(self):
        with self._choice():
            with self._option():
                self._boolterm_()
                self.ast['@'] = self.last_node
                self._spacing_()
                self._boolean_connector_()
                self.ast['@'] = self.last_node
                self._spacing_()
                self._boolexp_()
                self.ast['@'] = self.last_node
            with self._option():
                self._boolterm_()
            self._error('no available options')

    @graken()
    def _boolterm_(self):
        with self._choice():
            with self._option():
                self._bool_literal_()
            with self._option():
                self._option_path_()
                self.ast['@'] = self.last_node
                self._spacing_()
                self._operation_()
                self.ast['@'] = self.last_node
                self._spacing_()
                self._value_()
                self.ast['@'] = self.last_node
            with self._option():
                self._token('(')
                self._spacing_()
                self._boolexp_()
                self.ast['@'] = self.last_node
                self._spacing_()
                self._token(')')
            self._error('no available options')

    @graken()
    def _bool_literal_(self):
        with self._choice():
            with self._option():
                self._token('True')
            with self._option():
                self._token('False')
            self._error('expecting one of: False True')

    @graken()
    def _value_(self):
        with self._choice():
            with self._option():
                self._number_()
            with self._option():
                self._literal_string_()
            with self._option():
                self._bool_literal_()
            with self._option():
                self._option_path_()
                self.ast['path'] = self.last_node
            self._error('no available options')

        self.ast._define(
            ['path'],
            []
        )

    @graken()
    def _operation_(self):
        with self._choice():
            with self._option():
                self._token('IS')
            with self._option():
                self._token('=')
            with self._option():
                self._token('<>')
            with self._option():
                self._token('>')
            with self._option():
                self._token('<')
            self._error('expecting one of: < <> = > IS')

    @graken()
    def _literal_string_(self):
        self._token("'")

        def block1():
            self._pattern(r'[\w\ ]')
        self._closure(block1)
        self.ast['@'] = self.last_node
        self._token("'")

    @graken()
    def _boolean_connector_(self):
        with self._choice():
            with self._option():
                self._token('AND')
            with self._option():
                self._token('OR')
            with self._option():
                self._token('XOR')
            self._error('expecting one of: AND OR XOR')

class dependenciesSemantics(object):
    def number(self, ast):
        return ast

    def identifier(self, ast):
        return ast

    def ident_start(self, ast):
        return ast

    def ident_cont(self, ast):
        return ast

    def spacing(self, ast):
        return ast

    def space(self, ast):
        return ast

    def eol(self, ast):
        return ast

    def option_path(self, ast):
        return ast

    def boolexp(self, ast):
        return ast

    def boolterm(self, ast):
        return ast

    def bool_literal(self, ast):
        return ast

    def value(self, ast):
        return ast

    def operation(self, ast):
        return ast

    def literal_string(self, ast):
        return ast

    def boolean_connector(self, ast):
        return ast

def main(filename, startrule, trace=False, whitespace=None, nameguard=None):
    import json
    with open(filename) as f:
        text = f.read()
    parser = dependenciesParser(parseinfo=False)
    ast = parser.parse(
        text,
        startrule,
        filename=filename,
        trace=trace,
        whitespace=whitespace,
        nameguard=nameguard)
    print('AST:')
    print(ast)
    print()
    print('JSON:')
    print(json.dumps(ast, indent=2))
    print()

if __name__ == '__main__':
    import argparse
    import string
    import sys

    class ListRules(argparse.Action):
        def __call__(self, parser, namespace, values, option_string):
            print('Rules:')
            for r in dependenciesParser.rule_list():
                print(r)
            print()
            sys.exit(0)

    parser = argparse.ArgumentParser(description="Simple parser for dependencies.")
    parser.add_argument('-l', '--list', action=ListRules, nargs=0,
                        help="list all rules and exit")
    parser.add_argument('-n', '--no-nameguard', action='store_true',
                        dest='no_nameguard',
                        help="disable the 'nameguard' feature")
    parser.add_argument('-t', '--trace', action='store_true',
                        help="output trace information")
    parser.add_argument('-w', '--whitespace', type=str, default=string.whitespace,
                        help="whitespace specification")
    parser.add_argument('file', metavar="FILE", help="the input file to parse")
    parser.add_argument('startrule', metavar="STARTRULE",
                        help="the start rule for parsing")
    args = parser.parse_args()

    main(
        args.file,
        args.startrule,
        trace=args.trace,
        whitespace=args.whitespace,
        nameguard=not args.no_nameguard
    )


text:
package com.sumarlidi.medieval.webbapp.dtos;

import java.util.Date;

import javax.validation.constraints.Digits;
import javax.validation.constraints.Future;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;

public class AddEventsDTO {

	@NotBlank(message="Cannot be blank")
	@Size(min=3, message="Must be at least 3 letter size")
	private String name;

	@NotBlank(message="Cannot be blank")
	private String promoter;

	@DateTimeFormat(pattern="yyyy-MM-dd")
	@NotNull(message="Cannot be blank")
	@Future(message="Date should relate to future")
	private Date startDate;

	private String description;

	private String shortDescription;
	@NotBlank(message="Cannot be black")
	@Min(value=1, message="Number of participants must by higher than 0")
	@Digits(fraction = 0, integer = 5, message="Must be number from 0 to 100000")
	private String maxParticipants;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPromoter() {
		return promoter;
	}

	public void setPromoter(String promoter) {
		this.promoter = promoter;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getMaxParticipants() {
		return maxParticipants;
	}

	public void setMaxParticipants(String maxParticipants) {
		this.maxParticipants = maxParticipants;
	}

	public String getShortDescription() {
		return shortDescription;
	}

	public void setShortDescription(String shortDescription) {
		this.shortDescription = shortDescription;
	}

}

redpajama_set_name: RedPajamaGithub


text:
package acl

import (
	"context"
	"strings"

	"github.com/pkg/errors"

	"github.com/kopia/kopia/repo"
	"github.com/kopia/kopia/repo/manifest"
)

const (
	aclManifestType = "acl"
)

func matchOrWildcard(rule, actual string) bool {
	if rule == "*" {
		return true
	}

	return rule == actual
}

func userMatches(rule, username, hostname string) bool {
	ruleParts := strings.Split(rule, "@")
	if len(ruleParts) != 2 { //nolint:gomnd
		return false
	}

	return matchOrWildcard(ruleParts[0], username) && matchOrWildcard(ruleParts[1], hostname)
}

// EntriesForUser computes the list of ACL entries matching the given user.
func EntriesForUser(entries []*Entry, username, hostname string) []*Entry {
	result := []*Entry{}

	for _, e := range entries {
		if userMatches(e.User, username, hostname) {
			result = append(result, e)
		}
	}

	return result
}

// EffectivePermissions computes the effective access level for a given user@hostname to subject
// for a given set of ACL Entries.
func EffectivePermissions(username, hostname string, target map[string]string, entries []*Entry) AccessLevel {
	highest := AccessLevelNone

	for _, e := range entries {
		if !userMatches(e.User, username, hostname) {
			continue
		}

		if !e.Target.matches(target, username, hostname) {
			continue
		}

		if e.Access > highest {
			highest = e.Access
		}
	}

	return highest
}

// LoadEntries returns the set of all ACLs in the repository, using old list as a cache.
func LoadEntries(ctx context.Context, rep repo.Repository, old []*Entry) ([]*Entry, error) {
	if rep == nil {
		return nil, nil
	}

	entries, err := rep.FindManifests(ctx, map[string]string{
		manifest.TypeLabelKey: aclManifestType,
	})
	if err != nil {
		return nil, errors.Wrap(err, "error listing ACL manifests")
	}

	om := map[manifest.ID]*Entry{}
	for _, v := range old {
		om[v.ManifestID] = v
	}

	result := []*Entry{}

	for _, m := range entries {
		if o := om[m.ID]; o != nil {
			result = append(result, o)
			continue
		}

		var p Entry

		_, err := rep.GetManifest(ctx, m.ID, &p)
		if err != nil {
			return nil, errors.Wrapf(err, "error loading ACL manifest %v", m.ID)
		}

		p.ManifestID = m.ID

		result = append(result, &p)
	}

	return result, nil
}

// AddACL validates and adds the specified ACL entry to the repository.
func AddACL(ctx context.Context, w repo.RepositoryWriter, e *Entry) error {
	if err := e.Validate(); err != nil {
		return errors.Wrap(err, "error validating ACL")
	}

	manifestID, err := w.PutManifest(ctx, map[string]string{
		manifest.TypeLabelKey: aclManifestType,
	}, e)
	if err != nil {
		return errors.Wrap(err, "error writing manifest")
	}

	e.ManifestID = manifestID

	return nil
}


text:
package com.intel.analytics.bigdl.dllib.models.rnn

import com.intel.analytics.bigdl._
import com.intel.analytics.bigdl.dllib.feature.dataset.{DataSet, FixedLength, PaddingParam, SampleToMiniBatch}
import com.intel.analytics.bigdl.dllib.feature.dataset.text.LabeledSentenceToSample
import com.intel.analytics.bigdl.dllib.feature.dataset.text._
import com.intel.analytics.bigdl.dllib.feature.dataset.text.utils.SentenceToken
import com.intel.analytics.bigdl.dllib.nn.{CrossEntropyCriterion, Module, TimeDistributedCriterion}
import com.intel.analytics.bigdl.dllib.optim._
import com.intel.analytics.bigdl.dllib.tensor.{Storage, Tensor}
import com.intel.analytics.bigdl.dllib.utils.{T, Table}
import com.intel.analytics.bigdl.dllib.utils.{Engine, OptimizerV1, OptimizerV2}
import com.intel.analytics.bigdl.dllib.tensor.TensorNumericMath.TensorNumeric._
import org.apache.logging.log4j.{Level, LogManager}
import org.apache.logging.log4j.core.config.Configurator
import org.apache.spark.SparkContext

object Train {
  Configurator.setLevel("org", Level.ERROR)
  Configurator.setLevel("akka", Level.ERROR)
  Configurator.setLevel("breeze", Level.ERROR)

  import Utils._
  val logger = LogManager.getLogger(getClass)
  def main(args: Array[String]): Unit = {
    trainParser.parse(args, new TrainParams()).map(param => {

      val conf = Engine.createSparkConf()
        .setAppName("Train rnn on text")
        .set("spark.task.maxFailures", "1")
      val sc = new SparkContext(conf)
      Engine.init

      val tokens = SequencePreprocess(
        param.dataFolder + "/train.txt",
        sc = sc,
        param.sentFile,
        param.tokenFile)

      val dictionary = Dictionary(tokens, param.vocabSize)
      dictionary.save(param.saveFolder)

      val maxTrainLength = tokens.map(x => x.length).max

      val valtokens = SequencePreprocess(
        param.dataFolder + "/val.txt",
        sc = sc,
        param.sentFile,
        param.tokenFile)
      val maxValLength = valtokens.map(x => x.length).max

      logger.info(s"maxTrain length = ${maxTrainLength}, maxVal = ${maxValLength}")

      val totalVocabLength = dictionary.getVocabSize() + 1
      val startIdx = dictionary.getIndex(SentenceToken.start)
      val endIdx = dictionary.getIndex(SentenceToken.end)
      val padFeature = Tensor[Float]().resize(totalVocabLength)
      padFeature.setValue(endIdx + 1, 1.0f)
      val padLabel = Tensor[Float](T(startIdx.toFloat + 1.0f))
      val featurePadding = PaddingParam(Some(Array(padFeature)),
        FixedLength(Array(maxTrainLength)))
      val labelPadding = PaddingParam(Some(Array(padLabel)),
        FixedLength(Array(maxTrainLength)))

      val trainSet = DataSet.rdd(tokens)
        .transform(TextToLabeledSentence[Float](dictionary))
        .transform(LabeledSentenceToSample[Float](totalVocabLength))
        .transform(SampleToMiniBatch[Float](
          param.batchSize,
          Some(featurePadding),
          Some(labelPadding)))

      val validationSet = DataSet.rdd(valtokens)
        .transform(TextToLabeledSentence[Float](dictionary))
        .transform(LabeledSentenceToSample[Float](totalVocabLength))
        .transform(SampleToMiniBatch[Float](param.batchSize,
          Some(featurePadding), Some(labelPadding)))

      val model = if (param.modelSnapshot.isDefined) {
        Module.loadModule[Float](param.modelSnapshot.get)
      } else {
        val curModel = SimpleRNN(
          inputSize = totalVocabLength,
          hiddenSize = param.hiddenSize,
          outputSize = totalVocabLength)
        curModel.reset()
        curModel
      }

      if (param.optimizerVersion.isDefined) {
        param.optimizerVersion.get.toLowerCase match {
          case "optimizerv1" => Engine.setOptimizerVersion(OptimizerV1)
          case "optimizerv2" => Engine.setOptimizerVersion(OptimizerV2)
        }
      }

      val optimMethod = if (param.stateSnapshot.isDefined) {
        OptimMethod.load[Float](param.stateSnapshot.get)
      } else {
        new SGD[Float](learningRate = param.learningRate, learningRateDecay = 0.0,
          weightDecay = param.weightDecay, momentum = param.momentum, dampening = param.dampening)
      }

      val optimizer = Optimizer(
        model = model,
        dataset = trainSet,
        criterion = TimeDistributedCriterion[Float](
          CrossEntropyCriterion[Float](), sizeAverage = true)
      )

      if (param.checkpoint.isDefined) {
        optimizer.setCheckpoint(param.checkpoint.get, Trigger.everyEpoch)
      }

      if(param.overWriteCheckpoint) {
        optimizer.overWriteCheckpoint()
      }

      optimizer
        .setValidation(Trigger.everyEpoch, validationSet, Array(new Loss[Float](
          TimeDistributedCriterion[Float](CrossEntropyCriterion[Float](), sizeAverage = true))))
        .setOptimMethod(optimMethod)
        .setEndWhen(Trigger.maxEpoch(param.nEpochs))
        .setCheckpoint(param.checkpoint.get, Trigger.everyEpoch)
        .optimize()
      sc.stop()
    })
  }
}


text:
/**
 * Transform an object prototype to array
 * Usefull for jack
 * TODO: implement it on Jack
 */
function object2Array(object) {
    var a = [];
    for (var i in object.prototype) {
        if (typeof object.prototype[i] == "function") {
            a.push(i);
        }
    }
    return a;
}

function toDom(string)
{
    if (window.DOMParser)
    {
        var parser = new DOMParser();
        return parser.parseFromString(string, "text/xml").documentElement;
    }
    else // Internet Explorer
    {
        var parser = new ActiveXObject("Microsoft.XMLDOM");
        parser.async = "false";
        parser.loadXML(string);
        return parser.documentElement;
    }
}
var rosterPlugin = Strophe._connectionPlugins["roster"];
module("plugins.Roster", {
           setup: function() {
               rosterPlugin.items = [];
               rosterPlugin.ver = null;
               rosterPlugin._callbacks = [];
           },
           teardown: function() {

           }
});

// shortcut access

// Qunit test with jack for mocking facility
function jackTest(name, fun) {
    test(name,
         function() {
             jack(
                 function() {
                     var mockConnection = jack.create("mockConnection", object2Array(Strophe.Connection));
                     fun(mockConnection);
                 }

             );
         }
        );
}


text:
/**
 * php-asio/resolver.cpp
 *
 * @author CismonX<admin@cismon.net>
 */

#include "resolver.hpp"
#include "future.hpp"

namespace asio
{
    template <typename Protocol>
    zval* resolver<Protocol>::handler(const boost::system::error_code& error,
        iterator iter, zval* callback, zval* argument)
    {
        iterator end;
        ZVAL_INIT(addr_list);
        ZVAL_NEW_ARR(&addr_list);
        zend_hash_init(Z_ARR(addr_list), 0, nullptr, ZVAL_PTR_DTOR, 0);
        ZVAL_INIT(addr_val);
        while (iter != end) {
            auto addr = (*iter++).endpoint().address().to_string();
            ZVAL_STR(&addr_val, zend_string_init(addr.c_str(), addr.length(), 0));
            zend_hash_next_index_insert(Z_ARR(addr_list), &addr_val);
        }
        PHP_ASIO_INVOKE_CALLBACK_START(4)
            ZVAL_ARR(&arguments[1], Z_ARR(addr_list));
            PHP_ASIO_INVOKE_CALLBACK();
        PHP_ASIO_INVOKE_CALLBACK_END();
        CORO_RETURN(ZVAL_ARR, Z_ARR(addr_list));
    }

    template <typename Protocol>
    P3_METHOD(resolver<Protocol>, resolve)
    {
        zend_string* host;
        zend_string* service = nullptr;
        zval* callback = nullptr;
        zval* argument = nullptr;
        ZEND_PARSE_PARAMETERS_START(1, 4)
            Z_PARAM_STR(host)
            Z_PARAM_OPTIONAL
            Z_PARAM_STR(service)
            Z_PARAM_ZVAL(callback)
            Z_PARAM_ZVAL(argument)
        ZEND_PARSE_PARAMETERS_END();
        PHP_ASIO_FUTURE_INIT();
        future->template on_resolve<iterator>(boost::bind(
            &resolver::handler, this, _1, _2, cb, args));
        resolver_.async_resolve({ ZSTR_VAL(host), service ? ZSTR_VAL(service) : "" },
            STRAND_RESOLVE(ASYNC_HANDLER_DOUBLE_ARG(iterator)));
        FUTURE_RETURN();
    }

    template <typename Protocol>
    P3_METHOD(resolver<Protocol>, cancel)
    {
        resolver_.cancel();
        RETVAL_LONG(0);
    }

    template <typename Protocol>
    zend_class_entry* resolver<Protocol>::class_entry;

    template <typename Protocol>
    zend_object_handlers resolver<Protocol>::handlers;

    template class resolver<tcp>;
    template class resolver<udp>;
}


text:
/*jslint plusplus: true, nomen: true, regexp: true */
/*global define: false */

define([ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse',
         'pragma', 'uglifyjs/index', 'uglifyjs2',
         'source-map'],
function (lang,   logger,   envOptimize,        file,           parse,
          pragma, uglify,             uglify2,
          sourceMap) {
    'use strict';

    var optimize,
        cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig,
        cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g,
        cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g,
        SourceMapGenerator = sourceMap.SourceMapGenerator,
        SourceMapConsumer =sourceMap.SourceMapConsumer;

    /**
     * If an URL from a CSS url value contains start/end quotes, remove them.
     * This is not done in the regexp, since my regexp fu is not that strong,
     * and the CSS spec allows for ' and " in the URL if they are backslash escaped.
     * @param {String} url
     */
    function cleanCssUrlQuotes(url) {
        //Make sure we are not ending in whitespace.
        //Not very confident of the css regexps above that there will not be ending
        //whitespace.
        url = url.replace(/\s+$/, "");

        if (url.charAt(0) === "'" || url.charAt(0) === "\"") {
            url = url.substring(1, url.length - 1);
        }

        return url;
    }

    function fixCssUrlPaths(fileName, path, contents, cssPrefix) {
        return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) {
            var colonIndex, firstChar, parts, i,
                fixedUrlMatch = cleanCssUrlQuotes(urlMatch);

            fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/");

            //Only do the work for relative URLs. Skip things that start with / or #, or have
            //a protocol.
            firstChar = fixedUrlMatch.charAt(0);
            colonIndex = fixedUrlMatch.indexOf(":");
            if (firstChar !== "/" && firstChar !== "#" && (colonIndex === -1 || colonIndex > fixedUrlMatch.indexOf("/"))) {
                //It is a relative URL, tack on the cssPrefix and path prefix
                urlMatch = cssPrefix + path + fixedUrlMatch;

            } else {
                logger.trace(fileName + "\n  URL not a relative URL, skipping: " + urlMatch);
            }

            //Collapse .. and .
            parts = urlMatch.split("/");
            for (i = parts.length - 1; i > 0; i--) {
                if (parts[i] === ".") {
                    parts.splice(i, 1);
                } else if (parts[i] === "..") {
                    if (i !== 0 && parts[i - 1] !== "..") {
                        parts.splice(i - 1, 2);
                        i -= 1;
                    }
                }
            }

            return "url(" + parts.join("/") + ")";
        });
    }

    /**
     * Inlines nested stylesheets that have @import calls in them.
     * @param {String} fileName the file name
     * @param {String} fileContents the file contents
     * @param {String} cssImportIgnore comma delimited string of files to ignore
     * @param {String} cssPrefix string to be prefixed before relative URLs
     * @param {Object} included an object used to track the files already imported
     */
    function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) {
        //Find the last slash in the name.
        fileName = fileName.replace(lang.backSlashRegExp, "/");
        var endIndex = fileName.lastIndexOf("/"),
            //Make a file path based on the last slash.
            //If no slash, so must be just a file name. Use empty string then.
            filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "",
            //store a list of merged files
            importList = [],
            skippedList = [];

        //First make a pass by removing any commented out @import calls.
        fileContents = fileContents.replace(cssCommentImportRegExp, '');

        //Make sure we have a delimited ignore list to make matching faster
        if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") {
            cssImportIgnore += ",";
        }

        fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) {
            //Only process media type "all" or empty media type rules.
            if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) {
                skippedList.push(fileName);
                return fullMatch;
            }

            importFileName = cleanCssUrlQuotes(importFileName);

            //Ignore the file import if it is part of an ignore list.
            if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) {
                return fullMatch;
            }

            //Make sure we have a unix path for the rest of the operation.
            importFileName = importFileName.replace(lang.backSlashRegExp, "/");

            try {
                //if a relative path, then tack on the filePath.
                //If it is not a relative path, then the readFile below will fail,
                //and we will just skip that import.
                var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName,
                    importContents = file.readFile(fullImportFileName),
                    importEndIndex, importPath, flat;

                //Skip the file if it has already been included.
                if (included[fullImportFileName]) {
                    return '';
                }
                included[fullImportFileName] = true;

                //Make sure to flatten any nested imports.
                flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included);
                importContents = flat.fileContents;

                if (flat.importList.length) {
                    importList.push.apply(importList, flat.importList);
                }
                if (flat.skippedList.length) {
                    skippedList.push.apply(skippedList, flat.skippedList);
                }

                //Make the full import path
                importEndIndex = importFileName.lastIndexOf("/");

                //Make a file path based on the last slash.
                //If no slash, so must be just a file name. Use empty string then.
                importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : "";

                //fix url() on relative import (#5)
                importPath = importPath.replace(/^\.\//, '');

                //Modify URL paths to match the path represented by this file.
                importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix);

                importList.push(fullImportFileName);
                return importContents;
            } catch (e) {
                logger.warn(fileName + "\n  Cannot inline css import, skipping: " + importFileName);
                return fullMatch;
            }
        });

        if (cssPrefix && topLevel) {
            //Modify URL paths to match the path represented by this file.
            fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix);
        }

        return {
            importList : importList,
            skippedList: skippedList,
            fileContents : fileContents
        };
    }

    optimize = {
        /**
         * Optimizes a file that contains JavaScript content. Optionally collects
         * plugin resources mentioned in a file, and then passes the content
         * through an minifier if one is specified via config.optimize.
         *
         * @param {String} fileName the name of the file to optimize
         * @param {String} fileContents the contents to optimize. If this is
         * a null value, then fileName will be used to read the fileContents.
         * @param {String} outFileName the name of the file to use for the
         * saved optimized content.
         * @param {Object} config the build config object.
         * @param {Array} [pluginCollector] storage for any plugin resources
         * found.
         */
        jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) {
            if (!fileContents) {
                fileContents = file.readFile(fileName);
            }

            fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector);

            file.saveUtf8File(outFileName, fileContents);
        },

        /**
         * Optimizes a file that contains JavaScript content. Optionally collects
         * plugin resources mentioned in a file, and then passes the content
         * through an minifier if one is specified via config.optimize.
         *
         * @param {String} fileName the name of the file that matches the
         * fileContents.
         * @param {String} fileContents the string of JS to optimize.
         * @param {Object} [config] the build config object.
         * @param {Array} [pluginCollector] storage for any plugin resources
         * found.
         */
        js: function (fileName, fileContents, outFileName, config, pluginCollector) {
            var optFunc, optConfig,
                parts = (String(config.optimize)).split('.'),
                optimizerName = parts[0],
                keepLines = parts[1] === 'keepLines',
                licenseContents = '';

            config = config || {};

            //Apply pragmas/namespace renaming
            fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector);

            //Optimize the JS files if asked.
            if (optimizerName && optimizerName !== 'none') {
                optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName];
                if (!optFunc) {
                    throw new Error('optimizer with name of "' +
                                    optimizerName +
                                    '" not found for this environment');
                }

                optConfig = config[optimizerName] || {};
                if (config.generateSourceMaps) {
                    optConfig.generateSourceMaps = !!config.generateSourceMaps;
                    optConfig._buildSourceMap = config._buildSourceMap;
                }

                try {
                    if (config.preserveLicenseComments) {
                        //Pull out any license comments for prepending after optimization.
                        try {
                            licenseContents = parse.getLicenseComments(fileName, fileContents);
                        } catch (e) {
                            throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString());
                        }
                    }

                    fileContents = licenseContents + optFunc(fileName,
                                                             fileContents,
                                                             outFileName,
                                                             keepLines,
                                                             optConfig);
                    if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) {
                        config._buildSourceMap = optConfig._buildSourceMap;
                    }
                } catch (e) {
                    if (config.throwWhen && config.throwWhen.optimize) {
                        throw e;
                    } else {
                        logger.error(e);
                    }
                }
            } else {
                if (config._buildSourceMap) {
                    config._buildSourceMap = null;
                }
            }

            return fileContents;
        },

        /**
         * Optimizes one CSS file, inlining @import calls, stripping comments, and
         * optionally removes line returns.
         * @param {String} fileName the path to the CSS file to optimize
         * @param {String} outFileName the path to save the optimized file.
         * @param {Object} config the config object with the optimizeCss and
         * cssImportIgnore options.
         */
        cssFile: function (fileName, outFileName, config) {

            //Read in the file. Make sure we have a JS string.
            var originalFileContents = file.readFile(fileName),
                flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true),
                //Do not use the flattened CSS if there was one that was skipped.
                fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents,
                startIndex, endIndex, buildText, comment;

            if (flat.skippedList.length) {
                logger.warn('Cannot inline @imports for ' + fileName +
                            ',\nthe following files had media queries in them:\n' +
                            flat.skippedList.join('\n'));
            }

            //Do comment removal.
            try {
                if (config.optimizeCss.indexOf(".keepComments") === -1) {
                    startIndex = 0;
                    //Get rid of comments.
                    while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) {
                        endIndex = fileContents.indexOf("*/", startIndex + 2);
                        if (endIndex === -1) {
                            throw "Improper comment in CSS file: " + fileName;
                        }
                        comment = fileContents.substring(startIndex, endIndex);

                        if (config.preserveLicenseComments &&
                            (comment.indexOf('license') !== -1 ||
                             comment.indexOf('opyright') !== -1 ||
                             comment.indexOf('(c)') !== -1)) {
                            //Keep the comment, just increment the startIndex
                            startIndex = endIndex;
                        } else {
                            fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length);
                            startIndex = 0;
                        }
                    }
                }
                //Get rid of newlines.
                if (config.optimizeCss.indexOf(".keepLines") === -1) {
                    fileContents = fileContents.replace(/[\r\n]/g, " ");
                    fileContents = fileContents.replace(/\s+/g, " ");
                    fileContents = fileContents.replace(/\{\s/g, "{");
                    fileContents = fileContents.replace(/\s\}/g, "}");
                } else {
                    //Remove multiple empty lines.
                    fileContents = fileContents.replace(/(\r\n)+/g, "\r\n");
                    fileContents = fileContents.replace(/(\n)+/g, "\n");
                }
                //Remove unnecessary whitespace
                if (config.optimizeCss.indexOf(".keepWhitespace") === -1) {
                    //Remove leading and trailing whitespace from lines
                    fileContents = fileContents.replace(/^[ \t]+/gm, "");
                    fileContents = fileContents.replace(/[ \t]+$/gm, "");
                    //Remove whitespace after semicolon, colon, curly brackets and commas
                    fileContents = fileContents.replace(/(;|:|\{|}|,)[ \t]+/g, "$1");
                    //Remove whitespace before opening curly brackets
                    fileContents = fileContents.replace(/[ \t]+(\{)/g, "$1");
                    //Truncate double whitespace
                    fileContents = fileContents.replace(/([ \t])+/g, "$1");
                    //Remove empty lines
                    fileContents = fileContents.replace(/^[ \t]*[\r\n]/gm,'');
                }
            } catch (e) {
                fileContents = originalFileContents;
                logger.error("Could not optimized CSS file: " + fileName + ", error: " + e);
            }

            file.saveUtf8File(outFileName, fileContents);

            //text output to stdout and/or written to build.txt file
            buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n";
            flat.importList.push(fileName);
            buildText += flat.importList.map(function(path){
                return path.replace(config.dir, "");
            }).join("\n");

            return {
                importList: flat.importList,
                buildText: buildText +"\n"
            };
        },

        /**
         * Optimizes CSS files, inlining @import calls, stripping comments, and
         * optionally removes line returns.
         * @param {String} startDir the path to the top level directory
         * @param {Object} config the config object with the optimizeCss and
         * cssImportIgnore options.
         */
        css: function (startDir, config) {
            var buildText = "",
                importList = [],
                shouldRemove = config.dir && config.removeCombined,
                i, fileName, result, fileList;
            if (config.optimizeCss.indexOf("standard") !== -1) {
                fileList = file.getFilteredFileList(startDir, /\.css$/, true);
                if (fileList) {
                    for (i = 0; i < fileList.length; i++) {
                        fileName = fileList[i];
                        logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName);
                        result = optimize.cssFile(fileName, fileName, config);
                        buildText += result.buildText;
                        if (shouldRemove) {
                            result.importList.pop();
                            importList = importList.concat(result.importList);
                        }
                    }
                }

                if (shouldRemove) {
                    importList.forEach(function (path) {
                        if (file.exists(path)) {
                            file.deleteFile(path);
                        }
                    });
                }
            }
            return buildText;
        },

        optimizers: {
            uglify: function (fileName, fileContents, outFileName, keepLines, config) {
                var parser = uglify.parser,
                    processor = uglify.uglify,
                    ast, errMessage, errMatch;

                config = config || {};

                logger.trace("Uglifying file: " + fileName);

                try {
                    ast = parser.parse(fileContents, config.strict_semicolons);
                    if (config.no_mangle !== true) {
                        ast = processor.ast_mangle(ast, config);
                    }
                    ast = processor.ast_squeeze(ast, config);

                    fileContents = processor.gen_code(ast, config);

                    if (config.max_line_length) {
                        fileContents = processor.split_lines(fileContents, config.max_line_length);
                    }

                    //Add trailing semicolon to match uglifyjs command line version
                    fileContents += ';';
                } catch (e) {
                    errMessage = e.toString();
                    errMatch = /\nError(\r)?\n/.exec(errMessage);
                    if (errMatch) {
                        errMessage = errMessage.substring(0, errMatch.index);
                    }
                    throw new Error('Cannot uglify file: ' + fileName + '. Skipping it. Error is:\n' + errMessage);
                }
                return fileContents;
            },
            uglify2: function (fileName, fileContents, outFileName, keepLines, config) {
                var result, existingMap, resultMap, finalMap, sourceIndex,
                    uconfig = {},
                    existingMapPath = outFileName + '.map',
                    baseName = fileName && fileName.split('/').pop();

                config = config || {};

                lang.mixin(uconfig, config, true);

                uconfig.fromString = true;

                if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) {
                    uconfig.outSourceMap = baseName;

                    if (config._buildSourceMap) {
                        existingMap = JSON.parse(config._buildSourceMap);
                        uconfig.inSourceMap = existingMap;
                    } else if (file.exists(existingMapPath)) {
                        uconfig.inSourceMap = existingMapPath;
                        existingMap = JSON.parse(file.readFile(existingMapPath));
                    }
                }

                logger.trace("Uglify2 file: " + fileName);

                try {
                    //var tempContents = fileContents.replace(/\/\/\# sourceMappingURL=.*$/, '');
                    result = uglify2.minify(fileContents, uconfig, baseName + '.src.js');
                    if (uconfig.outSourceMap && result.map) {
                        resultMap = result.map;
                        if (existingMap) {
                            resultMap = JSON.parse(resultMap);
                            finalMap = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(resultMap));
                            finalMap.applySourceMap(new SourceMapConsumer(existingMap));
                            resultMap = finalMap.toString();
                        } else if (!config._buildSourceMap) {
                            file.saveFile(outFileName + '.src.js', fileContents);
                        }

                        fileContents = result.code;

                        if (config._buildSourceMap) {
                            config._buildSourceMap = resultMap;
                        } else {
                            file.saveFile(outFileName + '.map', resultMap);
                            fileContents += "\n//# sourceMappingURL=" + baseName + ".map";
                        }
                    } else {
                        fileContents = result.code;
                    }
                } catch (e) {
                    throw new Error('Cannot uglify2 file: ' + fileName + '. Skipping it. Error is:\n' + e.toString());
                }
                return fileContents;
            }
        }
    };

    return optimize;
});


text:
@interface CoreDataManager : NSObject

+ (void)setCoreDataManagedObjectContext:(NSManagedObjectContext*)context;
+ (NSArray*)getAllEntityRecords:(NSString*)entityForName;
+ (void)removeCoreDataEntityRows:(NSString*)entityForName;

@end


text:
<component name="libraryTable">
  <library name="ShareSDK-Facebook-2.5.4">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/libs/ShareSDK-Facebook-2.5.4.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
package me.dags.daflight.player.mode;

import me.dags.daflight.player.DFController;

public interface IMode
{
    public void input(DFController DFController);

    public void unFocused();
}


text:
package org.wso2.andes.kernel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.andes.kernel.slot.SlotDeliveryWorkerManager;
import org.wso2.andes.subscription.LocalSubscription;
import org.wso2.andes.subscription.SubscriptionEngine;

import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Strategy definition for queue message delivery
 */
public class FlowControlledQueueMessageDeliveryImpl implements MessageDeliveryStrategy {

    private static Log log = LogFactory.getLog(FlowControlledQueueMessageDeliveryImpl.class);
    private SubscriptionEngine subscriptionEngine;

    public FlowControlledQueueMessageDeliveryImpl(SubscriptionEngine subscriptionEngine) {
        this.subscriptionEngine = subscriptionEngine;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int deliverMessageToSubscriptions(MessageDeliveryInfo messageDeliveryInfo, String storageQueue) throws
            AndesException {

        Collection<DeliverableAndesMetadata> messages = messageDeliveryInfo.getReadButUndeliveredMessages();
        int sentMessageCount = 0;
        Iterator<DeliverableAndesMetadata> iterator = messages.iterator();

        String destination = messageDeliveryInfo.getDestination();
        DestinationType destinationType = messageDeliveryInfo.getDestinationType();

        ProtocolType protocolType = messageDeliveryInfo.getProtocolType();

        /**
         * get all relevant type of subscriptions. This call does NOT
         * return hierarchical subscriptions for the destination. There
         * are duplicated messages for each different subscribed destination.
         * For durable topic subscriptions this should return queue subscription
         * bound to unique queue based on subscription id
         */
        Collection<LocalSubscription> subscriptions4Queue = subscriptionEngine.getActiveLocalSubscribers(
                destination, protocolType, destinationType);

        if (subscriptions4Queue.isEmpty()) {
            // We don't have subscribers for this message
            // Handle orphaned slot created with this no subscription scenario for queue
            // clear all tracking when orphan slot situation
            messages.clear();
            SlotDeliveryWorkerManager.getInstance().stopDeliveryForDestination(storageQueue);
        } else {
            while (iterator.hasNext()) {

                try {

                    DeliverableAndesMetadata message = iterator.next();

                    int numOfCurrentMsgDeliverySchedules = 0;

                    boolean subscriberWithMatchingSelectorFound = true;

                    /**
                     * if message is addressed to queues, only ONE subscriber should
                     * get the message. Otherwise, loop for every subscriber
                     */
                    for (int j = 0; j < subscriptions4Queue.size(); j++) {

                        LocalSubscription localSubscription = MessageFlusher.getInstance().
                                findNextSubscriptionToSent(messageDeliveryInfo, subscriptions4Queue);
                        if (localSubscription.hasRoomToAcceptMessages()) {

                            if (!localSubscription.isMessageAcceptedBySelector(message)) {
                                // If this doesn't match a selector we skip sending the message
                                subscriberWithMatchingSelectorFound = false;
                                continue; // continue on to match selectors of other subscribers
                            }
                            if (log.isDebugEnabled()) {
                                log.debug("Scheduled to send id = " + message.getMessageID());
                            }

                            // In a re-queue for delivery scenario we need the correct destination. Hence setting
                            // it back correctly in AndesMetadata for durable subscription for topics
                            if (DestinationType.DURABLE_TOPIC == localSubscription.getDestinationType()) {
                                message.setDestination(localSubscription.getTargetQueue());
                            }

                            message.markAsScheduledToDeliver(localSubscription);
                            MessageFlusher.getInstance().deliverMessageAsynchronously(localSubscription, message);
                            numOfCurrentMsgDeliverySchedules++;

                            //for queue messages and durable topic messages (as they are now queue messages)
                            // we only send to one selected subscriber if it is a queue message
                            break;
                        }
                    }

                    if (numOfCurrentMsgDeliverySchedules == 1) {

                        iterator.remove();

                        if (log.isDebugEnabled()) {
                            log.debug("Removing Scheduled to send message from buffer. MsgId= " + message.getMessageID());
                        }

                        sentMessageCount++;

                    } else {

                        //if no subscriber has a matching selector, route message to DLC queue
                        if(!subscriberWithMatchingSelectorFound) {
                            Andes.getInstance().moveMessageToDeadLetterChannel(message, message.getDestination());
                            iterator.remove();
                        } else {
                            if (log.isDebugEnabled()) {
                                log.debug("All subscriptions for destination " + destination
                                        + " have max unacked " + "messages " + message.getDestination());
                            }
                            //if we continue message order will break
                            break;
                        }

                    }

                } catch (NoSuchElementException ex) {
                    // This exception can occur because the iterator of ConcurrentSkipListSet loads the at-the-time snapshot.
                    // Some records could be deleted by the time the iterator reaches them.
                    // However, this can only happen at the tail of the collection, not in middle, and it would cause the loop
                    // to blindly check for a batch of deleted records.
                    // Given this situation, this loop should break so the sendFlusher can re-trigger it.
                    // for tracing purposes can use this : log.warn("NoSuchElementException thrown",ex);
                    log.warn("NoSuchElementException thrown. ", ex);
                    break;
                }
            }
        }

        return sentMessageCount;
    }

}


text:
// Copyright (c) 2022 Xomega.Net. All rights reserved.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Windows.Controls;

namespace Xomega.Framework.Binding
{
    /// <summary>
    /// A class that provides binding for a ListView to the corresponding data list object.
    /// </summary>
    public class ListViewBinding : DataObjectBinding
    {
        /// <summary>
        ///  A static method to register list view context binding for ListView WPF element.
        /// </summary>
        public static void Register()
        {
            Register(typeof(ListView), delegate(object obj)
            {
                ListView listView = obj as ListView;
                return IsBindable(listView) ? new ListViewBinding(listView) : null;
            });
        }

        /// <summary>
        /// Constructs a new selector property binding for the given Selector element.
        /// </summary>
        /// <param name="listView">The selector element to be bound to the data property.</param>
        protected ListViewBinding(ListView listView) : base(listView)
        {
            listView.SelectionChanged += OnListViewSelectionChanged;
        }

        private void CleanupBindings(object sender, NotifyCollectionChangedEventArgs e)
        {
            ListView lv = element as ListView;
            for (int i=0; i < lv.Items.Count; i++)
                DataPropertyBinding.RemoveBindings(lv.ItemContainerGenerator.ContainerFromIndex(i));
        }

        /// <summary>
        /// Binds the framework element to the given data object.
        /// </summary>
        /// <param name="obj">The data object to bind the framework element to.</param>
        public override void BindTo(DataObject obj)
        {
            ListView lv = (ListView)element;
            if (obj is DataListObject lst)
            {
                lst.SelectionChanged -= OnListObjectSelectionChanged;
            }
            base.BindTo(obj); // assigns context
            OnListObjectSelectionChanged(context, EventArgs.Empty); // update current selection
            lst = obj as DataListObject;
            if (lst != null)
            {
                lst.SelectionChanged += OnListObjectSelectionChanged;
            }
            else CleanupBindings(element, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

            if (lv.ItemsSource is INotifyCollectionChanged oldSrc)
                oldSrc.CollectionChanged -= CleanupBindings;
            lv.ItemsSource = lst?.GetData();
            if (lv.ItemsSource is INotifyCollectionChanged newSrc)
                newSrc.CollectionChanged += CleanupBindings;
        }

        /// <summary>
        /// Remove any listeners when disposing
        /// </summary>
        public override void Dispose()
        {
            ListView listView = (ListView)element;
            listView.SelectionChanged -= OnListViewSelectionChanged;
            base.Dispose();
        }

        /// <summary>
        /// Handles selection update from the data list object by updating the list view selection
        /// </summary>
        private void OnListObjectSelectionChanged(object sender, EventArgs e)
        {
            ListView listView = element as ListView;
            if (PreventElementUpdate || !(sender is DataListObject listObj)) return;

            PreventModelUpdate = true;

            // update selection model for list view as needed
            if (DataListObject.SelectionModeSingle.Equals(listObj.RowSelectionMode))
                listView.SelectionMode = SelectionMode.Single;
            else if (DataListObject.SelectionModeMultiple.Equals(listObj.RowSelectionMode) &&
                     listView.SelectionMode == SelectionMode.Single)
                listView.SelectionMode = SelectionMode.Extended;

            // clear selection
            if (listView.SelectionMode == SelectionMode.Single)
                listView.SelectedItem = null;
            else listView.SelectedItems.Clear();

            // set selected item(s) from the list object
            foreach (DataRow r in listView.Items)
            {
                if (r.Selected)
                {
                    if (listView.SelectionMode == SelectionMode.Single)
                    {
                        listView.SelectedItem = r;
                        break;
                    }
                    else listView.SelectedItems.Add(r);
                }
            }
            PreventModelUpdate = false;
        }

        /// <summary>
        /// Handles selection update from the list view by updating selection in the data list object
        /// </summary>
        private void OnListViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListView listView = element as ListView;
            if (PreventModelUpdate || !(context is DataListObject listObj)) return;

            PreventElementUpdate = true;
            var selectedRows = new List<DataRow>();
            foreach (DataRow r in listView.SelectedItems)
                selectedRows.Add(r);
            listObj.SelectedRows = selectedRows;
            PreventElementUpdate = false;
        }
    }
}


text:
Tag.blueprint do
  name    { Sham.tag_name }
end


text:
namespace MicroBenchmarks.ServiceBus
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text;
    using BenchmarkDotNet.Attributes;
    using BenchmarkDotNet.Configs;
    using BenchmarkDotNet.Diagnosers;
    using BenchmarkDotNet.Exporters;
    using BenchmarkDotNet.Jobs;
    using Microsoft.Azure.Amqp;

    [Config(typeof(Config))]
    public class DataConversion
    {
        private IEnumerable<ReadOnlyMemory<byte>> data;

        private class Config : ManualConfig
        {
            public Config()
            {
                AddExporter(MarkdownExporter.GitHub);
                AddDiagnoser(MemoryDiagnoser.Default);
                AddJob(Job.Default.WithInvocationCount(320000));
            }
        }

        [Params(1, 2, 4, 8, 16, 32, 64)]
        public int Elements { get; set; }

        [IterationSetup]
        public void Setup()
        {
            data = Enumerable.Range(0, Elements)
                .Select(i => (ReadOnlyMemory<byte>) Encoding.UTF8.GetBytes($"Hello World {i}"));
        }

        [Benchmark(Baseline = true)]
        public ArraySegment<byte>[] ToArray()
        {
            return ConvertBefore(data);
        }

        static ArraySegment<byte>[] ConvertBefore(IEnumerable<ReadOnlyMemory<byte>> allData)
        {
            return allData.Select(data => new ArraySegment<byte>(data.IsEmpty ? Array.Empty<byte>() : data.ToArray())).ToArray();
        }

        [Benchmark]
        public ArraySegment<byte>[] Marshal()
        {
            return ConvertAfter(data);
        }

        static ArraySegment<byte>[] ConvertAfter(IEnumerable<ReadOnlyMemory<byte>> allData)
        {
            return allData.Select(data =>
            {
                ArraySegment<byte> segment;
                if (!data.IsEmpty)
                {
                    if (!MemoryMarshal.TryGetArray(data, out segment))
                    {
                        segment = new ArraySegment<byte>(data.ToArray());
                    }
                }
                else
                {
                    segment = new ArraySegment<byte>(Array.Empty<byte>());
                }

                return segment;
            }).ToArray();
        }
    }
}


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

import { AshaWorkerPaymentRulesModel } from '../../model/asha-worker-payment-rules-model';

import { AshaWorkersDetailsService } from '../../service/asha-workers-details.service';
import { ActionOutcomeMessageModel } from '../../model/action-outcome-message-model';
import { DataService} from '../../service/share-data.service'
import { ErrorHandler } from '../../error.component'
import { ActivityRuleModel }  from '../../model/activity-rule-model'
declare var jQuery: any;

@Component({
    selector: 'manage-activity-payment',
    templateUrl: './manage-activity-payment.component.html',
    styleUrls: ['./manage-activity-payment.component.scss'],
    providers: [AshaWorkersDetailsService]
})
export class ManageActivityPaymentConfiguration implements OnInit{
    constructor(private route: ActivatedRoute, private ashaWorkersDetailsService: AshaWorkersDetailsService,private dataService:DataService,private errorHandler:ErrorHandler){

    }

    ruleList : ActivityRuleModel[];
   ngOnInit(){
        this.activityPaymentRuleList();
    }

    activityPaymentRuleList(){
        this.dataService.setLoading(true);
        this.ashaWorkersDetailsService.activityPaymentRuleList()
        .subscribe(res =>{
            this.dataService.setLoading(false);
            this.ruleList = res;
        },err=>{
            this.errorHandler.handleError(err);
        });
    }

}


text:
<?php

namespace Recca0120\Upload;

use Illuminate\Support\ServiceProvider;

class UploadServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot()
    {
        if ($this->app->runningInConsole() === true) {
            $this->handlePublishes();
        }
    }

    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../config/upload.php', 'upload');

        $this->app->singleton(Filesystem::class, Filesystem::class);
        $this->app->singleton(UploadManager::class, function ($app) {
            return new UploadManager($app, $app['request'], $app->make(Filesystem::class));
        });
    }

    /**
     * handle publishes.
     */
    protected function handlePublishes()
    {
        $this->publishes([
            __DIR__.'/../config/upload.php' => config_path('upload.php'),
        ], 'config');
    }
}


text:
module.exports = (function(){
  "use strict";

  var ParseError = require("./ParseError");
  var CSSParser = require("./CSSParser");
  var voidHtmlElements = require("./voidHtmlElements");

  // ### Character Entity Parsing
  //
  // We currently only parse the most common named character entities.
  var CHARACTER_ENTITY_REFS = {
    lt: "<",
    gt: ">",
    apos: "'",
    quot: '"',
    amp: "&"
  };

  // HTML attribute parsing rules are based on
  // http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#attr-data
  // -> ref http://www.w3.org/TR/2011/WD-html5-20110525/infrastructure.html#xml-compatible
  //    -> ref http://www.w3.org/TR/REC-xml/#NT-NameChar
  // note: this lacks the final \\u10000-\\uEFFFF in the startchar set, because JavaScript
  //       cannot cope with unciode characters with points over 0xFFFF.
  var attributeNameStartChar = "A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
  var nameStartChar = new RegExp("[" + attributeNameStartChar + "]");
  var attributeNameChar = attributeNameStartChar + "0-9\\-\\.\\u00B7\\u0300-\\u036F\\u203F-\\u2040:";
  var nameChar = new RegExp("[" + attributeNameChar + "]");

  //Define a property checker for https page
  var checkMixedContent = require("./checkMixedContent").mixedContent;

  //Define activeContent with tag-attribute pairs
  function isActiveContent (tagName, attrName) {
    if (attrName === "href") {
      return ["link"].indexOf(tagName) > -1;
    }
    if (attrName === "src") {
      return ["script", "iframe"].indexOf(tagName) > -1;
    }
    if (attrName === "data") {
      return ["object"].indexOf(tagName) > -1;
    }
    return false;
  }

  // the current active omittable html Element
  var activeTagNode = false;

  // the parent html Element for optional closing tag tags
  var parentTagNode = false;

  // 'foresee' if there is no more content in the parent element, and the
  // parent element is not an a element in the case of activeTag is a p element.
  function isNextTagParent(stream, parentTagName) {
    return stream.findNext(/<\/([\w\-]+)\s*>/, 1) === parentTagName;
  }

  // 'foresee' if the next tag is a close tag
  function isNextCloseTag(stream) {
    return stream.findNext(/<\/([\w\-]+)\s*>/, 1);
  }

  // Check exception for Tag omission rules: for p tag, if there is no more
  // content in the parent element and the parent element is not an a element.
  function allowsOmmitedEndTag(parentTagName, tagName) {
    if (tagName === "p") {
      return ["a"].indexOf(parentTagName) > -1;
    }
    return false;
  }

  function HTMLParser(stream, domBuilder) {
    this.warnings = [];
    this.stream = stream;
    this.domBuilder = domBuilder;
    this.cssParser = new CSSParser(stream, domBuilder, this.warnings);
  }

  // `replaceEntityRefs()` will replace named character entity references
  // (e.g. `<`) in the given text string and return the result. If an
  // entity name is unrecognized, don't replace it at all. Writing HTML
  // would be surprisingly painful without this forgiving behavior.
  //
  // This function does not currently replace numeric character entity
  // references (e.g., ` `).
  function replaceEntityRefs(text) {
    return text.replace(/&([A-Za-z]+);/g, function(ref, name) {
      name = name.toLowerCase();
      if (name in CHARACTER_ENTITY_REFS)
        return CHARACTER_ENTITY_REFS[name];
      return ref;
    });
  };

  HTMLParser.prototype = {
    // since SVG requires a slightly different code path,
    // we need to track whether we're in HTML or SVG mode.
    parsingSVG: false,

    // For SVG DOM elements, we need to know the SVG namespace.
    svgNameSpace: "http://www.w3.org/2000/svg",

    // HTML5 documents have a special doctype that we must use
    html5Doctype: "<!DOCTYPE html>",

    // Void HTML elements are the ones that don't need to have a closing tag.
    voidHtmlElements: voidHtmlElements,

    // Tag Omission Rules, based on the rules on optional tags as outlined in
    // http://www.w3.org/TR/html5/syntax.html#optional-tags

    // HTML elements that with omittable close tag
    omittableCloseTagHtmlElements: ["p", "li", "td", "th"],

    // HTML elements that paired with omittable close tag list
    omittableCloseTags: {
      "p": ["address", "article", "aside", "blockquote", "dir", "div", "dl",
            "fieldset", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6",
            "header", "hgroup", "hr", "main", "nav", "ol", "p", "pre",
            "section", "table", "ul"],
      "th": ["th", "td"],
      "td": ["th", "td"],
      "li": ["li"]
    },

    // We keep a list of all valid HTML5 elements.
    htmlElements: ["a", "abbr", "address", "area", "article", "aside",
                   "audio", "b", "base", "bdi", "bdo", "bgsound", "blink",
                   "blockquote", "body", "br", "button", "canvas", "caption",
                   "cite", "code", "col", "colgroup", "command", "datalist",
                   "dd", "del", "details", "dfn", "div", "dl", "dt", "em",
                   "embed", "fieldset", "figcaption", "figure", "footer",
                   "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5",
                   "h6", "head", "header", "hgroup", "hr", "html", "i",
                   "iframe", "img", "input", "ins", "kbd", "keygen", "label",
                   "legend", "li", "link", "main", "map", "mark", "marquee", "menu",
                   "meta", "meter", "nav", "nobr", "noscript", "object", "ol",
                   "optgroup", "option", "output", "p", "param", "pre",
                   "progress", "q", "rp", "rt", "ruby", "samp", "script",
                   "section", "select", "small", "source", "spacer", "span",
                   "strong", "style", "sub", "summary", "sup", "svg", "table",
                   "tbody", "td", "textarea", "tfoot", "th", "thead", "time",
                   "title", "tr", "track", "u", "ul", "var", "video", "wbr"],

    // HTML5 allows SVG elements
    svgElements:  ["a", "altglyph", "altglyphdef", "altglyphitem", "animate",
                   "animatecolor", "animatemotion", "animatetransform", "circle",
                   "clippath", "color-profile", "cursor", "defs", "desc",
                   "ellipse", "feblend", "fecolormatrix", "fecomponenttransfer",
                   "fecomposite", "feconvolvematrix", "fediffuselighting",
                   "fedisplacementmap", "fedistantlight", "feflood", "fefunca",
                   "fefuncb", "fefuncg", "fefuncr", "fegaussianblur", "feimage",
                   "femerge", "femergenode", "femorphology", "feoffset",
                   "fepointlight", "fespecularlighting", "fespotlight",
                   "fetile", "feturbulence", "filter", "font", "font-face",
                   "font-face-format", "font-face-name", "font-face-src",
                   "font-face-uri", "foreignobject", "g", "glyph", "glyphref",
                   "hkern", "image", "line", "lineargradient", "marker", "mask",
                   "metadata", "missing-glyph", "mpath", "path", "pattern",
                   "polygon", "polyline", "radialgradient", "rect", "script",
                   "set", "stop", "style", "svg", "switch", "symbol", "text",
                   "textpath", "title", "tref", "tspan", "use", "view", "vkern"],

    // HTML5 doesn't use namespaces, but actually it does. These are supported:
    attributeNamespaces: ["xlink", "xml"],

    // We also keep a list of HTML elements that are now obsolete, but
    // may still be encountered in the wild on popular sites.
    obsoleteHtmlElements: ["acronym", "applet", "basefont", "big", "center",
                           "dir", "font", "isindex", "listing", "noframes",
                           "plaintext", "s", "strike", "tt", "xmp"],

    webComponentElements: ["template", "shadow", "content"],

    // This is a helper function to determine whether a given string
    // is a custom HTML element as per Custom Elements spec
    // (see http://www.w3.org/TR/2013/WD-custom-elements-20130514/#terminology).
    _isCustomElement: function(tagName) {
      return tagName.search(/^[\w\d]+-[\w\d]+$/) > -1;
    },

    // This is a helper function to determine whether a given string
    // is a legal HTML5 element tag.
    _knownHTMLElement: function(tagName) {
      return this.voidHtmlElements.indexOf(tagName) > -1 ||
              this.htmlElements.indexOf(tagName) > -1 ||
              this.obsoleteHtmlElements.indexOf(tagName) > -1 ||
              this.webComponentElements.indexOf(tagName) > -1;
    },

    // This is a helper function to determine whether a given string
    // is a legal SVG element tag.
    _knownSVGElement: function(tagName) {
      return this.svgElements.indexOf(tagName) > -1;
    },

    // This is a helper function to determine whether a given string
    // is a void HTML element tag.
    _knownVoidHTMLElement: function(tagName) {
      return this.voidHtmlElements.indexOf(tagName) > -1;
    },

    // This is a helper function to determine whether a given string
    // is a HTML element tag which can optional omit its close tag.
    _knownOmittableCloseTagHtmlElement: function(tagName) {
      return this.omittableCloseTagHtmlElements.indexOf(tagName) > -1;
    },

    // This is a helper function to determine whether a given string
    // is in the list of ommittableCloseTags which enable an active tag omit its close tag.
    _knownOmittableCloseTags: function(activeTagName, foundTagName) {
      return this.omittableCloseTags[activeTagName].indexOf(foundTagName) > -1;
    },

    // This is a helper function to determine whether an attribute namespace
    // is supposed in the HTML spec. Currently these are "xlink" and "xml".
    _supportedAttributeNameSpace: function(ns) {
      return this.attributeNamespaces.indexOf(ns) !== -1;
    },

    // #### The HTML Master Parse Function
    //
    // The HTML master parse function works the same as the CSS
    // parser: it takes the token stream and will try to parse
    // the content as a sequence of HTML elements.
    //
    // Any parse errors along the way will result in the code
    // throwing a `ParseError`.
    parse: function() {
      // First we check to see if the beginning of our stream is
      // an HTML5 doctype tag. We're currently quite strict and don't
      // parse XHTML or other doctypes.
      if (this.stream.match(this.html5Doctype, true, true))
        this.domBuilder.fragment.node.parseInfo = {
          doctype: {
            start: 0,
            end: this.stream.pos
          }
        };
      // Next, we parse "tag soup", creating text nodes and diving into
      // tags as we find them.
      while (!this.stream.end()) {
        if (this.stream.peek() == '<') {
          this._buildTextNode();
          this._parseStartTag();
        } else
          this.stream.next();
      }

      this._buildTextNode();

      // At the end, it's possible we're left with an open tag, so
      // we test for that.
      if (this.domBuilder.currentNode != this.domBuilder.fragment.node)
        throw new ParseError("UNCLOSED_TAG", this);

      return {
        warnings: (this.warnings.length > 0 ? this.warnings : false)
      };
    },

    // This is a helper to build a DOM text node.
    _buildTextNode: function() {
      var token = this.stream.makeToken();
      if (token) {
        this.domBuilder.text(replaceEntityRefs(token.value), token.interval);
      }
    },

    // #### HTML Tag Parsing
    //
    // This is the entry point for parsing the beginning of an HTML tag.
    // It assumes the stream is on a `<` character.
    _parseStartTag: function() {
      if (this.stream.next() != '<')
        throw new Error('assertion failed, expected to be on "<"');

      if (this.stream.match('!--', true)) {
        this.domBuilder.pushContext("text", this.stream.pos);
        this._parseComment();
        this.domBuilder.pushContext("html", this.stream.pos);
        return;
      }

      this.stream.eat(/\//);
      this.stream.eatWhile(/[\w\d-]/);
      var token = this.stream.makeToken();
      var tagName = token.value.slice(1).toLowerCase();

      if (tagName === "svg")
        this.parsingSVG = true;

      // If the character after the `<` is a `/`, we're on a closing tag.
      // We want to report useful errors about whether the tag is unexpected
      // or doesn't match with the most recent opening tag.
      if (tagName[0] == '/') {
        activeTagNode = false;
        var closeTagName = tagName.slice(1).toLowerCase();
        if (closeTagName === "svg")
          this.parsingSVG = false;
        if (this._knownVoidHTMLElement(closeTagName))
          throw new ParseError("CLOSE_TAG_FOR_VOID_ELEMENT", this,
                               closeTagName, token);
        if (!this.domBuilder.currentNode.parseInfo)
          throw new ParseError("UNEXPECTED_CLOSE_TAG", this, closeTagName,
                               token);
        this.domBuilder.currentNode.parseInfo.closeTag = {
          start: token.interval.start
        };
        var openTagName = this.domBuilder.currentNode.nodeName.toLowerCase();
        if (closeTagName != openTagName)
          throw new ParseError("MISMATCHED_CLOSE_TAG", this, openTagName,
                               closeTagName, token);
        this._parseEndCloseTag();
      }

      else {
        if (tagName) {
          var badSVG = this.parsingSVG && !this._knownSVGElement(tagName);
          var badHTML = !this.parsingSVG && !this._knownHTMLElement(tagName) && !this._isCustomElement(tagName);
          if (badSVG || badHTML) {
            throw new ParseError("INVALID_TAG_NAME", tagName, token);
          }
        }
        else {
          throw new ParseError("INVALID_TAG_NAME", tagName, token);
        }

        var parseInfo = { openTag: { start: token.interval.start }};
        var nameSpace = (this.parsingSVG ? this.svgNameSpace : undefined);

        // If the preceding tag and the active tag is omittableCloseTag pairs,
        // we tell our DOM builder that we're done.
        if (activeTagNode && parentTagNode != this.domBuilder.fragment.node){
          var activeTagName = activeTagNode.nodeName.toLowerCase();
          if(this._knownOmittableCloseTags(activeTagName, tagName)) {
            this.domBuilder.popElement();
          }
        }
        // Store currentNode as the parentTagNode
        parentTagNode = this.domBuilder.currentNode;
        this.domBuilder.pushElement(tagName, parseInfo, nameSpace);

        if (!this.stream.end())
          this._parseEndOpenTag(tagName);
      }
    },
    // This helper parses HTML comments. It assumes the stream has just
    // passed the beginning `<!--` of an HTML comment.
    _parseComment: function() {
      var token;
      while (!this.stream.end()) {
        if (this.stream.match('-->', true)) {
          token = this.stream.makeToken();
          this.domBuilder.comment(token.value.slice(4, -3), token.interval);
          return;
        }
        this.stream.next();
      }
      token = this.stream.makeToken();
      throw new ParseError("UNTERMINATED_COMMENT", token);
    },
    // This helper parses CDATA content, which should be treated as raw text,
    // rather than being parsed for markup. It assumes the stream has just
    // passed the beginning `<tagname` of an HTML element.
    _parseCDATA: function(tagname) {
      var token,
           matchString = '</'+tagname+'>',
           text,
           textInterval = { start: 0, end: 0 },
           openTagEnd = this.domBuilder.currentNode.parseInfo.openTag.end,
           closeTagInterval;

      this.stream.makeToken();
      while (!this.stream.end()) {
        if (this.stream.match(matchString, true)) {
          token = this.stream.makeToken();
          text = token.value.slice(0, -matchString.length);
          closeTagInterval = {
            start: openTagEnd + text.length,
            end: token.interval.end
          };
          this.domBuilder.currentNode.parseInfo.closeTag = closeTagInterval;
          textInterval.start = token.interval.start;
          textInterval.end = token.interval.end - (closeTagInterval.end - closeTagInterval.start);
          this.domBuilder.text(text, textInterval);
          this.domBuilder.popElement();
          return;
        }
        this.stream.next();
      }
      throw new ParseError("UNCLOSED_TAG", this);
    },
    // This helper function checks if the current tag contains an attribute
    containsAttribute: function (stream) {
      return stream.eat(nameStartChar);
    },
    // This helper function parses the end of a closing tag. It expects
    // the stream to be right after the end of the closing tag's tag
    // name.
    _parseEndCloseTag: function() {
      this.stream.eatSpace();
      if (this.stream.next() != '>') {
        if(this.containsAttribute(this.stream)) {
          throw new ParseError("ATTRIBUTE_IN_CLOSING_TAG", this);
        } else {
          throw new ParseError("UNTERMINATED_CLOSE_TAG", this);
        }
      }
      var end = this.stream.makeToken().interval.end;
      this.domBuilder.currentNode.parseInfo.closeTag.end = end;
      this.domBuilder.popElement();
    },
    // This helper function parses the rest of an opening tag after
    // its tag name, looking for `attribute="value"` data until a
    // `>` is encountered.
    _parseEndOpenTag: function(tagName) {
      var tagMark = this.stream.pos,
          startMark = this.stream.pos;

      while (!this.stream.end()) {

        if (this.containsAttribute(this.stream)) {
          if (this.stream.peek !== "=") {
            this.stream.eatWhile(nameChar);
          }
          this._parseAttribute(tagName);
        }

        else if (this.stream.eatSpace()) {
          this.stream.makeToken();
          startMark = this.stream.pos;
        }

        else if (this.stream.peek() == '>' || this.stream.match("/>")) {
          var selfClosing = this.stream.match("/>", true);
          if (selfClosing) {
            if (!this.parsingSVG && !this._knownVoidHTMLElement(tagName))
              throw new ParseError("SELF_CLOSING_NON_VOID_ELEMENT", this,
                                   tagName);
          } else
            this.stream.next();
          var end = this.stream.makeToken().interval.end;
          this.domBuilder.currentNode.parseInfo.openTag.end = end;

          // If the opening tag represents a void element, there will not be
          // a closing element, so we tell our DOM builder that we're done.
          if (tagName && ((selfClosing && this._knownSVGElement(tagName)) || this._knownVoidHTMLElement(tagName)))
            this.domBuilder.popElement();

          // If the open tag represents a optional-omit-close-tag element, there may be
          // an optional closing element, so we save the currentNode into activeTag for next step check.
          activeTagNode = false;
          if (tagName && this._knownOmittableCloseTagHtmlElement(tagName)){
            activeTagNode = this.domBuilder.currentNode;
          }

          // If the opening tag represents a `<style>` element, we hand
          // off parsing to our CSS parser.
          if (!this.stream.end() && tagName === "style") {
            this.domBuilder.pushContext("css", this.stream.pos);
            var cssBlock = this.cssParser.parse();
            this.domBuilder.pushContext("html", this.stream.pos);
            this.domBuilder.text(cssBlock.value, cssBlock.parseInfo);
          }

          // If the opening tag represents a `<textarea>` element, we need
          // to parse all its contents as CDATA (unparsed character data)
          if (tagName && tagName === "script") {
            this.domBuilder.pushContext("javascript", this.stream.pos);
            this._parseCDATA("script");
            this.domBuilder.pushContext("html", this.stream.pos);
          }

          // If the opening tag represents a `<textarea>` element, we need
          // to parse all its contents as CDATA (unparsed character data)
          if (tagName && tagName === "textarea") {
            this.domBuilder.pushContext("text", this.stream.pos);
            this._parseCDATA("textarea");
            this.domBuilder.pushContext("html", this.stream.pos);
          }

          // if there is no more content in the parent element, we tell DOM builder that we're done.
          if(parentTagNode && parentTagNode != this.domBuilder.fragment.node) {
            var parentTagName = parentTagNode.nodeName.toLowerCase(),
                nextIsParent = isNextTagParent(this.stream, parentTagName),
                needsEndTag = !allowsOmmitedEndTag(parentTagName, tagName),
                optionalEndTag = this._knownOmittableCloseTagHtmlElement(parentTagName),
                nextTagCloses = isNextCloseTag(this.stream);
            if(nextIsParent && (needsEndTag || (optionalEndTag && nextTagCloses))) {
              if(this._knownOmittableCloseTagHtmlElement(tagName)) {
                this.domBuilder.popElement();
              }
            }
          }
          return;
        }

        // error cases: bad attribute name, or unclosed tag
        else {
          this.stream.eatWhile(/[^'"\s=<>]/);
          var attrToken = this.stream.makeToken();
          if (!attrToken) {
            this.stream.tokenStart = tagMark;
            attrToken = this.stream.makeToken();
            var peek = this.stream.peek();
            if(peek === "'" || peek === '"') {
              this.stream.next();
              this.stream.eatWhile(new RegExp("[^"+peek+"]"));
              this.stream.next();
              var token = this.stream.makeToken();
              throw new ParseError("UNBOUND_ATTRIBUTE_VALUE", this, token);
            }
            throw new ParseError("UNTERMINATED_OPEN_TAG", this);
          }
          attrToken.interval.start = startMark;
          throw new ParseError("INVALID_ATTR_NAME", this, attrToken);
        }
      }
    },
    // This helper function parses an HTML tag attribute. It expects
    // the stream to be right after the end of an attribute name.
    _parseAttribute: function(tagName) {
      var nameTok = this.stream.makeToken();
      nameTok.value = nameTok.value.toLowerCase();
      this.stream.eatSpace();
      // If the character after the attribute name is a `=`, then we
      // look for an attribute value; otherwise, this is a boolean
      // attribute.
      if (this.stream.peek() == '=') {
        this.stream.next();

        if(nameTok.value.indexOf(":") !== -1) {
          var parts = nameTok.value.split(":");
          if(parts.length > 2) {
            throw new ParseError("MULTIPLE_ATTR_NAMESPACES", this, nameTok);
          }
          var nameSpace = parts[0],
              attributeName = parts[1];
          if(!this._supportedAttributeNameSpace(nameSpace)) {
            throw new ParseError("UNSUPPORTED_ATTR_NAMESPACE", this, nameTok);
          }
        }

        // Currently, we only support quoted attribute values, even
        // though the HTML5 standard allows them to sometimes go unquoted.
        this.stream.eatSpace();
        this.stream.makeToken();
        var quoteType = this.stream.next();
        if (quoteType !== '"' && quoteType !== "'") {
          throw new ParseError("UNQUOTED_ATTR_VALUE", this);
        }
        if (quoteType === '"') {
          this.stream.eatWhile(/[^"]/);
        } else {
          this.stream.eatWhile(/[^']/);
        }
        if (this.stream.next() !== quoteType) {
          throw new ParseError("UNTERMINATED_ATTR_VALUE", this, nameTok);
        }
        var valueTok = this.stream.makeToken();

        //Add a new validator to check if there is a http link in a https page
        if (checkMixedContent && valueTok.value.match(/http:/) && isActiveContent(tagName, nameTok.value)) {
          this.warnings.push(
            new ParseError("HTTP_LINK_FROM_HTTPS_PAGE", this, nameTok, valueTok)
          );
        }

        var unquotedValue = replaceEntityRefs(valueTok.value.slice(1, -1));
        this.domBuilder.attribute(nameTok.value, unquotedValue, {
          name: nameTok.interval,
          value: valueTok.interval
        });
      } else {
        this.stream.makeToken();
        this.domBuilder.attribute(nameTok.value, '', {
          name: nameTok.interval
        });
      }
    }
  };

  HTMLParser.replaceEntityRefs = replaceEntityRefs;

  return HTMLParser;
}());


text:
import os
import re
import imp
import sys

def _import_protocol(base_path, protocol_module_name):
    """
    Import a module from a base path, used to import protocol modules.

    This implementation is derived from the __import__ example here:
        https://docs.python.org/2/library/imp.html
    """

    # Try to return the module if it's been loaded already
    try:
        return sys.modules[protocol_module_name]
    except KeyError:
        pass

    # If any of the following calls raises an exception,
    # there's a problem we can't handle -- let the caller handle it.
    #
    fp, pathname, description = imp.find_module(protocol_module_name, [base_path])
    try:
        return imp.load_module(protocol_module_name, fp, pathname, description)
    finally:
        # Since we may exit via an exception, close fp explicitly.
        if fp:
            fp.close()

def list_all(base_path=None):
    """
    Returns a list of the current protocol version file names in the versions module sorted by name.
    """
    if base_path is None:
        base_path = os.path.dirname(__file__)
    pattern = re.compile('.*protocol[0-9]+.py$')
    files = [ f for f in os.listdir(base_path) \
        if pattern.match(f) ]
    files.sort()
    return files

def latest():
    """
    Import the latest protocol version in the versions module (directory)
    """
    # Find matchng protocol version files
    base_path = os.path.dirname(__file__)
    files = list_all(base_path)

    # Sort using version number, take latest
    latest_version = files[-1]

    # Convert file to module name
    module_name = latest_version.split('.')[0]

    # Perform the import
    return _import_protocol(base_path, module_name)

def build(build_version):
    """
    Get the module for a specific build version
    """
    base_path = os.path.dirname(__file__)
    return _import_protocol(base_path, 'protocol{0:05d}'.format(build_version))


text:
module ActsAsTaggableOn::Taggable
  module Core
    def self.included(base)
      base.send :include, ActsAsTaggableOn::Taggable::Core::InstanceMethods
      base.extend ActsAsTaggableOn::Taggable::Core::ClassMethods

      base.class_eval do
        attr_writer :custom_contexts
        after_save :save_tags
      end

      base.initialize_acts_as_taggable_on_core
    end

    module ClassMethods
      def initialize_acts_as_taggable_on_core
        tag_types.map(&:to_s).each do |tags_type|
          tag_type         = tags_type.to_s.singularize
          context_taggings = "#{tag_type}_taggings".to_sym
          context_tags     = tags_type.to_sym

          class_eval do
            has_many context_taggings, :as => :taggable, :dependent => :destroy, :include => :tag, :class_name => "ActsAsTaggableOn::Tagging",
            :conditions => ["#{ActsAsTaggableOn::Tagging.table_name}.tag_id = #{ActsAsTaggableOn::Tag.table_name}.#{ActsAsTaggableOn::Tag.primary_key} AND #{ActsAsTaggableOn::Tagging.table_name}.context = ?", tags_type]
            has_many context_tags, :through => context_taggings, :source => :tag, :class_name => "ActsAsTaggableOn::Tag"
          end

          class_eval %(
            def #{tag_type}_list
              tag_list_on('#{tags_type}')
            end

            def #{tag_type}_list=(new_tags)
              set_tag_list_on('#{tags_type}', new_tags)
            end

            def all_#{tags_type}_list
              all_tags_list_on('#{tags_type}')
            end
          )
        end
      end

      def acts_as_taggable_on(*args)
        super(*args)
        initialize_acts_as_taggable_on_core
      end

      # all column names are necessary for PostgreSQL group clause
      def grouped_column_names_for(object)
        object.column_names.map { |column| "#{object.table_name}.#{column}" }.join(", ")
      end

      ##
      # Return a scope of objects that are tagged with the specified tags.
      #
      # @param tags The tags that we want to query for
      # @param [Hash] options A hash of options to alter you query:
      #                       * <tt>:exclude</tt> - if set to true, return objects that are *NOT* tagged with the specified tags
      #                       * <tt>:any</tt> - if set to true, return objects that are tagged with *ANY* of the specified tags
      #                       * <tt>:match_all</tt> - if set to true, return objects that are *ONLY* tagged with the specified tags
      #
      # Example:
      #   User.tagged_with("awesome", "cool")                     # Users that are tagged with awesome and cool
      #   User.tagged_with("awesome", "cool", :exclude => true)   # Users that are not tagged with awesome or cool
      #   User.tagged_with("awesome", "cool", :any => true)       # Users that are tagged with awesome or cool
      #   User.tagged_with("awesome", "cool", :match_all => true) # Users that are tagged with just awesome and cool
      def tagged_with(tags, options = {})
        tag_list = ActsAsTaggableOn::TagList.from(tags)
        empty_result = scoped(:conditions => "1 = 0")

        return empty_result if tag_list.empty?

        joins = []
        conditions = []

        context = options.delete(:on)
        alias_base_name = undecorated_table_name.gsub('.','_')

        if options.delete(:exclude)
          tags_conditions = tag_list.map { |t| sanitize_sql(["#{ActsAsTaggableOn::Tag.table_name}.name #{like_operator} ?", t]) }.join(" OR ")
          conditions << "#{table_name}.#{primary_key} NOT IN (SELECT #{ActsAsTaggableOn::Tagging.table_name}.taggable_id FROM #{ActsAsTaggableOn::Tagging.table_name} JOIN #{ActsAsTaggableOn::Tag.table_name} ON #{ActsAsTaggableOn::Tagging.table_name}.tag_id = #{ActsAsTaggableOn::Tag.table_name}.#{ActsAsTaggableOn::Tag.primary_key} AND (#{tags_conditions}) WHERE #{ActsAsTaggableOn::Tagging.table_name}.taggable_type = #{quote_value(base_class.name)})"

        elsif options.delete(:any)
          # get tags, drop out if nothing returned (we need at least one)
          tags = ActsAsTaggableOn::Tag.named_any(tag_list)
          return scoped(:conditions => "1 = 0") unless tags.length > 0

          # setup taggings alias so we can chain, ex: items_locations_taggings_awesome_cool_123
          # avoid ambiguous column name
          taggings_context = context ? "_#{context}" : ''

          #TODO: fix alias to be smaller
          taggings_alias   = "#{alias_base_name}#{taggings_context}_taggings_#{tags.map(&:safe_name).join('_')}_#{rand(1024)}"

          tagging_join  = "JOIN #{ActsAsTaggableOn::Tagging.table_name} #{taggings_alias}" +
                          "  ON #{taggings_alias}.taggable_id = \"#{table_name}\".#{primary_key}" +
                          " AND #{taggings_alias}.taggable_type = #{quote_value(base_class.name)}"
          tagging_join << " AND " + sanitize_sql(["#{taggings_alias}.context = ?", context.to_s]) if context

          # don't need to sanitize sql, map all ids and join with OR logic
          conditions << tags.map { |t| "#{taggings_alias}.tag_id = #{t.id}" }.join(" OR ")
          select_clause = "DISTINCT  \"#{table_name}\".*" unless context and tag_types.one?

          joins << tagging_join

        else
          tags = ActsAsTaggableOn::Tag.named_any(tag_list)
          return empty_result unless tags.length == tag_list.length

          tags.each do |tag|
            prefix   = "#{tag.safe_name}_#{rand(1024)}"

            taggings_alias = "#{alias_base_name}_taggings_#{prefix}"

            tagging_join  = "JOIN #{ActsAsTaggableOn::Tagging.table_name} #{taggings_alias}" +
                            "  ON #{taggings_alias}.taggable_id = \"#{table_name}\".#{primary_key}" +
                            " AND #{taggings_alias}.taggable_type = #{quote_value(base_class.name)}" +
                            " AND #{taggings_alias}.tag_id = #{tag.id}"
            tagging_join << " AND " + sanitize_sql(["#{taggings_alias}.context = ?", context.to_s]) if context

            joins << tagging_join
          end
        end

        taggings_alias, tags_alias = "#{alias_base_name}_taggings_group", "#{alias_base_name}_tags_group"

        if options.delete(:match_all)
          joins << "LEFT OUTER JOIN #{ActsAsTaggableOn::Tagging.table_name} #{taggings_alias}" +
                   "  ON #{taggings_alias}.taggable_id = \"#{table_name}\".#{primary_key}" +
                   " AND #{taggings_alias}.taggable_type = #{quote_value(base_class.name)}"

          group_columns = ActsAsTaggableOn::Tag.using_postgresql? ? grouped_column_names_for(self) : "#{table_name}.#{primary_key}"
          group = "#{group_columns} HAVING COUNT(#{taggings_alias}.taggable_id) = #{tags.size}"
        end

        scoped(:select     => select_clause,
               :joins      => joins.join(" "),
               :group      => group,
               :conditions => conditions.join(" AND "),
               :order      => options[:order],
               :readonly   => false)
      end

      def is_taggable?
        true
      end
    end

    module InstanceMethods
      # all column names are necessary for PostgreSQL group clause
      def grouped_column_names_for(object)
        self.class.grouped_column_names_for(object)
      end

      def custom_contexts
        @custom_contexts ||= []
      end

      def is_taggable?
        self.class.is_taggable?
      end

      def add_custom_context(value)
        custom_contexts << value.to_s unless custom_contexts.include?(value.to_s) or self.class.tag_types.map(&:to_s).include?(value.to_s)
      end

      def cached_tag_list_on(context)
        self["cached_#{context.to_s.singularize}_list"]
      end

      def tag_list_cache_set_on(context)
        variable_name = "@#{context.to_s.singularize}_list"
        !instance_variable_get(variable_name).nil?
      end

      def tag_list_cache_on(context)
        variable_name = "@#{context.to_s.singularize}_list"
        instance_variable_get(variable_name) || instance_variable_set(variable_name, ActsAsTaggableOn::TagList.new(tags_on(context).map(&:name)))
      end

      def tag_list_on(context)
        add_custom_context(context)
        tag_list_cache_on(context)
      end

      def all_tags_list_on(context)
        variable_name = "@all_#{context.to_s.singularize}_list"
        return instance_variable_get(variable_name) if instance_variable_get(variable_name)

        instance_variable_set(variable_name, ActsAsTaggableOn::TagList.new(all_tags_on(context).map(&:name)).freeze)
      end

      ##
      # Returns all tags of a given context
      def all_tags_on(context)
        tag_table_name = ActsAsTaggableOn::Tag.table_name
        tagging_table_name = ActsAsTaggableOn::Tagging.table_name

        opts  =  ["#{tagging_table_name}.context = ?", context.to_s]
        scope = base_tags.where(opts)

        if ActsAsTaggableOn::Tag.using_postgresql?
          group_columns = grouped_column_names_for(ActsAsTaggableOn::Tag)
          scope = scope.order("max(#{tagging_table_name}.created_at)").group(group_columns)
        else
          scope = scope.group("#{ActsAsTaggableOn::Tag.table_name}.#{ActsAsTaggableOn::Tag.primary_key}")
        end

        scope.all
      end

      ##
      # Returns all tags that are not owned of a given context
      def tags_on(context)
        base_tags.where(["#{ActsAsTaggableOn::Tagging.table_name}.context = ? AND #{ActsAsTaggableOn::Tagging.table_name}.tagger_id IS NULL", context.to_s]).all
      end

      def set_tag_list_on(context, new_list)
        add_custom_context(context)

        variable_name = "@#{context.to_s.singularize}_list"
        instance_variable_set(variable_name, ActsAsTaggableOn::TagList.from(new_list))
      end

      def tagging_contexts
        custom_contexts + self.class.tag_types.map(&:to_s)
      end

      def reload(*args)
        self.class.tag_types.each do |context|
          instance_variable_set("@#{context.to_s.singularize}_list", nil)
          instance_variable_set("@all_#{context.to_s.singularize}_list", nil)
        end

        super(*args)
      end

      def save_tags
        tagging_contexts.each do |context|
          next unless tag_list_cache_set_on(context)

          tag_list = tag_list_cache_on(context).uniq

          # Find existing tags or create non-existing tags:
          tag_list = ActsAsTaggableOn::Tag.find_or_create_all_with_like_by_name(tag_list)

          current_tags = tags_on(context)
          old_tags     = current_tags - tag_list
          new_tags     = tag_list     - current_tags

          # Find taggings to remove:
          old_taggings = taggings.where(:tagger_type => nil, :tagger_id => nil,
                                        :context => context.to_s, :tag_id => old_tags).all

          if old_taggings.present?
            # Destroy old taggings:
            ActsAsTaggableOn::Tagging.destroy_all "#{ActsAsTaggableOn::Tagging.primary_key}".to_sym => old_taggings.map(&:id)
          end

          # Create new taggings:
          new_tags.each do |tag|
            taggings.create!(:tag_id => tag.id, :context => context.to_s, :taggable => self)
          end
        end

        true
      end
    end
  end
end