text:
package io.crate.planner.operators;

import static io.crate.execution.engine.pipeline.LimitAndOffset.NO_LIMIT;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Nullable;

import io.crate.analyze.OrderBy;
import io.crate.common.collections.Lists2;
import io.crate.data.Row;
import io.crate.execution.dsl.phases.ExecutionPhases;
import io.crate.execution.dsl.phases.MergePhase;
import io.crate.execution.dsl.projection.GroupProjection;
import io.crate.execution.dsl.projection.Projection;
import io.crate.execution.dsl.projection.builder.ProjectionBuilder;
import io.crate.execution.engine.pipeline.LimitAndOffset;
import io.crate.expression.symbol.AggregateMode;
import io.crate.expression.symbol.Function;
import io.crate.expression.symbol.ScopedSymbol;
import io.crate.expression.symbol.Symbol;
import io.crate.expression.symbol.SymbolVisitors;
import io.crate.expression.symbol.Symbols;
import io.crate.metadata.Reference;
import io.crate.metadata.RowGranularity;
import io.crate.metadata.doc.DocTableInfo;
import io.crate.planner.DependencyCarrier;
import io.crate.planner.ExecutionPlan;
import io.crate.planner.Merge;
import io.crate.planner.PlannerContext;
import io.crate.planner.distribution.DistributionInfo;
import io.crate.planner.node.dql.GroupByConsumer;
import io.crate.statistics.ColumnStats;
import io.crate.statistics.Stats;
import io.crate.statistics.TableStats;

public class GroupHashAggregate extends ForwardingLogicalPlan {

    private static final String DISTRIBUTED_MERGE_PHASE_NAME = "distributed merge";
    final List<Function> aggregates;
    final List<Symbol> groupKeys;
    private final List<Symbol> outputs;
    private final long numExpectedRows;

    static long approximateDistinctValues(long numSourceRows, TableStats tableStats, List<Symbol> groupKeys) {
        long distinctValues = 1;
        int numKeysWithStats = 0;
        for (Symbol groupKey : groupKeys) {
            if (Symbols.containsCorrelatedSubQuery(groupKey)) {
                throw new UnsupportedOperationException("Cannot use correlated subquery in GROUP BY clause");
            }
            Stats stats = null;
            ColumnStats<?> columnStats = null;
            if (groupKey instanceof Reference ref) {
                stats = tableStats.getStats(ref.ident().tableIdent());
                columnStats = stats.statsByColumn().get(ref.column());
                numKeysWithStats++;
            } else if (groupKey instanceof ScopedSymbol) {
                ScopedSymbol scopedSymbol = (ScopedSymbol) groupKey;
                stats = tableStats.getStats(scopedSymbol.relation());
                columnStats = stats.statsByColumn().get(scopedSymbol.column());
                numKeysWithStats++;
            }

            if (columnStats == null) {
                // Assume worst case: Every value is unique
                distinctValues *= numSourceRows;
            } else {
                // `approxDistinct` is the number of distinct values in relation to `stats.numDocs()´, not in
                // relation to `numSourceRows`, which is based on the estimates of a source operator.
                // That is why we calculate the cardinality ratio and calculate the new distinct
                // values based on `numSourceRows` to account for changes in the number of rows in source operators
                //
                // e.g. SELECT x, count(*) FROM tbl GROUP BY x
                // and  SELECT x, count(*) FROM tbl WHERE pk = 1 GROUP BY x
                //
                // have a different number of groups
                double cardinalityRatio = columnStats.approxDistinct() / stats.numDocs();
                distinctValues *= (long) (numSourceRows * cardinalityRatio);
            }
        }
        if (numKeysWithStats == groupKeys.size()) {
            return Math.min(distinctValues, numSourceRows);
        } else {
            return numSourceRows;
        }
    }

    public GroupHashAggregate(LogicalPlan source, List<Symbol> groupKeys, List<Function> aggregates, long numExpectedRows) {
        super(source);
        this.numExpectedRows = numExpectedRows;
        this.aggregates = List.copyOf(new LinkedHashSet<>(aggregates));
        this.outputs = Lists2.concat(groupKeys, this.aggregates);
        this.groupKeys = groupKeys;
    }

    @Override
    public long numExpectedRows() {
        return numExpectedRows;
    }

    public List<Function> aggregates() {
        return aggregates;
    }

    @Override
    public ExecutionPlan build(DependencyCarrier executor,
                               PlannerContext plannerContext,
                               Set<PlanHint> hints,
                               ProjectionBuilder projectionBuilder,
                               int limit,
                               int offset,
                               @Nullable OrderBy order,
                               @Nullable Integer pageSizeHint,
                               Row params,
                               SubQueryResults subQueryResults) {
        if (hints.contains(PlanHint.PREFER_SOURCE_LOOKUP)) {
            hints = new HashSet<>(hints);
            hints.remove(PlanHint.PREFER_SOURCE_LOOKUP);
        }
        ExecutionPlan executionPlan = source.build(
            executor, plannerContext, hints, projectionBuilder, NO_LIMIT, 0, null, null, params, subQueryResults);
        if (executionPlan.resultDescription().hasRemainingLimitOrOffset()) {
            executionPlan = Merge.ensureOnHandler(executionPlan, plannerContext);
        }
        SubQueryAndParamBinder paramBinder = new SubQueryAndParamBinder(params, subQueryResults);

        List<Symbol> sourceOutputs = source.outputs();
        if (shardsContainAllGroupKeyValues()) {
            GroupProjection groupProjection = projectionBuilder.groupProjection(
                sourceOutputs,
                groupKeys,
                aggregates,
                paramBinder,
                AggregateMode.ITER_FINAL,
                source.preferShardProjections() ? RowGranularity.SHARD : RowGranularity.CLUSTER,
                plannerContext.transactionContext().sessionSettings().searchPath()
            );
            executionPlan.addProjection(groupProjection, NO_LIMIT, 0, null);
            return executionPlan;
        }

        if (ExecutionPhases.executesOnHandler(plannerContext.handlerNode(), executionPlan.resultDescription().nodeIds())) {
            if (source.preferShardProjections()) {
                executionPlan.addProjection(
                    projectionBuilder.groupProjection(
                        sourceOutputs,
                        groupKeys,
                        aggregates,
                        paramBinder,
                        AggregateMode.ITER_PARTIAL,
                        RowGranularity.SHARD,
                        plannerContext.transactionContext().sessionSettings().searchPath()
                    )
                );
                executionPlan.addProjection(
                    projectionBuilder.groupProjection(
                        outputs,
                        groupKeys,
                        aggregates,
                        paramBinder,
                        AggregateMode.PARTIAL_FINAL,
                        RowGranularity.NODE,
                        plannerContext.transactionContext().sessionSettings().searchPath()
                    ),
                    NO_LIMIT,
                    0,
                    null
                );
                return executionPlan;
            } else {
                executionPlan.addProjection(
                    projectionBuilder.groupProjection(
                        sourceOutputs,
                        groupKeys,
                        aggregates,
                        paramBinder,
                        AggregateMode.ITER_FINAL,
                        RowGranularity.NODE,
                        plannerContext.transactionContext().sessionSettings().searchPath()
                    ),
                    NO_LIMIT,
                    0,
                    null
                );
                return executionPlan;
            }
        }

        GroupProjection toPartial = projectionBuilder.groupProjection(
            sourceOutputs,
            groupKeys,
            aggregates,
            paramBinder,
            AggregateMode.ITER_PARTIAL,
            source.preferShardProjections() ? RowGranularity.SHARD : RowGranularity.NODE,
            plannerContext.transactionContext().sessionSettings().searchPath()
        );
        executionPlan.addProjection(toPartial);
        executionPlan.setDistributionInfo(DistributionInfo.DEFAULT_MODULO);

        GroupProjection toFinal = projectionBuilder.groupProjection(
            outputs,
            groupKeys,
            aggregates,
            paramBinder,
            AggregateMode.PARTIAL_FINAL,
            RowGranularity.CLUSTER,
            plannerContext.transactionContext().sessionSettings().searchPath()
        );
        return createMerge(
            plannerContext,
            executionPlan,
            Collections.singletonList(toFinal),
            executionPlan.resultDescription().nodeIds()
        );
    }

    @Override
    public List<Symbol> outputs() {
        return outputs;
    }

    @Override
    public LogicalPlan pruneOutputsExcept(TableStats tableStats, Collection<Symbol> outputsToKeep) {
        HashSet<Symbol> toKeep = new HashSet<>();
        // We cannot prune groupKeys, even if they are not used in the outputs, because it would change the result semantically
        for (Symbol groupKey : groupKeys) {
            SymbolVisitors.intersection(groupKey, source.outputs(), toKeep::add);
        }
        ArrayList<Function> newAggregates = new ArrayList<>();
        for (Symbol outputToKeep : outputsToKeep) {
            SymbolVisitors.intersection(outputToKeep, aggregates, newAggregates::add);
        }
        for (Function newAggregate : newAggregates) {
            SymbolVisitors.intersection(newAggregate, source.outputs(), toKeep::add);
        }
        LogicalPlan newSource = source.pruneOutputsExcept(tableStats, toKeep);
        if (newSource == source && aggregates.size() == newAggregates.size()) {
            return this;
        }
        return new GroupHashAggregate(newSource, groupKeys, newAggregates, numExpectedRows);
    }

    @Override
    public LogicalPlan replaceSources(List<LogicalPlan> sources) {
        return new GroupHashAggregate(Lists2.getOnlyElement(sources), groupKeys, aggregates, numExpectedRows);
    }

    private ExecutionPlan createMerge(PlannerContext plannerContext,
                                      ExecutionPlan executionPlan,
                                      List<Projection> projections,
                                      Collection<String> nodeIds) {
        return new Merge(
            executionPlan,
            new MergePhase(
                plannerContext.jobId(),
                plannerContext.nextExecutionPhaseId(),
                DISTRIBUTED_MERGE_PHASE_NAME,
                executionPlan.resultDescription().nodeIds().size(),
                1,
                nodeIds,
                executionPlan.resultDescription().streamOutputs(),
                projections,
                DistributionInfo.DEFAULT_BROADCAST,
                null
            ),
            NO_LIMIT,
            LimitAndOffset.NO_OFFSET,
            this.outputs.size(),
            NO_LIMIT,
            null
        );
    }

    /*
     * @return true if it's guaranteed that a group-key-value doesn't occur in more than 1 shard.
     *         Each shard has "group or row authority"
     */
    private boolean shardsContainAllGroupKeyValues() {
        return source instanceof Collect &&
               ((Collect) source).tableInfo instanceof DocTableInfo &&
               GroupByConsumer.groupedByClusteredColumnOrPrimaryKeys(
                   ((DocTableInfo) ((Collect) source).tableInfo),
                   ((Collect) source).mutableBoundWhere,
                   groupKeys);
    }

    @Override
    public <C, R> R accept(LogicalPlanVisitor<C, R> visitor, C context) {
        return visitor.visitGroupHashAggregate(this, context);
    }

    @Override
    public String toString() {
        return "GroupBy{" +
               "src=" + source +
               ", keys=" + groupKeys +
               ", agg=" + aggregates +
               '}';
    }

    @Override
    public void print(PrintContext printContext) {
        printContext
            .text("GroupHashAggregate[")
            .text(Lists2.joinOn(", ", groupKeys, Symbol::toString));
        if (!aggregates.isEmpty()) {
            printContext
                .text(" | ")
                .text(Lists2.joinOn(", ", aggregates, Symbol::toString));
        }
        printContext
            .text("]")
            .nest(source::print);
    }
}


text:
(function($) {

    $.fn.horizontalNav = function(options) {

        // Extend our default options with those provided.
        var opts = $.extend({}, $.fn.horizontalNav.defaults, options);

        return this.each(function () {

            // Save our object
            var $this = $(this);

            // Build element specific options
            // This lets me access options with this syntax: o.optionName
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

            // Save the wrapper. The wrapper is the element that
            // we figure out what the full width should be
            if ($this.is('ul')) {
                var ul_wrap = $this.parent();
            } else {
                var ul_wrap = $this;
            }

            // Grab elements we'll need and add some default styles
            var ul = $this.is('ul') ? $this : ul_wrap.find('> ul'), // The unordered list element
                li = ul.find('> li'), // All list items
                li_last = li.last(), // Last list item
                li_count = li.size(), // The number of navigation elements
                li_a = li.find('> a'); // Remove padding from the links

            if (o.minimumItems && o.minimumItems > li_count) {
                $this.addClass("horizontalNav-notprocessed");
                return false;
            }

            // If set to responsive, re-construct after every browser resize
            if ( o.responsive === true ) {
                // Only need to do this for IE7 and below
                // or if we set tableDisplay to false
                if ( (o.tableDisplay != true) || ($.browser.msie && parseInt($.browser.version, 10) <= 7) ) {
                    resizeTrigger( _construct, o.responsiveDelay );
                }
            }

            if ($('.clearHorizontalNav').length ) {
                ul_wrap.css({ 'zoom' : '1' });
            } else {
                ul_wrap.css({ 'zoom' : '1' }).append('<div class="clearHorizontalNav">');
                // let's append a clearfixing element to the ul wrapper
                $('.clearHorizontalNav').css({
                'display' : 'block',
                'overflow' : 'hidden',
                'visibility' : 'hidden',
                'width' : 0,
                'height' : 0,
                'clear' : 'both'
                });
            }

            // Initiate the plugin
            _construct();

            // Returns the true inner width of an element
            // Essentially it's the inner width without padding.
            function trueInnerWidth(element) {
                return element.innerWidth() - (
                    parseInt(element.css('padding-left')) + parseInt(element.css('padding-right'))
                );
            }

            // Call funcion on browser resize
            function resizeTrigger(callback, delay) {
                // Delay before function is called
                delay = delay || 100;
                // Call function on resize
                var resizeTimer;
                $(window).resize(function() {
                    clearTimeout(resizeTimer);
                    resizeTimer = setTimeout(function() {
                        callback();
                    }, delay);
                });
            }

            // The heavy lifting of this plugin. This is where we
            // find and set the appropriate widths for list items
            function _construct() {

                if ( (o.tableDisplay != true) || ($.browser.msie && parseInt($.browser.version, 10) <= 7) ) {

                    // IE7 doesn't support the "display: table" method
                    // so we need to do it the hard way.

                    // Add some styles
                    ul.css({ 'float' : 'left' });
                    li.css({ 'float' : 'left', 'width' : 'auto' });
                    li_a.css({ 'padding-left' : 0, 'padding-right' : 0 });

                    // Grabbing widths and doing some math
                    var ul_width = trueInnerWidth(ul),
                        ul_width_outer = ul.outerWidth(true),
                        ul_width_extra = ul_width_outer - ul_width,

                        full_width = trueInnerWidth(ul_wrap),
                        extra_width = (full_width - ul_width_extra) - ul_width,
                        li_padding = Math.floor( extra_width / li_count );

                    // Cycle through the list items and give them widths
                    li.each(function(index) {
                        var li_width = trueInnerWidth( $(this) );
                        $(this).css({ 'width' : (li_width + li_padding) + 'px' });
                    });

                    // Get the leftover pixels after we set every itms width
                    var li_last_width = trueInnerWidth(li_last) + ( (full_width - ul_width_extra) - trueInnerWidth(ul) );
                    // I hate to do this but for some reason Firefox (v13.0) and IE are always
                    // one pixel off when rendering. So this is a quick fix for that.
                    if ($.browser.mozilla || $.browser.msie) {
                        li_last_width = li_last_width - 1;
                    }
                    // Add the leftovers to the last navigation item
                    li_last.css({ 'width' : li_last_width + 'px' });

                } else {
                    // Every modern browser supports the "display: table" method
                    // so this is the best way to do it for them.
                    ul.css({ 'display' : 'table', 'float' : 'none', 'width' : '100%' });
                    li.css({ 'display' : 'table-cell', 'float' : 'none' });
                }
                $this.addClass("horizontalNav-processed").removeClass("horizontalNav-notprocessed");
            }

        }); // @end of return this.each()

    };

    $.fn.horizontalNav.defaults = {
        responsive : true,
        responsiveDelay : 100,
        tableDisplay : true,
        minimumItems : 0
    };

})(jQuery);

redpajama_set_name: RedPajamaGithub


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
	value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _SSvgFilter2 = require('./SSvgFilter');

var _SSvgFilter3 = _interopRequireDefault(_SSvgFilter2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @name 			SGradientSvgFilter
 * @extends 		SSvgFilter
 * This SVG filter class apply either a linear or a radial gradient of your choice
 * on an HTMLElement.
 * This is useful cause the gradient will only be applied on part of the elements that is really visible and will respect the opacity
 * of each parts
 *
 * @example 		js
 * const filter = new SGradientSvgFilter();
 * filter.linear(['red','blue','green']);
 * filter.applyTo(myCoolHTMLElement);
 *
 * @author 			Olivier Bossel <olivier.bossel@gmail.com> (https://olivierbossel.com)
 */
var SGradientSvgFilter = function (_SSvgFilter) {
	_inherits(SGradientSvgFilter, _SSvgFilter);

	/**
  * @constructor
  */
	function SGradientSvgFilter() {
		_classCallCheck(this, SGradientSvgFilter);

		var _this = _possibleConstructorReturn(this, (SGradientSvgFilter.__proto__ || Object.getPrototypeOf(SGradientSvgFilter)).call(this, '\n\t\t\t<feImage xlink:href="" x="0" y="0" result="IMAGEFILL" preserveAspectRatio="none" />\n\t\t\t<feComposite operator="in" in="IMAGEFILL" in2="SourceAlpha" />\n\t\t'));

		_this._image = _this.filter.querySelector('feImage');
		_this._tile = _this.filter.querySelector('feTile');
		return _this;
	}

	/**
  * Linear gradient
  * @param 		{Array} 			colors 			An array of colors for your gradient
  * @param 		{Object} 			settings 		The settings of your gradient that consist of an object like : ```{width: 512, height: 512, x0: 0, x1: 512, y0: 0, y1: 1}```
  */

	_createClass(SGradientSvgFilter, [{
		key: 'linear',
		value: function linear(colors) {
			var settings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

			var width = settings.width || 512,
			    height = settings.height || 512,
			    x0 = settings.x0 || 0,
			    x1 = settings.x1 || width,
			    y0 = settings.y0 || 0,
			    y1 = settings.y1 || 0;
			var can = document.createElement('canvas');
			can.setAttribute('width', width);
			can.setAttribute('height', height);
			var ctx = can.getContext('2d'),
			    grad = ctx.createLinearGradient(x0, y0, x1, y1);
			// loop on each colors
			var i = 0;
			colors.forEach(function (color) {
				grad.addColorStop(1 / (colors.length - 1) * i, color);
				i++;
			});
			ctx.fillStyle = grad;
			ctx.fillRect(0, 0, width, height);
			this.grad64 = can.toDataURL();
			this._image.setAttribute('xlink:href', this.grad64);
		}

		/**
   * Linear gradient
   * @param 		{Array} 			colors 			An array of colors for your gradient
   * @param 		{Object} 			settings 		The settings of your gradient that consist of an object like : ```{width: 512, height: 512, x0: 256, x1: 256, y0: 256, y1: 256, r0: 0, r1: 512}```
   */

	}, {
		key: 'radial',
		value: function radial(colors) {
			var settings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

			var width = settings.width || 512,
			    height = settings.height || 512,
			    x0 = settings.x0 || width / 2,
			    x1 = settings.x1 || width / 2,
			    r0 = settings.r0 || 0,
			    y0 = settings.y0 || height / 2,
			    y1 = settings.y1 || height / 2,
			    r1 = settings.r1 || width;
			var can = document.createElement('canvas');
			can.setAttribute('width', width);
			can.setAttribute('height', height);
			var ctx = can.getContext('2d'),
			    grad = ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);
			// loop on each colors
			var i = 0;
			colors.forEach(function (color) {
				grad.addColorStop(1 / (colors.length - 1) * i, color);
				i++;
			});
			ctx.fillStyle = grad;
			ctx.fillRect(0, 0, width, height);
			this.grad64 = can.toDataURL();
			this._image.setAttribute('xlink:href', this.grad64);
		}

		/**
   * Apply the filter to element
   * @override
   * @param 		{HTMLElement} 		elm 		The element on which to apply the filter
   */

	}, {
		key: 'applyTo',
		value: function applyTo(elm) {
			_get(SGradientSvgFilter.prototype.__proto__ || Object.getPrototypeOf(SGradientSvgFilter.prototype), 'applyTo', this).call(this, elm);
			this._setImageSize();
			window.addEventListener('resize', this._onWindowResize.bind(this));
		}

		/**
   * Remove the filter from element
   * @override
   * @param 	{HTMLElement} 	elm 	The element to unapply the filter from
   */

	}, {
		key: 'unapplyFrom',
		value: function unapplyFrom(elm) {
			_get(SGradientSvgFilter.prototype.__proto__ || Object.getPrototypeOf(SGradientSvgFilter.prototype), 'unapplyFrom', this).call(this, elm);
			window.removeEventListener('resize', this._onWindowResize);
		}

		/**
   * When the window is resizing
   * @param 		{Event} 		e 		The resize event
   */

	}, {
		key: '_onWindowResize',
		value: function _onWindowResize(e) {
			// set the image size
			this._setImageSize();
		}

		/**
   * Set image width
   */

	}, {
		key: '_setImageSize',
		value: function _setImageSize() {
			var width = this.elms[0].offsetWidth,
			    height = this.elms[0].offsetHeight;
			if (width >= height) {
				this._image.setAttribute('width', width);
				this._image.removeAttribute('height');
			} else {
				this._image.setAttribute('height', height);
				this._image.removeAttribute('width');
			}
			// this._image.setAttribute('width', width);
			// this._image.setAttribute('height', height);
		}
	}]);

	return SGradientSvgFilter;
}(_SSvgFilter3.default);

// export modules

exports.default = SGradientSvgFilter;


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<config>
  <luceneMatchVersion>${tests.luceneMatchVersion:LATEST}</luceneMatchVersion>

  <!--<lib dir="../../contrib/velocity/lib" />-->
  <!--<lib dir="../../dist/" regex="solr-velocity-\d.*\.jar" />-->

  <requestHandler name="search" class="solr.SearchHandler" default="true">
     <lst name="defaults">
       <str name="echoParams">explicit</str>
       <int name="rows">10</int>
     </lst>
    </requestHandler>

  <queryResponseWriter name="velocity" class="solr.VelocityResponseWriter"/>

  <queryResponseWriter name="velocityWithInitProps" class="solr.VelocityResponseWriter">
    <str name="init.properties.file">velocity-init.properties</str>
  </queryResponseWriter>
</config>


text:
'use strict'

var toString = require('nlcst-to-string')
var visit = require('unist-util-visit')
var convert = require('unist-util-is/convert')

var word = convert('WordNode')
var punctuation = convert('PunctuationNode')
var wordOrSource = convert(['WordNode', 'SourceNode'])

var decadeExpression = /^\d\ds$/
var source = 'retext-quotes'
var doubleQuotationMark = '"'
var singleQuotationMark = "'"
var leftDoubleQuotationMark = '"'
var rightDoubleQuotationMark = '"'
var leftSingleQuotationMark = '''
var rightSingleQuotationMark = '''
var doubleQuotationMarks = leftDoubleQuotationMark + rightDoubleQuotationMark
var singleQuotationMarks = leftSingleQuotationMark + rightSingleQuotationMark
var opening = 'open'
var closing = 'close'
var apostrophe = 'apostrophe'
var quote = 'quote'

module.exports = quotes

// Check quote use.
function quotes(options) {
  var settings = options || {}
  var preferred = settings.preferred || 'smart'
  var smart = settings.smart || [doubleQuotationMarks, singleQuotationMarks]
  var straight = settings.straight || [doubleQuotationMark, singleQuotationMark]

  return transformer

  function transformer(tree, file) {
    // Walk paragraphs first, that way if the stack isn't closed properly we
    // can start fresh each paragraph.
    visit(tree, 'ParagraphNode', visitor)

    function visitor(paragraph) {
      var stack = []

      visit(paragraph, 'PunctuationNode', each)

      return visit.SKIP

      function each(node, index, parent) {
        var actual = toString(node)
        var style = check(actual, straight, smart)
        var expected
        var message
        var markers
        var label

        if (!style) {
          return
        }

        if (
          actual === singleQuotationMark ||
          actual === rightSingleQuotationMark ||
          !style.type
        ) {
          inferStyle(style, stack, node, index, parent)
        }

        // Open stack.
        if (style.type === opening) {
          stack.push(style)
        }

        // Calculate preferred style.
        if (style.type === apostrophe) {
          expected =
            preferred === 'smart'
              ? rightSingleQuotationMark
              : singleQuotationMark
        } else {
          markers = preferred === 'smart' ? smart : straight
          expected = markers[(stack.length + 1) % markers.length]

          if (expected.length > 1) {
            expected = expected.charAt(style.type === opening ? 0 : 1)
          }
        }

        // Close stack.
        // There could be a case here where opening and closing are mismatched,
        // like `"'this"'`.
        // I think we've got the highest chance of removing them one at a time,
        // but haven't really checked it.
        // We'll see whether the simple solution holds.
        if (style.type === closing) {
          stack.pop()
        }

        // Perfect!
        if (actual === expected) {
          return
        }

        // On to warning…
        label = style.type === apostrophe ? style.type : quote

        if (preferred === style.style) {
          message = file.message(
            'Expected `' +
              expected +
              '` to be used at this level of nesting, not `' +
              actual +
              '`',
            node
          )
        } else {
          message = file.message(
            'Expected a ' +
              preferred +
              ' ' +
              label +
              ': `' +
              expected +
              '`, not `' +
              actual +
              '`',
            node
          )
        }

        message.source = source
        message.ruleId = label
        message.actual = actual
        message.expected = [expected]
      }
    }
  }
}

// Check whether `straight` or `smart` contains `value`.
function check(value, straight, smart) {
  return (
    contains(value, straight, 'straight') || contains(value, smart, 'smart')
  )
}

// Check if the marker is in `markers`.
function contains(value, markers, label) {
  var length = markers.length
  var index = -1
  var marker
  var both

  while (++index < length) {
    marker = markers[index]
    both = marker.length > 1

    if (marker.charAt(0) === value) {
      return {style: label, type: both ? opening : null, marker: marker}
    }

    if (both && marker.charAt(1) === value) {
      return {style: label, type: closing, marker: marker}
    }
  }
}

// Infere the `style` of a quote.
// eslint-disable-next-line max-params
function inferStyle(style, stack, node, index, parent) {
  var siblings = parent.children
  var previous
  var next
  var value

  /* istanbul ignore if - Needed if this is ever externalised. */
  if (!node || !punctuation(node)) {
    return
  }

  value = toString(node)

  if (value === singleQuotationMark || value === rightSingleQuotationMark) {
    // Apostrophe when in word.
    if (word(parent)) {
      style.type = apostrophe
      return
    }

    previous = siblings[index - 1]
    next = siblings[index + 1]

    if (wordOrSource(previous)) {
      value = toString(previous)

      // Apostrophe if the previous word ends in `s`, and there's no open single
      // quote.  Example: `Mr. Jones' golf clubs` vs. `'Mr. Jones' golf clubs`.
      if (
        value.charAt(value.length - 1).toLowerCase() === 's' &&
        open(stack, style)
      ) {
        style.type = apostrophe
      } else {
        style.type = closing
      }

      return
    }

    if (word(next)) {
      value = toString(next)

      // Apostrophe if the next word is a decade.
      style.type = decadeExpression.test(value) ? apostrophe : opening

      return
    }
  }

  style.type = open(stack, style) ? opening : closing
}

function open(stack, style) {
  return !stack.length || stack[stack.length - 1].marker !== style.marker
}


text:
/* eslint-env mocha */
'use strict'

const hat = require('hat')
const { getDescribe, getIt, expect } = require('../utils/mocha')

/** @typedef { import("ipfsd-ctl/src/factory") } Factory */
/**
 * @param {Factory} common
 * @param {Object} options
 */
module.exports = (common, options) => {
  const describe = getDescribe(options)
  const it = getIt(options)

  describe('.files.mv', function () {
    this.timeout(40 * 1000)

    let ipfs

    before(async () => { ipfs = (await common.spawn()).api })

    before(async () => {
      await ipfs.files.mkdir('/test/lv1/lv2', { parents: true })
      await ipfs.files.write('/test/a', Buffer.from('Hello, world!'), { create: true })
    })
    after(() => common.clean())

    it('should not move not found file/dir, expect error', () => {
      const testDir = `/test-${hat()}`

      return expect(ipfs.files.mv(`${testDir}/404`, `${testDir}/a`)).to.eventually.be.rejected()
    })

    it('should move file, expect no error', async () => {
      const testDir = `/test-${hat()}`

      await ipfs.files.mkdir(`${testDir}/lv1/lv2`, { parents: true })
      await ipfs.files.write(`${testDir}/a`, Buffer.from('Hello, world!'), { create: true })

      await ipfs.files.mv(`${testDir}/a`, `${testDir}/c`)
    })

    it('should move dir, expect no error', async () => {
      const testDir = `/test-${hat()}`

      await ipfs.files.mkdir(`${testDir}/lv1/lv2`, { parents: true })
      await ipfs.files.mv('/test/lv1/lv2', '/test/lv1/lv4')
    })
  })
}


text:
namespace Charity.Web.Areas.Recipients.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using Charity.Data.Models;
    using Charity.Web.Infrastructure.Mapping;

    public class FoodRequestRegisterModel : IMapFrom<FoodRequest>
    {
        public FoodRequestRegisterModel()
        {

        }

        public FoodRequestRegisterModel(int foodDonationId)
        {
            this.FoodDonationId = foodDonationId;
        }

        [Required]
        [Display(Name = "Donation")]
        public int FoodDonationId { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must not be more than {1} characters.")]
        [UIHint("SinglelineText")]
        public string Quantity { get; set; }

        [Required]
        [UIHint("DatePickerLine")]
        [Display(Name = "Need From")]
        public DateTime NeedFrom { get; set; }

        [Required]
        [UIHint("DatePickerLine")]
        [Display(Name = "Need To")]
        public DateTime NeedTo { get; set; }

        [Required]
        [StringLength(600, ErrorMessage = "The {0} must not be more than {1} characters.")]
        [UIHint("MultilineText")]
        public string Description { get; set; }
    }
}


text:
#include <stdio.h>
#include "common.h"
#include "resultiterator.h"
#include "allheaders.h"
#include "pageres.h"
#include "tesseractclass.h"

using namespace tesseract;

#ifdef __cplusplus
extern "C" {
#endif  /* __cplusplus */

jstring Java_com_example_ocr_ResultIterator_nativeGetUTF8Text(JNIEnv *env,
    jclass clazz, jint nativeResultIterator, jint level) {
  ResultIterator *resultIterator = (ResultIterator *) nativeResultIterator;
  PageIteratorLevel enumLevel = (PageIteratorLevel) level;

  char *text = resultIterator->GetUTF8Text(enumLevel);
  jstring result = env->NewStringUTF(text);

  free(text);

  return result;
}

jfloat Java_com_example_ocr_ResultIterator_nativeConfidence(JNIEnv *env,
    jclass clazz, jint nativeResultIterator, jint level) {
  ResultIterator *resultIterator = (ResultIterator *) nativeResultIterator;
  PageIteratorLevel enumLevel = (PageIteratorLevel) level;

  return (jfloat) resultIterator->Confidence(enumLevel);
}

#ifdef __cplusplus
}
#endif  /* __cplusplus */


text:
<?php

interface RokCommon_Form_IItemNameHandler
{
	/**
	 * @abstract
	 *
	 * @param string       $name
	 * @param string       $group
	 * @param string|null  $formcontrol
	 * @param bool         $multiple
	 *
	 * @return string the name to use for the html tag
	 */
    public function getName($name, $group = null, $formcontrol = null, $multiple = false);

    /**
     * @abstract
     *
     * @param string       $name
     * @param string|null  $id
     * @param string       $group
     * @param string|null  $formcontrol
     * @param bool         $multiple
     *
     * @return string the id to use for the html tag
     */
    public function getId($name, $id = null, $group = null, $formcontrol = null, $multiple = false);
}


text:
using System;
using UnityEngine;

namespace BansheeGz.BGSpline.Curve
{
    /// <summary>Point, attached to separate GameObject </summary>
    [DisallowMultipleComponent]
    // Note, some code was copy pasted from BGCurvePoint class
    public class BGCurvePointGO : MonoBehaviour, BGCurvePointI
    {
        #region fields

        //control type
        [SerializeField] private BGCurvePoint.ControlTypeEnum controlType;

        //relative to curve position
        [SerializeField] private Vector3 positionLocal;

        //relative to point position
        [SerializeField] private Vector3 controlFirstLocal;
        [SerializeField] private Vector3 controlSecondLocal;

        //transform for using as point position
        [SerializeField] private Transform pointTransform;

        //point's curve
        [SerializeField] private BGCurve curve;

        //custom fields values for all points. it's an array with only one element. the reason why we store it like this- is to reduce storage and serialization costs.
        [SerializeField] private BGCurvePoint.FieldsValues[] fieldsValues;

        /// <summary>The curve, point's belong to</summary>
        public BGCurve Curve
        {
            get { return curve; }
        }

        /// <summary>This field is not meant for use outside of BGCurve package </summary>
        //all fields values
        public BGCurvePoint.FieldsValues PrivateValuesForFields
        {
            get
            {
                if (fieldsValues == null || fieldsValues.Length < 1 || fieldsValues[0] == null) fieldsValues = new[] {new BGCurvePoint.FieldsValues()};
                return fieldsValues[0];
            }
            set
            {
                if (fieldsValues == null || fieldsValues.Length < 1 || fieldsValues[0] == null) fieldsValues = new[] {new BGCurvePoint.FieldsValues()};
                fieldsValues[0] = value;
            }
        }

        // =============================================== Position

        //see interface for comments
        public Vector3 PositionLocal
        {
            get
            {
                if (pointTransform != null) return curve.transform.InverseTransformPoint(pointTransform.position);

                switch (Curve.PointsMode)
                {
                    case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                        return positionLocal;
                    case BGCurve.PointsModeEnum.GameObjectsTransform:
                        return curve.transform.InverseTransformPoint(transform.position);
                    default:
                        throw WrongMode();
                }
            }
            set { SetPosition(value); }
        }

        //see interface for comments
        public Vector3 PositionLocalTransformed
        {
            get
            {
                if(pointTransform != null) return pointTransform.position - curve.transform.position;

                switch (Curve.PointsMode)
                {
                    case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                        return curve.transform.TransformPoint(positionLocal) - curve.transform.position;
                    case BGCurve.PointsModeEnum.GameObjectsTransform:
                        return transform.position - curve.transform.position;
                    default:
                        throw WrongMode();
                }
            }
            set { SetPosition(value + curve.transform.position, true); }
        }

        //see interface for comments
        public Vector3 PositionWorld
        {
            get
            {
                if (pointTransform != null) return pointTransform.position;

                switch (Curve.PointsMode)
                {
                    case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                        return curve.transform.TransformPoint(positionLocal);
                    case BGCurve.PointsModeEnum.GameObjectsTransform:
                        return transform.position;
                    default:
                        throw WrongMode();
                }
            }
            set { SetPosition(value, true); }
        }

        // =============================================== First Handle
        //see interface for comments
        public Vector3 ControlFirstLocal
        {
            get { return controlFirstLocal; }
            set { SetControlFirstLocal(value); }
        }

        //see interface for comments
        public Vector3 ControlFirstLocalTransformed
        {
            get { return TargetTransform.TransformVector(controlFirstLocal); }
            set { SetControlFirstLocal(TargetTransform.InverseTransformVector(value)); }
        }

        //see interface for comments
        public Vector3 ControlFirstWorld
        {
            get
            {
                if (pointTransform != null) return pointTransform.position + pointTransform.TransformVector(controlFirstLocal);

                switch (Curve.PointsMode)
                {
                    case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                        return curve.transform.TransformPoint(new Vector3(positionLocal.x + controlFirstLocal.x, positionLocal.y + controlFirstLocal.y, positionLocal.z + controlFirstLocal.z));
                    case BGCurve.PointsModeEnum.GameObjectsTransform:
                        return transform.position + transform.TransformVector(controlFirstLocal);
                    default:
                        throw WrongMode();
                }
            }
            set
            {
                Vector3 localPos;
                if (pointTransform != null) localPos = pointTransform.InverseTransformVector(value - pointTransform.position);
                else
                {
                    switch (Curve.PointsMode)
                    {
                        case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                            localPos = curve.transform.InverseTransformPoint(value) - PositionLocal;
                            break;
                        case BGCurve.PointsModeEnum.GameObjectsTransform:
                            localPos = transform.InverseTransformVector(value - transform.position);
                            break;
                        default:
                            throw WrongMode();
                    }
                }
                SetControlFirstLocal(localPos);
            }
        }

        // =============================================== Second Handle
        //see interface for comments
        public Vector3 ControlSecondLocal
        {
            get { return controlSecondLocal; }
            set { SetControlSecondLocal(value); }
        }

        //see interface for comments
        public Vector3 ControlSecondLocalTransformed
        {
            get { return TargetTransform.TransformVector(controlSecondLocal); }
            set { SetControlSecondLocal(TargetTransform.InverseTransformVector(value)); }
        }

        //see interface for comments
        public Vector3 ControlSecondWorld
        {
            get
            {
                if (pointTransform != null) return pointTransform.position + pointTransform.TransformVector(controlSecondLocal);

                switch (Curve.PointsMode)
                {
                    case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                        return curve.transform.TransformPoint(new Vector3(positionLocal.x + controlSecondLocal.x, positionLocal.y + controlSecondLocal.y, positionLocal.z + controlSecondLocal.z));
                    case BGCurve.PointsModeEnum.GameObjectsTransform:
                        return transform.position + transform.TransformVector(controlSecondLocal);
                    default:
                        throw WrongMode();
                }
            }
            set
            {
                Vector3 localPos;
                if (pointTransform != null) localPos = pointTransform.InverseTransformVector(value - pointTransform.position);
                else
                {
                    switch (Curve.PointsMode)
                    {
                        case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                            localPos = curve.transform.InverseTransformPoint(value) - PositionLocal;
                            break;
                        case BGCurve.PointsModeEnum.GameObjectsTransform:
                            localPos = transform.InverseTransformVector(value - transform.position);
                            break;
                        default:
                            throw WrongMode();
                    }
                }
                SetControlSecondLocal(localPos);
            }
        }

        // =============================================== Control type
        //see interface for comments
        public BGCurvePoint.ControlTypeEnum ControlType
        {
            get { return controlType; }
            set
            {
                if (controlType == value) return;

                curve.FireBeforeChange(BGCurve.EventPointControlType);

                controlType = value;

                if (controlType == BGCurvePoint.ControlTypeEnum.BezierSymmetrical) controlSecondLocal = -controlFirstLocal;

                curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointControlType) : null, sender: this);
            }
        }

        // =============================================== Transform
        public Transform PointTransform
        {
            get { return pointTransform; }
            set
            {
                if (pointTransform == value) return;

                curve.FireBeforeChange(BGCurve.EventPointTransform);

                var oldTransformNull = pointTransform == null && value != null;
                var newTransformNull = value == null && pointTransform != null;

                //we need to transfer system fields
                var control1 = ControlFirstLocalTransformed;
                var control2 = ControlSecondLocalTransformed;
                var positionWorld = PositionWorld;

                pointTransform = value;

                // transfer system fields
                if (pointTransform != null)
                {
                    pointTransform.position = positionWorld;
                    controlFirstLocal = pointTransform.InverseTransformVector(control1);
                    controlSecondLocal = pointTransform.InverseTransformVector(control2);
                }
                else
                {
                    switch (curve.PointsMode)
                    {
                        case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                            positionLocal = curve.transform.InverseTransformPoint(positionWorld);
                            controlFirstLocal = curve.transform.InverseTransformVector(control1);
                            controlSecondLocal = curve.transform.InverseTransformVector(control2);
                            break;
                        case BGCurve.PointsModeEnum.GameObjectsTransform:
                            transform.position = positionWorld;
                            controlFirstLocal = transform.InverseTransformVector(control1);
                            controlSecondLocal = transform.InverseTransformVector(control2);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException("curve.PointsMode");
                    }
                }

                // inform curve
                if (oldTransformNull) curve.PrivateTransformForPointAdded(curve.IndexOf(this));
                else if (newTransformNull) curve.PrivateTransformForPointRemoved(curve.IndexOf(this));

                curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointTransform) : null, sender: this);
            }
        }

        //target transform (used to calculate control positions)
        private Transform TargetTransform
        {
            get
            {
                if (pointTransform != null) return pointTransform;

                switch (Curve.PointsMode)
                {
                    case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                        return curve.transform;
                    case BGCurve.PointsModeEnum.GameObjectsTransform:
                        return transform;
                    default:
                        throw WrongMode();
                }
            }
        }

        #endregion

        #region custom fields

        //===============================================================================================
        //                                                    Custom Fields (see interface for comments)
        //===============================================================================================
        //----------------------------------- Getters
        public T GetField<T>(string name)
        {
            var type = typeof(T);
            var value = GetField(name, type);
            var field = (T) value;
            return field;
        }

        public float GetFloat(string name)
        {
            return PrivateValuesForFields.floatValues[curve.IndexOfFieldValue(name)];
        }

        public bool GetBool(string name)
        {
            return PrivateValuesForFields.boolValues[curve.IndexOfFieldValue(name)];
        }

        public int GetInt(string name)
        {
            return PrivateValuesForFields.intValues[curve.IndexOfFieldValue(name)];
        }

        public Vector3 GetVector3(string name)
        {
            return PrivateValuesForFields.vector3Values[curve.IndexOfFieldValue(name)];
        }

        public Quaternion GetQuaternion(string name)
        {
            return PrivateValuesForFields.quaternionValues[curve.IndexOfFieldValue(name)];
        }

        public Bounds GetBounds(string name)
        {
            return PrivateValuesForFields.boundsValues[curve.IndexOfFieldValue(name)];
        }

        public Color GetColor(string name)
        {
            return PrivateValuesForFields.colorValues[curve.IndexOfFieldValue(name)];
        }

        public object GetField(string name, Type type)
        {
            return BGCurvePoint.FieldTypes.GetField(curve, type, name, PrivateValuesForFields);
        }

        //----------------------------------- Setters
        public void SetField<T>(string name, T value)
        {
            SetField(name, value, typeof(T));
        }

        public void SetField(string name, object value, Type type)
        {
            curve.FireBeforeChange(BGCurve.EventPointField);

            BGCurvePoint.FieldTypes.SetField(curve, type, name, value, PrivateValuesForFields);

            curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointField) : null, sender: this);
        }

        public void SetFloat(string name, float value)
        {
            curve.FireBeforeChange(BGCurve.EventPointField);

            PrivateValuesForFields.floatValues[curve.IndexOfFieldValue(name)] = value;

            curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointField) : null, sender: this);
        }

        public void SetBool(string name, bool value)
        {
            curve.FireBeforeChange(BGCurve.EventPointField);

            PrivateValuesForFields.boolValues[curve.IndexOfFieldValue(name)] = value;

            curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointField) : null, sender: this);
        }

        public void SetInt(string name, int value)
        {
            curve.FireBeforeChange(BGCurve.EventPointField);

            PrivateValuesForFields.intValues[curve.IndexOfFieldValue(name)] = value;

            curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointField) : null, sender: this);
        }

        public void SetVector3(string name, Vector3 value)
        {
            curve.FireBeforeChange(BGCurve.EventPointField);

            PrivateValuesForFields.vector3Values[curve.IndexOfFieldValue(name)] = value;

            curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointField) : null, sender: this);
        }

        public void SetQuaternion(string name, Quaternion value)
        {
            curve.FireBeforeChange(BGCurve.EventPointField);

            PrivateValuesForFields.quaternionValues[curve.IndexOfFieldValue(name)] = value;

            curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointField) : null, sender: this);
        }

        public void SetBounds(string name, Bounds value)
        {
            curve.FireBeforeChange(BGCurve.EventPointField);

            PrivateValuesForFields.boundsValues[curve.IndexOfFieldValue(name)] = value;

            curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointField) : null, sender: this);
        }

        public void SetColor(string name, Color value)
        {
            curve.FireBeforeChange(BGCurve.EventPointField);

            PrivateValuesForFields.colorValues[curve.IndexOfFieldValue(name)] = value;

            curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointField) : null, sender: this);
        }

        #endregion

        #region Misc public methods

        //================================================================================
        //                                                    Misc public functions
        //================================================================================

        public override string ToString()
        {
            return "Point [localPosition=" + positionLocal + "]";
        }

        #endregion

        #region private methods

        //set position
        private void SetPosition(Vector3 value, bool worldSpaceIsUsed = false)
        {
            curve.FireBeforeChange(BGCurve.EventPointPosition);

            //snapping
            if (curve.SnapType != BGCurve.SnapTypeEnum.Off)
            {
                if (worldSpaceIsUsed) curve.ApplySnapping(ref value);
                else
                {
                    //we need to transfer space before applying snapping
                    var pos = curve.transform.TransformPoint(value);
                    if (curve.ApplySnapping(ref pos)) value = curve.transform.InverseTransformPoint(pos);
                }
            }

            //assign position
            if (pointTransform != null)
            {
                //2d mode with curve's transform changed is not working correctly
                if (curve.Mode2D != BGCurve.Mode2DEnum.Off) value = curve.Apply2D(value);
                pointTransform.position = worldSpaceIsUsed ? value : curve.transform.TransformPoint(value);
            }
            else
            {
                switch (Curve.PointsMode)
                {
                    case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                        if (worldSpaceIsUsed)
                        {
                            var localPos = curve.transform.InverseTransformPoint(value);
                            if (curve.Mode2D != BGCurve.Mode2DEnum.Off) localPos = curve.Apply2D(localPos);
                            positionLocal = localPos;
                        }
                        else
                        {
                            if (curve.Mode2D != BGCurve.Mode2DEnum.Off) value = curve.Apply2D(value);
                            positionLocal = value;
                        }
                        break;
                    case BGCurve.PointsModeEnum.GameObjectsTransform:
                        if (worldSpaceIsUsed)
                        {
                            if (curve.Mode2D != BGCurve.Mode2DEnum.Off) value = curve.transform.TransformPoint(curve.Apply2D(curve.transform.InverseTransformPoint(value)));
                            transform.position = value;
                        }
                        else
                        {
                            if (curve.Mode2D != BGCurve.Mode2DEnum.Off) value = curve.Apply2D(value);
                            transform.position = curve.transform.TransformPoint(value);
                        }
                        break;
                    default:
                        throw WrongMode();
                }
            }

            curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointPosition) : null, sender: this);
        }

        //set local control 1
        private void SetControlFirstLocal(Vector3 value)
        {
            curve.FireBeforeChange(BGCurve.EventPointControl);

            if (curve.Mode2D != BGCurve.Mode2DEnum.Off) value = curve.Apply2D(value);

            if (controlType == BGCurvePoint.ControlTypeEnum.BezierSymmetrical) controlSecondLocal = -value;

            controlFirstLocal = value;
            curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointControl) : null, sender: this);
        }

        //set local control 2 (it's basically copy/paste from SetControlFirstLocal, but we can not use delegates here because of performance)
        private void SetControlSecondLocal(Vector3 value)
        {
            curve.FireBeforeChange(BGCurve.EventPointControl);

            if (curve.Mode2D != BGCurve.Mode2DEnum.Off) value = curve.Apply2D(value);

            if (controlType == BGCurvePoint.ControlTypeEnum.BezierSymmetrical) controlFirstLocal = -value;

            controlSecondLocal = value;
            curve.FireChange(curve.UseEventsArgs ? BGCurveChangedArgs.GetInstance(Curve, this, BGCurve.EventPointControl) : null, sender: this);
        }

        #endregion

        #region Not copy pasted

        //=================================================================================
        //                                                    This is not copy/pasted part
        //=================================================================================

        /// <summary>all methods, prefixed with Private, are not meant to be called from outside of BGCurve package </summary>
        //Init with data. No events are fired. point==null for pointsMode switching.
        public void PrivateInit(BGCurvePoint point, BGCurve.PointsModeEnum pointsMode)
        {
            if (point != null)
            {
                // init from new point
                curve = point.Curve;
                controlType = point.ControlType;
                pointTransform = point.PointTransform;

                switch (pointsMode)
                {
                    case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                        positionLocal = point.PositionLocal;
                        controlFirstLocal = point.ControlFirstLocal;
                        controlSecondLocal = point.ControlSecondLocal;
                        break;
                    case BGCurve.PointsModeEnum.GameObjectsTransform:
                        transform.localPosition = point.PositionLocal;

                        //transformed locals are always the same
                        var targetTransform = pointTransform != null ? pointTransform : transform;
                        controlFirstLocal = targetTransform.InverseTransformVector(point.ControlFirstLocalTransformed);
                        controlSecondLocal = targetTransform.InverseTransformVector(point.ControlSecondLocalTransformed);
                        break;
                    default:
                        throw new ArgumentOutOfRangeException("pointsMode", pointsMode, null);
                }
            }
            else
            {
                // change pointsMode
                Transform targetTransform;
                switch (pointsMode)
                {
                    case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                    {
                        if (Curve.PointsMode != BGCurve.PointsModeEnum.GameObjectsTransform)
                            throw new ArgumentOutOfRangeException("Curve.PointsMode", "Curve points mode should be equal to GameObjectsTransform");

                        positionLocal = transform.localPosition;

                        //transformed locals are always the same
                        targetTransform = pointTransform != null ? pointTransform : curve.transform;
                        break;
                    }
                    case BGCurve.PointsModeEnum.GameObjectsTransform:
                    {
                        if (Curve.PointsMode != BGCurve.PointsModeEnum.GameObjectsNoTransform)
                            throw new ArgumentOutOfRangeException("Curve.PointsMode", "Curve points mode should be equal to GameObjectsNoTransform");

                        transform.position = PositionWorld;

                        //transformed locals are always the same
                        targetTransform = pointTransform != null ? pointTransform : transform;
                        break;
                    }
                    default:
                        throw new ArgumentOutOfRangeException("pointsMode", pointsMode, null);
                }

                controlFirstLocal = targetTransform.InverseTransformVector(ControlFirstLocalTransformed);
                controlSecondLocal = targetTransform.InverseTransformVector(ControlSecondLocalTransformed);

            }
        }

        //creates wrong pointMode exception
        private static ArgumentOutOfRangeException WrongMode()
        {
            return new ArgumentOutOfRangeException("Curve.PointsMode");
        }

        #endregion
    }
}


text:
<?php

namespace LD2\Exception;

class LoadLocException extends RuntimeExcetion
{
    public function __construct($locId)
    {
        $msg = sprintf("Locations %s han not loaded", $locId);
        parent::__construct($msg);
    }
}


text:
import os

from django.core.urlresolvers import reverse
from django.db import models
from django.template.defaultfilters import slugify

from markupfield.fields import MarkupField
from product_details import product_details

ENGLISH_COUNTRY_CHOICES = sorted(
    [(code, u'{0} ({1})'.format(name, code)) for code, name in
     product_details.get_regions('en-US').items()],
    cmp=lambda x, y: cmp(x[1], y[1])
)

class CountryField(models.CharField):
    description = ('CharField with country settings specific to trephub '
                   'defaults.')

    def __init__(self, *args, **kwargs):
        options = {
            'max_length': 16,
            'default': u'us',
            'choices': ENGLISH_COUNTRY_CHOICES
        }
        options.update(kwargs)
        return super(CountryField, self).__init__(*args, **options)

# South introspection rules for custom fields
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ['^trephub\.base\.models\.CountryField'])

class Sponsor(models.Model):
    name = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(default='', unique=True)
    description = MarkupField(markup_type='markdown')

    def _logo_path(self, filename):
        root, ext = os.path.splitext(filename)
        return 'sponsors/{0}{1}'.format(slugify(self.name), ext)
    logo = models.ImageField(upload_to=_logo_path)

    def get_absolute_url(self):
        return '#'.join((reverse('base.sponsors'), self.slug))

    def __unicode__(self):
        return u'<Sponsor `{0}`>'.format(self.name)


text:
require "reviews_app/entities/review_normalizer"
require "reviews_app/entities/review_validator"


text:
@interface PodsDummy_Pods_PotatsoLibrary : NSObject
@end
@implementation PodsDummy_Pods_PotatsoLibrary
@end


text:
package org.rapidnewsawards.messages;

import java.io.Serializable;
import java.util.LinkedList;

import org.rapidnewsawards.core.User;

public class UserInfo implements Serializable {
	private static final long serialVersionUID = 1L;
	public User user;
	public LinkedList<Vote_Link> votes;
	public LinkedList<User> followers;
	public LinkedList<User> follows;
	public LinkedList<SocialInfo> socials;
}


text:
package tehnut.lib.mc.util;

import net.minecraft.entity.item.EntityItem;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.wrapper.InvWrapper;
import net.minecraftforge.items.wrapper.SidedInvWrapper;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class InventoryHelper {

    @Nullable
    public static IItemHandler getItemHandler(@Nullable TileEntity tile, @Nullable EnumFacing side) {
        if (tile == null)
            return null;

        IItemHandler handler = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side);

        if (handler == null) {
            if (side != null && tile instanceof ISidedInventory)
                handler = new SidedInvWrapper((ISidedInventory) tile, side);
            else if (tile instanceof IInventory)
                handler = new InvWrapper((IInventory) tile);
        }

        return handler;
    }

    @Nullable
    public static IItemHandler getItemHandler(World world, BlockPos pos, @Nullable EnumFacing side) {
        return getItemHandler(world.getTileEntity(pos), side);
    }

    @Nonnull
    public static ItemStack insertStack(World world, BlockPos pos, @Nullable EnumFacing facing, ItemStack stack) {
        return insertStack(world.getTileEntity(pos), stack, facing);
    }

    @Nonnull
    public static ItemStack insertStack(@Nullable TileEntity tile, ItemStack stack, @Nullable EnumFacing facing) {
        if (tile == null)
            return stack;

        IItemHandler handler = getItemHandler(tile, facing);
        return insertStack(handler, stack);
    }

    @Nonnull
    public static ItemStack insertStack(@Nullable IItemHandler itemHandler, ItemStack stack) {
        if (itemHandler == null)
            return stack;

        ItemStack copy = stack.copy();
        for (int i = 0; i < itemHandler.getSlots(); i++) {
            copy = itemHandler.insertItem(i, copy, false);
            if (copy.isEmpty())
                return ItemStack.EMPTY;
        }

        return copy;
    }

    public static boolean dropRemainderAtBlock(World world, BlockPos pos, @Nullable EnumFacing pushDirection, ItemStack stack) {
        if (world.isRemote)
            return false;

        EntityItem entityItem = new EntityItem(world);
        BlockPos spawnPos = new BlockPos(pos);
        double velocity = 0.15D;
        if (pushDirection != null) {
            spawnPos.offset(pushDirection);

            switch (pushDirection) {
                case DOWN:
                    entityItem.motionY = -velocity;
                    entityItem.setPosition(spawnPos.getX() + 0.5D, spawnPos.getY() - 1.0D, spawnPos.getZ() + 0.5D);
                    break;
                case UP:
                    entityItem.motionY = velocity;
                    entityItem.setPosition(spawnPos.getX() + 0.5D, spawnPos.getY() + 1.0D, spawnPos.getZ() + 0.5D);
                    break;
                case NORTH:
                    entityItem.motionZ = -velocity;
                    entityItem.setPosition(spawnPos.getX() + 0.5D, spawnPos.getY() + 0.5D, spawnPos.getZ() - 1.0D);
                    break;
                case SOUTH:
                    entityItem.motionZ = velocity;
                    entityItem.setPosition(spawnPos.getX() + 0.5D, spawnPos.getY() + 0.5D, spawnPos.getZ() + 1.0D);
                    break;
                case WEST:
                    entityItem.motionX = -velocity;
                    entityItem.setPosition(spawnPos.getX() - 1.0D, spawnPos.getY() + 0.5D, spawnPos.getZ() + 0.5D);
                    break;
                case EAST:
                    entityItem.motionX = velocity;
                    entityItem.setPosition(spawnPos.getX() + 1.0D, spawnPos.getY() + 0.5D, spawnPos.getZ() + 0.5D);
                    break;
            }
        }

        entityItem.setEntityItemStack(stack);
        return world.spawnEntity(entityItem);
    }
}


text:
_a postmodern excuse generator for the modern world_

_run_ ```python manage.py runserver``` _in the main folder, then visit your_ ```localhost:8000``` _to begin_

_find our official submission page [here](http://devpost.com/software/lately)_

### the problem
In general, people are **statistically insignificant**. Billions of lives are nothing but **empty puppets**, buffeted by the torrential winds of chaos as major events are generated by the decisions of mother nature and the powerful few. As the years pass, the struggle to maintain the delusion of control becomes exhausting and, after some soul-seeking, decidedly pointless. You spend an hour too long **wallowing in psychophilosophical self-pity** and now you're late for work.

### where we come in
Why not embrace the inevitable chaos the world offers and secede your dearest possession, i.e. your professional image, to the inscrutable wisdom of the random number generator? Simply **log on to our service** with your Microsoft Outlook account, and our **AI algorithm** will construct a **semi-coherent message**excusing your temporary absence. But that's not all:

- you **never get to see the email** we send for you, because just like the TPP, higher forces in our universe **don't care** whether you're in the know or not.
- just to make sure there's **no funny business**, the message we send **won't show up in your "sent" folder** either.

### photographic proof

![wow, picture 1](https://challengepost-s3-challengepost.netdna-ssl.com/photos/production/software_photos/000/303/268/datas/gallery.jpg)
![wow, picture 2](https://challengepost-s3-challengepost.netdna-ssl.com/photos/production/software_photos/000/303/276/datas/gallery.jpg)

### just a taste of what you're getting by signing on with us
* Sorry for being late, I was forgiving the sins of my priest.
* Sorry for being late, I was Netflix and Chilling with my mother's grandson.
* Sorry for being late, I was aggressively examining my partner's muscle spasms or intense jazz hands, I cannot tell.

### happy customers
"What exactly is postmodernism, except modernism without the anxiety?"
_Jonathan Lethem_

"Nothing exists; even if something exists, nothing can be known about it; and even if something can be known about it, knowledge about it can't be communicated to others."
_Gorgias_

"There are no hard distinctions between what is real and what is unreal, nor between what is true and what is false. A thing is not necessarily either true or false; it can be both true and false."
_Harold Pinter_

"The Postmodernists' tyranny wears people down by boredom and semi-literate prose."
_Christopher Hitchens_


text:
""" Access and control log capturing. """
import logging
import re
from contextlib import contextmanager

import py

import pytest
from _pytest.compat import nullcontext
from _pytest.config import create_terminal_writer
from _pytest.pathlib import Path

DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s"
DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"
_ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m")

def _remove_ansi_escape_sequences(text):
    return _ANSI_ESCAPE_SEQ.sub("", text)

class ColoredLevelFormatter(logging.Formatter):
    """
    Colorize the %(levelname)..s part of the log format passed to __init__.
    """

    LOGLEVEL_COLOROPTS = {
        logging.CRITICAL: {"red"},
        logging.ERROR: {"red", "bold"},
        logging.WARNING: {"yellow"},
        logging.WARN: {"yellow"},
        logging.INFO: {"green"},
        logging.DEBUG: {"purple"},
        logging.NOTSET: set(),
    }
    LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*s)")

    def __init__(self, terminalwriter, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._original_fmt = self._style._fmt
        self._level_to_fmt_mapping = {}

        levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)
        if not levelname_fmt_match:
            return
        levelname_fmt = levelname_fmt_match.group()

        for level, color_opts in self.LOGLEVEL_COLOROPTS.items():
            formatted_levelname = levelname_fmt % {
                "levelname": logging.getLevelName(level)
            }

            # add ANSI escape sequences around the formatted levelname
            color_kwargs = {name: True for name in color_opts}
            colorized_formatted_levelname = terminalwriter.markup(
                formatted_levelname, **color_kwargs
            )
            self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(
                colorized_formatted_levelname, self._fmt
            )

    def format(self, record):
        fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)
        self._style._fmt = fmt
        return super().format(record)

class PercentStyleMultiline(logging.PercentStyle):
    """A logging style with special support for multiline messages.

    If the message of a record consists of multiple lines, this style
    formats the message as if each line were logged separately.
    """

    @staticmethod
    def _update_message(record_dict, message):
        tmp = record_dict.copy()
        tmp["message"] = message
        return tmp

    def format(self, record):
        if "\n" in record.message:
            lines = record.message.splitlines()
            formatted = self._fmt % self._update_message(record.__dict__, lines[0])
            # TODO optimize this by introducing an option that tells the
            # logging framework that the indentation doesn't
            # change. This allows to compute the indentation only once.
            indentation = _remove_ansi_escape_sequences(formatted).find(lines[0])
            lines[0] = formatted
            return ("\n" + " " * indentation).join(lines)
        else:
            return self._fmt % record.__dict__

def get_option_ini(config, *names):
    for name in names:
        ret = config.getoption(name)  # 'default' arg won't work as expected
        if ret is None:
            ret = config.getini(name)
        if ret:
            return ret

def pytest_addoption(parser):
    """Add options to control log capturing."""
    group = parser.getgroup("logging")

    def add_option_ini(option, dest, default=None, type=None, **kwargs):
        parser.addini(
            dest, default=default, type=type, help="default value for " + option
        )
        group.addoption(option, dest=dest, **kwargs)

    add_option_ini(
        "--no-print-logs",
        dest="log_print",
        action="store_const",
        const=False,
        default=True,
        type="bool",
        help="disable printing caught logs on failed tests.",
    )
    add_option_ini(
        "--log-level",
        dest="log_level",
        default=None,
        help="logging level used by the logging module",
    )
    add_option_ini(
        "--log-format",
        dest="log_format",
        default=DEFAULT_LOG_FORMAT,
        help="log format as used by the logging module.",
    )
    add_option_ini(
        "--log-date-format",
        dest="log_date_format",
        default=DEFAULT_LOG_DATE_FORMAT,
        help="log date format as used by the logging module.",
    )
    parser.addini(
        "log_cli",
        default=False,
        type="bool",
        help='enable log display during test run (also known as "live logging").',
    )
    add_option_ini(
        "--log-cli-level", dest="log_cli_level", default=None, help="cli logging level."
    )
    add_option_ini(
        "--log-cli-format",
        dest="log_cli_format",
        default=None,
        help="log format as used by the logging module.",
    )
    add_option_ini(
        "--log-cli-date-format",
        dest="log_cli_date_format",
        default=None,
        help="log date format as used by the logging module.",
    )
    add_option_ini(
        "--log-file",
        dest="log_file",
        default=None,
        help="path to a file when logging will be written to.",
    )
    add_option_ini(
        "--log-file-level",
        dest="log_file_level",
        default=None,
        help="log file logging level.",
    )
    add_option_ini(
        "--log-file-format",
        dest="log_file_format",
        default=DEFAULT_LOG_FORMAT,
        help="log format as used by the logging module.",
    )
    add_option_ini(
        "--log-file-date-format",
        dest="log_file_date_format",
        default=DEFAULT_LOG_DATE_FORMAT,
        help="log date format as used by the logging module.",
    )

@contextmanager
def catching_logs(handler, formatter=None, level=None):
    """Context manager that prepares the whole logging machinery properly."""
    root_logger = logging.getLogger()

    if formatter is not None:
        handler.setFormatter(formatter)
    if level is not None:
        handler.setLevel(level)

    # Adding the same handler twice would confuse logging system.
    # Just don't do that.
    add_new_handler = handler not in root_logger.handlers

    if add_new_handler:
        root_logger.addHandler(handler)
    if level is not None:
        orig_level = root_logger.level
        root_logger.setLevel(min(orig_level, level))
    try:
        yield handler
    finally:
        if level is not None:
            root_logger.setLevel(orig_level)
        if add_new_handler:
            root_logger.removeHandler(handler)

class LogCaptureHandler(logging.StreamHandler):
    """A logging handler that stores log records and the log text."""

    def __init__(self):
        """Creates a new log handler."""
        logging.StreamHandler.__init__(self, py.io.TextIO())
        self.records = []

    def emit(self, record):
        """Keep the log records in a list in addition to the log text."""
        self.records.append(record)
        logging.StreamHandler.emit(self, record)

    def reset(self):
        self.records = []
        self.stream = py.io.TextIO()

class LogCaptureFixture:
    """Provides access and control of log capturing."""

    def __init__(self, item):
        """Creates a new funcarg."""
        self._item = item
        # dict of log name -> log level
        self._initial_log_levels = {}  # Dict[str, int]

    def _finalize(self):
        """Finalizes the fixture.

        This restores the log levels changed by :meth:`set_level`.
        """
        # restore log levels
        for logger_name, level in self._initial_log_levels.items():
            logger = logging.getLogger(logger_name)
            logger.setLevel(level)

    @property
    def handler(self):
        """
        :rtype: LogCaptureHandler
        """
        return self._item.catch_log_handler

    def get_records(self, when):
        """
        Get the logging records for one of the possible test phases.

        :param str when:
            Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown".

        :rtype: List[logging.LogRecord]
        :return: the list of captured records at the given stage

        .. versionadded:: 3.4
        """
        handler = self._item.catch_log_handlers.get(when)
        if handler:
            return handler.records
        else:
            return []

    @property
    def text(self):
        """Returns the formatted log text."""
        return _remove_ansi_escape_sequences(self.handler.stream.getvalue())

    @property
    def records(self):
        """Returns the list of log records."""
        return self.handler.records

    @property
    def record_tuples(self):
        """Returns a list of a stripped down version of log records intended
        for use in assertion comparison.

        The format of the tuple is:

            (logger_name, log_level, message)
        """
        return [(r.name, r.levelno, r.getMessage()) for r in self.records]

    @property
    def messages(self):
        """Returns a list of format-interpolated log messages.

        Unlike 'records', which contains the format string and parameters for interpolation, log messages in this list
        are all interpolated.
        Unlike 'text', which contains the output from the handler, log messages in this list are unadorned with
        levels, timestamps, etc, making exact comparisons more reliable.

        Note that traceback or stack info (from :func:`logging.exception` or the `exc_info` or `stack_info` arguments
        to the logging functions) is not included, as this is added by the formatter in the handler.

        .. versionadded:: 3.7
        """
        return [r.getMessage() for r in self.records]

    def clear(self):
        """Reset the list of log records and the captured log text."""
        self.handler.reset()

    def set_level(self, level, logger=None):
        """Sets the level for capturing of logs. The level will be restored to its previous value at the end of
        the test.

        :param int level: the logger to level.
        :param str logger: the logger to update the level. If not given, the root logger level is updated.

        .. versionchanged:: 3.4
            The levels of the loggers changed by this function will be restored to their initial values at the
            end of the test.
        """
        logger_name = logger
        logger = logging.getLogger(logger_name)
        # save the original log-level to restore it during teardown
        self._initial_log_levels.setdefault(logger_name, logger.level)
        logger.setLevel(level)

    @contextmanager
    def at_level(self, level, logger=None):
        """Context manager that sets the level for capturing of logs. After the end of the 'with' statement the
        level is restored to its original value.

        :param int level: the logger to level.
        :param str logger: the logger to update the level. If not given, the root logger level is updated.
        """
        logger = logging.getLogger(logger)
        orig_level = logger.level
        logger.setLevel(level)
        try:
            yield
        finally:
            logger.setLevel(orig_level)

@pytest.fixture
def caplog(request):
    """Access and control log capturing.

    Captured logs are available through the following properties/methods::

    * caplog.messages        -> list of format-interpolated log messages
    * caplog.text            -> string containing formatted log output
    * caplog.records         -> list of logging.LogRecord instances
    * caplog.record_tuples   -> list of (logger_name, level, message) tuples
    * caplog.clear()         -> clear captured records and formatted log output string
    """
    result = LogCaptureFixture(request.node)
    yield result
    result._finalize()

def get_actual_log_level(config, *setting_names):
    """Return the actual logging level."""

    for setting_name in setting_names:
        log_level = config.getoption(setting_name)
        if log_level is None:
            log_level = config.getini(setting_name)
        if log_level:
            break
    else:
        return

    if isinstance(log_level, str):
        log_level = log_level.upper()
    try:
        return int(getattr(logging, log_level, log_level))
    except ValueError:
        # Python logging does not recognise this as a logging level
        raise pytest.UsageError(
            "'{}' is not recognized as a logging level name for "
            "'{}'. Please consider passing the "
            "logging level num instead.".format(log_level, setting_name)
        )

# run after terminalreporter/capturemanager are configured
@pytest.hookimpl(trylast=True)
def pytest_configure(config):
    config.pluginmanager.register(LoggingPlugin(config), "logging-plugin")

class LoggingPlugin:
    """Attaches to the logging module and captures log messages for each test.
    """

    def __init__(self, config):
        """Creates a new plugin to capture log messages.

        The formatter can be safely shared across all handlers so
        create a single one for the entire test session here.
        """
        self._config = config

        self.print_logs = get_option_ini(config, "log_print")
        self.formatter = self._create_formatter(
            get_option_ini(config, "log_format"),
            get_option_ini(config, "log_date_format"),
        )
        self.log_level = get_actual_log_level(config, "log_level")

        self.log_file_level = get_actual_log_level(config, "log_file_level")
        self.log_file_format = get_option_ini(config, "log_file_format", "log_format")
        self.log_file_date_format = get_option_ini(
            config, "log_file_date_format", "log_date_format"
        )
        self.log_file_formatter = logging.Formatter(
            self.log_file_format, datefmt=self.log_file_date_format
        )

        log_file = get_option_ini(config, "log_file")
        if log_file:
            self.log_file_handler = logging.FileHandler(
                log_file, mode="w", encoding="UTF-8"
            )
            self.log_file_handler.setFormatter(self.log_file_formatter)
        else:
            self.log_file_handler = None

        self.log_cli_handler = None

        self.live_logs_context = lambda: nullcontext()
        # Note that the lambda for the live_logs_context is needed because
        # live_logs_context can otherwise not be entered multiple times due
        # to limitations of contextlib.contextmanager.

        if self._log_cli_enabled():
            self._setup_cli_logging()

    def _create_formatter(self, log_format, log_date_format):
        # color option doesn't exist if terminal plugin is disabled
        color = getattr(self._config.option, "color", "no")
        if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search(
            log_format
        ):
            formatter = ColoredLevelFormatter(
                create_terminal_writer(self._config), log_format, log_date_format
            )
        else:
            formatter = logging.Formatter(log_format, log_date_format)

        formatter._style = PercentStyleMultiline(formatter._style._fmt)
        return formatter

    def _setup_cli_logging(self):
        config = self._config
        terminal_reporter = config.pluginmanager.get_plugin("terminalreporter")
        if terminal_reporter is None:
            # terminal reporter is disabled e.g. by pytest-xdist.
            return

        capture_manager = config.pluginmanager.get_plugin("capturemanager")
        # if capturemanager plugin is disabled, live logging still works.
        log_cli_handler = _LiveLoggingStreamHandler(terminal_reporter, capture_manager)

        log_cli_formatter = self._create_formatter(
            get_option_ini(config, "log_cli_format", "log_format"),
            get_option_ini(config, "log_cli_date_format", "log_date_format"),
        )

        log_cli_level = get_actual_log_level(config, "log_cli_level", "log_level")
        self.log_cli_handler = log_cli_handler
        self.live_logs_context = lambda: catching_logs(
            log_cli_handler, formatter=log_cli_formatter, level=log_cli_level
        )

    def set_log_path(self, fname):
        """Public method, which can set filename parameter for
        Logging.FileHandler(). Also creates parent directory if
        it does not exist.

        .. warning::
            Please considered as an experimental API.
        """
        fname = Path(fname)

        if not fname.is_absolute():
            fname = Path(self._config.rootdir, fname)

        if not fname.parent.exists():
            fname.parent.mkdir(exist_ok=True, parents=True)

        self.log_file_handler = logging.FileHandler(
            str(fname), mode="w", encoding="UTF-8"
        )
        self.log_file_handler.setFormatter(self.log_file_formatter)

    def _log_cli_enabled(self):
        """Return True if log_cli should be considered enabled, either explicitly
        or because --log-cli-level was given in the command-line.
        """
        return self._config.getoption(
            "--log-cli-level"
        ) is not None or self._config.getini("log_cli")

    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
    def pytest_collection(self):
        with self.live_logs_context():
            if self.log_cli_handler:
                self.log_cli_handler.set_when("collection")

            if self.log_file_handler is not None:
                with catching_logs(self.log_file_handler, level=self.log_file_level):
                    yield
            else:
                yield

    @contextmanager
    def _runtest_for(self, item, when):
        with self._runtest_for_main(item, when):
            if self.log_file_handler is not None:
                with catching_logs(self.log_file_handler, level=self.log_file_level):
                    yield
            else:
                yield

    @contextmanager
    def _runtest_for_main(self, item, when):
        """Implements the internals of pytest_runtest_xxx() hook."""
        with catching_logs(
            LogCaptureHandler(), formatter=self.formatter, level=self.log_level
        ) as log_handler:
            if self.log_cli_handler:
                self.log_cli_handler.set_when(when)

            if item is None:
                yield  # run the test
                return

            if not hasattr(item, "catch_log_handlers"):
                item.catch_log_handlers = {}
            item.catch_log_handlers[when] = log_handler
            item.catch_log_handler = log_handler
            try:
                yield  # run test
            finally:
                if when == "teardown":
                    del item.catch_log_handler
                    del item.catch_log_handlers

            if self.print_logs:
                # Add a captured log section to the report.
                log = log_handler.stream.getvalue().strip()
                item.add_report_section(when, "log", log)

    @pytest.hookimpl(hookwrapper=True)
    def pytest_runtest_setup(self, item):
        with self._runtest_for(item, "setup"):
            yield

    @pytest.hookimpl(hookwrapper=True)
    def pytest_runtest_call(self, item):
        with self._runtest_for(item, "call"):
            yield

    @pytest.hookimpl(hookwrapper=True)
    def pytest_runtest_teardown(self, item):
        with self._runtest_for(item, "teardown"):
            yield

    @pytest.hookimpl(hookwrapper=True)
    def pytest_runtest_logstart(self):
        if self.log_cli_handler:
            self.log_cli_handler.reset()
        with self._runtest_for(None, "start"):
            yield

    @pytest.hookimpl(hookwrapper=True)
    def pytest_runtest_logfinish(self):
        with self._runtest_for(None, "finish"):
            yield

    @pytest.hookimpl(hookwrapper=True)
    def pytest_runtest_logreport(self):
        with self._runtest_for(None, "logreport"):
            yield

    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
    def pytest_sessionfinish(self):
        with self.live_logs_context():
            if self.log_cli_handler:
                self.log_cli_handler.set_when("sessionfinish")
            if self.log_file_handler is not None:
                try:
                    with catching_logs(
                        self.log_file_handler, level=self.log_file_level
                    ):
                        yield
                finally:
                    # Close the FileHandler explicitly.
                    # (logging.shutdown might have lost the weakref?!)
                    self.log_file_handler.close()
            else:
                yield

    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
    def pytest_sessionstart(self):
        with self.live_logs_context():
            if self.log_cli_handler:
                self.log_cli_handler.set_when("sessionstart")
            if self.log_file_handler is not None:
                with catching_logs(self.log_file_handler, level=self.log_file_level):
                    yield
            else:
                yield

    @pytest.hookimpl(hookwrapper=True)
    def pytest_runtestloop(self, session):
        """Runs all collected test items."""

        if session.config.option.collectonly:
            yield
            return

        if self._log_cli_enabled() and self._config.getoption("verbose") < 1:
            # setting verbose flag is needed to avoid messy test progress output
            self._config.option.verbose = 1

        with self.live_logs_context():
            if self.log_file_handler is not None:
                with catching_logs(self.log_file_handler, level=self.log_file_level):
                    yield  # run all the tests
            else:
                yield  # run all the tests

class _LiveLoggingStreamHandler(logging.StreamHandler):
    """
    Custom StreamHandler used by the live logging feature: it will write a newline before the first log message
    in each test.

    During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured
    and won't appear in the terminal.
    """

    def __init__(self, terminal_reporter, capture_manager):
        """
        :param _pytest.terminal.TerminalReporter terminal_reporter:
        :param _pytest.capture.CaptureManager capture_manager:
        """
        logging.StreamHandler.__init__(self, stream=terminal_reporter)
        self.capture_manager = capture_manager
        self.reset()
        self.set_when(None)
        self._test_outcome_written = False

    def reset(self):
        """Reset the handler; should be called before the start of each test"""
        self._first_record_emitted = False

    def set_when(self, when):
        """Prepares for the given test phase (setup/call/teardown)"""
        self._when = when
        self._section_name_shown = False
        if when == "start":
            self._test_outcome_written = False

    def emit(self, record):
        ctx_manager = (
            self.capture_manager.global_and_fixture_disabled()
            if self.capture_manager
            else nullcontext()
        )
        with ctx_manager:
            if not self._first_record_emitted:
                self.stream.write("\n")
                self._first_record_emitted = True
            elif self._when in ("teardown", "finish"):
                if not self._test_outcome_written:
                    self._test_outcome_written = True
                    self.stream.write("\n")
            if not self._section_name_shown and self._when:
                self.stream.section("live log " + self._when, sep="-", bold=True)
                self._section_name_shown = True
            logging.StreamHandler.emit(self, record)


text:
echo off
SETLOCAL enabledelayedexpansion
cd ..
call setEnv.cmd

echo on
"%JAVA_HOME%\bin\java" %MEM_ARGS% -classpath "%CLASSPATH%" twitter4j.examples.friendship.GetIncomingFriendships %*

ENDLOCAL


text:
package websocket.models.requests;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import websocket.IRequestSendErrorHandler;
import websocket.IResponseHandler;
import websocket.models.IRequestData;
import websocket.models.Request;

/**
 * Created by loganga on 5/9/2016
 */
public class FileCreateRequest implements IRequestData {

    @JsonProperty("Name")
    protected String name;

    @JsonProperty("RelativePath")
    protected String relativePath;

    @JsonProperty("ProjectID")
    protected long projectID;

    @JsonProperty("FileBytes")
    protected byte[] fileBytes;

    public FileCreateRequest(String name, String relativePath, long projectID, byte[] fileBytes) {
        this.name = name;
        this.relativePath = relativePath;
        this.projectID = projectID;
        this.fileBytes = fileBytes;
    }

    @JsonIgnore
    @Override
    public Request getRequest(IResponseHandler responseHandler, IRequestSendErrorHandler requestSendErrorHandler) {
        return new Request("File", "Create", this, responseHandler, requestSendErrorHandler);
    }
}