text:
<!DOCTYPE html>

        <meta charset="UTF-8">

        <?php
        $ctr = 1;
        $no = 1;
        $total = [];
        $grandTotalSkip = 1;
        $isOnSameGroup = true;
        $currentGroupByData = [];

        foreach ($showTotalColumns as $column => $type) {
            $total[$column] = 0;
        }

        if ($showTotalColumns != []) {
            foreach ($columns as $colName => $colData) {
                if (!array_key_exists($colName, $showTotalColumns)) {
                    $grandTotalSkip++;
                } else {
                    break;
                }
            }
        }

        $grandTotalSkip = !$showNumColumn ? $grandTotalSkip - 1 : $grandTotalSkip;
        ?>

{{ $headers['title'] }}

            @if ($showMeta)
                @foreach($headers['meta'] as $name => $value)

                        {{ $name }}
                        {{ ucwords($value) }}

                @endforeach
            @endif

            @if ($showHeader)

                    @if ($showNumColumn)
                        {{ __('laravel-report-generator::messages.no') }}
                    @endif
                    @foreach ($columns as $colName => $colData)
                        @if (array_key_exists($colName, $editColumns))
                            {{ $colName }}
                        @else
                            {{ $colName }}
                        @endif
                    @endforeach

            @endif

            <?php
            $__env = isset($__env) ? $__env : null;
            ?>
            @foreach($query->take($limit ?: null)->cursor() as $result)
                <?php
                    if ($groupByArr != []) {
                        $isOnSameGroup = true;
                        foreach ($groupByArr as $groupBy) {
                            if (is_object($columns[$groupBy]) && $columns[$groupBy] instanceof Closure) {
                                $thisGroupByData[$groupBy] = $columns[$groupBy]($result);
                            } else {
                                $thisGroupByData[$groupBy] = $result->{$columns[$groupBy]};
                            }

                            if (isset($currentGroupByData[$groupBy])) {
                                if ($thisGroupByData[$groupBy] != $currentGroupByData[$groupBy]) {
                                    $isOnSameGroup = false;
                                }
                            }

                            $currentGroupByData[$groupBy] = $thisGroupByData[$groupBy];
                        }

                        if ($isOnSameGroup === false) {
                            echo '
';
                            if ($showNumColumn || $grandTotalSkip > 1) {
                                echo ''.__('laravel-report-generator::messages.grand_total').'	';
                            }
                            $dataFound = false;
                            foreach ($columns as $colName => $colData) {
                                if (array_key_exists($colName, $showTotalColumns)) {
                                    if ($showTotalColumns[$colName] == 'point') {
                                        echo '' . number_format($total[$colName], 2, '.', ',') . '	';
                                    } else {
                                        echo '' . strtoupper($showTotalColumns[$colName]) . ' ' . number_format($total[$colName], 2, '.', ',') . '	';
                                    }
                                    $dataFound = true;
                                } else {
                                    if ($dataFound) {
                                        echo '	';
                                    }
                                }
                            }
                            echo '
';//

';

                            // Reset No, Reset Grand Total
                            $no = 1;
                            foreach ($showTotalColumns as $showTotalColumn => $type) {
                                $total[$showTotalColumn] = 0;
                            }
                            $isOnSameGroup = true;
                        }
                    }
                ?>

                    @if ($showNumColumn)
                        {{ $no }}
                    @endif
                    @foreach ($columns as $colName => $colData)
                        <?php
                            $class = 'left';
                            // Check Edit Column to manipulate class & Data
                            if (is_object($colData) && $colData instanceof Closure) {
                                $generatedColData = $colData($result);
                            } else {
                                $generatedColData = $result->{$colData};
                            }
                            $displayedColValue = $generatedColData;
                            if (array_key_exists($colName, $editColumns)) {
                                if (isset($editColumns[$colName]['class'])) {
                                    $class = $editColumns[$colName]['class'];
                                }

                                if (isset($editColumns[$colName]['displayAs'])) {
                                    $displayAs = $editColumns[$colName]['displayAs'];
                                    if (is_object($displayAs) && $displayAs instanceof Closure) {
                                        $displayedColValue = $displayAs($result);
                                    } elseif (!(is_object($displayAs) && $displayAs instanceof Closure)) {
                                        $displayedColValue = $displayAs;
                                    }
                                }
                            }

                            if (array_key_exists($colName, $showTotalColumns)) {
                                $total[$colName] += $generatedColData;
                            }
                        ?>
                        {{ $displayedColValue }}
                    @endforeach

                <?php $ctr++; $no++; ?>
            @endforeach
            @if ($showTotalColumns != [] && $ctr > 1)

                    @if ($showNumColumn || $grandTotalSkip > 1)
                        {{ __('laravel-report-generator::messages.grand_total') }}	 {{-- For Number --}}
                    @endif
                    <?php $dataFound = false; ?>
                    @foreach ($columns as $colName => $colData)
                        @if (array_key_exists($colName, $showTotalColumns))
                            <?php $dataFound = true; ?>
                            @if ($showTotalColumns[$colName] == 'point')
                                {{ number_format($total[$colName], 2, '.', ',') }}
                            @else
                                {{ strtoupper($showTotalColumns[$colName]) }} {{ number_format($total[$colName], 2, '.', ',') }}
                            @endif
                        @else
                            @if ($dataFound)

                            @endif
                        @endif
                    @endforeach

            @endif


text:
@interface RecentlyTabsTopSpacingHeader : UIView

// Returns the desired height when included in a UITableViewCell.
+ (CGFloat)desiredHeightInUITableViewCell;

@end

// View adding space at the bottom of the Recently Closed section.
@interface RecentlyClosedSectionFooter : UIView

// Designated initializer.
- (instancetype)initWithFrame:(CGRect)aRect;

// Returns the desired height when included in a UITableViewCell.
+ (CGFloat)desiredHeightInUITableViewCell;

@end

#endif  // IOS_CHROME_BROWSER_UI_NTP_RECENT_TABS_VIEWS_SPACERS_VIEW_H_

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Acme\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Precio
 *
 * @ORM\Table(name="precio")
 * @ORM\Entity
 */
class Precio
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="Nombre", type="string", length=50, nullable=false)
     */
    private $nombre;

    /**
     * @var string
     *
     * @ORM\Column(name="Precio", type="decimal", precision=10, scale=0, nullable=false)
     */
    private $precio;

}


text:
var parseWindshaftErrors = require('../windshaft/error-parser');

function CartoDBLayerGroupViewBase (layerGroupModel, opts) {
  opts = opts || {};
  this.interaction = [];
  this.nativeMap = opts.nativeMap;
  this._mapModel = opts.mapModel;

  layerGroupModel.on('change:urls', this._reload, this);
  layerGroupModel.onLayerVisibilityChanged(this._reload.bind(this));
  /** dirty raster hack **/
  var layers = layerGroupModel._layersCollection.models;
  var isRaster = function(layer) {
    if (!!layer.attributes.layer_name && layer.attributes.layer_name.indexOf('_raster') > 0) return true;
    for (var lay in layersData) {
      if (!layersData[lay].options.source) continue;
      if (layersData[lay].options.source == layer.attributes.source.id)
        return !!(layersData[lay].options.table_name.indexOf('_raster') != -1);
    }
  }
  for(ele in layers){
    if (layers[ele].attributes.type.toLowerCase() == 'cartodb' && isRaster(layers[ele]))
      layers[ele].attributes.type = 'raster_tileo';
  }

  this._reload();
}

CartoDBLayerGroupViewBase.prototype = {
  _reload: function () {
    throw new Error('_reload must be implemented');
  },

  _reloadInteraction: function () {
    this._clearInteraction();

    this.model.forEachGroupedLayer(function (layerModel, layerIndex) {
      if (layerModel.isVisible() &&
          layerModel.isInteractive() && this._mapModel &&
          this._mapModel.isFeatureInteractivityEnabled()) {
        this._enableInteraction(layerIndex);
      }
    }, this);
  },

  _clearInteraction: function () {
    for (var layerIndex in this.interaction) {
      if (this.interaction.hasOwnProperty(layerIndex) &&
        this.interaction[layerIndex]) {
        this.interaction[layerIndex].remove();
        this.interaction[layerIndex] = null;
      }
    }
  },

  _enableInteraction: function (layerIndexInLayerGroup) {
    var self = this;
    var tilejson = this._generateTileJSON(layerIndexInLayerGroup);
    if (tilejson) {
      var previousLayerInteraction = this.interaction[layerIndexInLayerGroup];
      if (previousLayerInteraction) {
        previousLayerInteraction.remove();
      }

      // eslint-disable-next-line
      this.interaction[layerIndexInLayerGroup] = new this.interactionClass()
        .map(this.nativeMap)
        .tilejson(tilejson)
        .on('on', function (zeraEvent) {
          if (self._interactionDisabled) return;
          zeraEvent.layer = layerIndexInLayerGroup;
          self._manageOnEvents(self.nativeMap, zeraEvent);
        })
        .on('off', function (zeraEvent) {
          if (self._interactionDisabled) return;
          zeraEvent = zeraEvent || {};
          // TODO: zera has an .on('error', () => { }) callback that should be used here
          if (zeraEvent.errors != null) {
            self._manageInteractivityErrors(zeraEvent);
          }
          zeraEvent.layer = layerIndexInLayerGroup;
          self._manageOffEvents(self.nativeMap, zeraEvent);
        });
    }
  },

  _manageInteractivityErrors: function (payload) {
    var errors = parseWindshaftErrors(payload);
    if (errors.length > 0) {
      this.trigger('featureError', errors[0]);
    }
  },

  _generateTileJSON: function (layerIndexInLayerGroup) {
    if (this.model.hasURLs()) {
      return {
        tilejson: '2.0.0',
        scheme: 'xyz',
        grids: this.model.getGridURLTemplatesWithSubdomains(layerIndexInLayerGroup),
        tiles: this.model.getTileURLTemplatesWithSubdomains(),
        formatter: function (options, data) { return data; }
      };
    }
  },

  error: function (e) { },

  tilesOk: function () { }
};

module.exports = CartoDBLayerGroupViewBase;


text:
/**
 * Искать элементы по заданному условию или указателю.
 * Метод возвращает либо массив найденных элементов, либо
 * сам элемент (если mult = false)
 *
 * @param {($$CollectionFilter|$$CollectionLink|?$$CollectionIteratorInterface)=} [opt_filterOrParams='active'] -
 *     1) функция-фильтр;
 *     2) строковое выражение (запись эквивалентна: return + строковое выражение);
 *     3) true (если фильтр отключён);
 *     4) указатель (перегрузка).
 *     ИЛИ объект, свойствами которого указаны параметры функции (приставки opt_ отбрасываются)
 *
 * @param {?string=} [opt_id='active'] - ИД коллекции
 * @param {?boolean=} [opt_mult=true] - если false, то после первой успешной итерации цикл прерывается
 *
 * @param {?number=} [opt_count] - максимальное количество элементов в ответе (по умолчанию весь объект)
 * @param {?number=} [opt_from=0] - количество пропускаемых успешных итераций
 * @param {?number=} [opt_startIndex=0] - начальная позиция поиска
 * @param {?number=} [opt_endIndex] - конечная позиция поиска (включается)
 *
 * @param {?boolean=} [opt_reverse=false] - если true, то обход коллекции идёт с хвоста (спуск)
 * @param {?boolean=} [opt_inverseFilter=false] - если true,
 *     то успешной итерацией считается отрицательный результат
 *
 * @param {(boolean|number|null)=} [opt_notOwn=false] - если true,
 *     то итерации по объекту идут с учётом свойств прототипа,
 *     a если -1, то только свойства прототипа
 *
 * @param {?boolean=} [opt_live=false] - если true, то начальная длина коллекции не кешируется,
 *     т.е. добавленные во время операции элементы будут участвовать в обходе
 *     (только для массивов, массиво-подобных объектов, Map, Set и opt_reverse = false)
 *
 * @param {?string=} [opt_use] - тип используемого цикла внутри итератора: for, for of или for in
 * @param {Object=} [opt_vars] - объект добавляемых переменных в кластер
 *
 * @see Collection.prototype.byLink
 * @param {$$CollectionLink=} [opt_context] - дополнительный контекст
 *
 * @param {?boolean=} [opt_chain=false] - если true, то метод установит полученную коллекцию активной
 *     и вернёт ссылку на экземпляр Collection (только в случае синхронной операции)
 *
 * @param {?boolean=} [opt_thread=false] - если true, то операция разбивается на части и выполняется отложено,
 *     а сам метод вернёт ссылку на объект-генератор
 *
 * @param {?string=} [opt_priority='normal'] - приоритет отложенной задачи (low, normal, hight, critical)
 * @param {?function(this:Collection, ?)=} [opt_onIterationEnd] - функция обратного вызова на завершение итерации
 * @param {?function(this:Collection, ?)=} [opt_onComplete] - функция обратного вызова на завершение операции
 * @param {?function(this:Collection, ?)=} [opt_onChunk] - функция обратного вызова на
 *     завершение части отложенной операции
 *
 * @param {?boolean=} [opt_generator] - если true, то операция компилируется как генератор
 * @return {(!Collection|!Generator|!Array|?)}
 */
Collection.prototype.get = function (
	opt_filterOrParams,
	opt_id,
	opt_mult,
	opt_count,
	opt_from,
	opt_startIndex,
	opt_endIndex,
	opt_reverse,
	opt_inverseFilter,
	opt_notOwn,
	opt_live,
	opt_use,
	opt_vars,
	opt_context,
	opt_chain,
	opt_thread,
	opt_priority,
	opt_onIterationEnd,
	opt_onComplete,
	opt_onChunk,
	opt_generator
) {
	var old = opt_filterOrParams;

	if (isObject(opt_filterOrParams)) {
		/** @type {$$CollectionIteratorInterface} */
		let p = _.any(opt_filterOrParams || {});
		opt_id = _(opt_id, p.id);
		opt_mult = _(opt_mult, p.mult);
		opt_context = _(opt_context, p.context);
		opt_chain = _(opt_chain, p.chain);
		opt_onComplete = _(opt_onComplete, p.onComplete);
		opt_filterOrParams = _.any(p.filter);
	}

	if (opt_filterOrParams != null && !isFunction(opt_filterOrParams) && (
		isString(opt_filterOrParams) && !this._isFilter(opt_filterOrParams) ||
		isArray(opt_filterOrParams) ||
		isNumber(opt_filterOrParams) ||
		isLink(opt_filterOrParams)
	)) {

		let tmp = this._chain(this._getOne(this._joinContexts(opt_context, opt_filterOrParams), opt_id), opt_chain);

		if (opt_onComplete) {
			opt_onComplete.call(this, tmp);
		}

		return tmp;
	}

	var res = [];
	var returnVal = this.forEach(
		(el) => {
			res.push(el);
		},

		old,
		opt_id,
		opt_mult,
		opt_count,
		opt_from,
		opt_startIndex,
		opt_endIndex,
		opt_reverse,
		opt_inverseFilter,
		opt_notOwn,
		opt_live,
		opt_use,
		opt_vars,
		opt_context,
		res,
		opt_thread,
		opt_priority,
		opt_onIterationEnd,

		function () {
			if (opt_mult === false) {
				res = res[0];
			}

			this._chain(res, opt_chain);

			if (opt_onComplete) {
				opt_onComplete.call(this, res);
			}
		},

		opt_onChunk,
		opt_generator
	);

	if (returnVal !== this) {
		return returnVal;
	}

	return opt_chain ? this : res;
};


text:
package org.spoofax.jsglr2.parseforest;

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

import org.metaborg.parsetable.productions.IProduction;
import org.metaborg.parsetable.productions.ProductionType;
import org.spoofax.jsglr2.parser.AbstractParseState;
import org.spoofax.jsglr2.parser.observing.ParserObserving;
import org.spoofax.jsglr2.stack.IStackNode;

public abstract class ParseForestManager
//@formatter:off
   <ParseForest extends IParseForest,
    Derivation  extends IDerivation<ParseForest>,
    ParseNode   extends IParseNode<ParseForest, Derivation>,
    StackNode   extends IStackNode,
    ParseState  extends AbstractParseState<?, StackNode>>
//@formatter:on
    implements ParseNodeVisiting<ParseForest, Derivation, ParseNode> {

    protected final ParserObserving<ParseForest, Derivation, ParseNode, StackNode, ParseState> observing;
    protected final Disambiguator<ParseForest, Derivation, ParseNode, StackNode, ParseState> disambiguator;

    protected ParseForestManager(ParserObserving<ParseForest, Derivation, ParseNode, StackNode, ParseState> observing,
        Disambiguator<ParseForest, Derivation, ParseNode, StackNode, ParseState> disambiguator) {
        this.observing = observing;
        this.disambiguator = disambiguator;
    }

    /**
     * @param stack
     *            The parse node will be added to the link _to_ this stack node.
     */
    abstract public ParseNode createParseNode(ParseState parseState, IStackNode stack, IProduction production,
        Derivation firstDerivation);

    /**
     * @param stack
     *            The derivation will be added to the parse node on the link _to_ this stack node.
     */
    abstract public Derivation createDerivation(ParseState parseState, IStackNode stack, IProduction production,
        ProductionType productionType, ParseForest[] parseForests);

    abstract public void addDerivation(ParseState parseState, ParseNode parseNode, Derivation derivation);

    abstract public ParseNode createSkippedNode(ParseState parseState, IStackNode stack, IProduction production,
        ParseForest[] parseForests);

    abstract public ParseForest createCharacterNode(ParseState parseState);

    abstract public ParseForest[] parseForestsArray(int length);

    public ParseForest filterStartSymbol(ParseForest parseForest, String startSymbol, ParseState parseState) {
        ParseNode topNode = (ParseNode) parseForest;
        List<Derivation> derivationsWithStartSymbol = new ArrayList<>();

        for(Derivation derivation : topNode.getDerivations()) {
            String derivationStartSymbol = derivation.production().startSymbolSort();

            if(derivationStartSymbol != null && derivationStartSymbol.equals(startSymbol))
                derivationsWithStartSymbol.add(derivation);
        }

        if(derivationsWithStartSymbol.isEmpty())
            return null;
        else
            return (ParseForest) filteredTopParseNode(topNode, derivationsWithStartSymbol);
    }

    abstract protected ParseNode filteredTopParseNode(ParseNode parseNode, List<Derivation> derivations);

}


text:
ACCEPTED

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

#### Published in
Svensk Skogsvårdsförening Tidskr. , Hafte 32: (1934)

#### Original name
Lecythophora lignicola Nannf., 1934

### Remarks
null


text:
package org.openqa.selenium.remote.server;

import static com.google.common.collect.Lists.newArrayList;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.number.OrderingComparisons.greaterThan;
import static org.hamcrest.number.OrderingComparisons.lessThan;
import static org.junit.Assert.assertThat;
import static org.openqa.selenium.remote.server.CapabilitiesComparator.getBestMatch;

import com.google.common.collect.Lists;

import org.junit.Test;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.util.Comparator;
import java.util.List;

public class CapabilitiesComparatorTest {

  private Comparator<Capabilities> comparator;

  @Test
  public void shouldMatchByBrowserName_assumingAllOtherPropertiesAreNull() {
    comparator = compareBy(capabilities("firefox", "", Platform.ANY, true));

    Capabilities c1 = capabilities("firefox", null, null, false);
    Capabilities c2 = capabilities("chrome", null, null, false);

    assertGreaterThan(c1, c2);
  }

  @Test
  public void shouldMatchByBrowserName_assumingAllOtherPropertiesAreTheSame() {
    comparator = compareBy(capabilities("firefox", "", Platform.ANY, true));

    Capabilities c1 = capabilities("firefox", "", Platform.ANY, true);
    Capabilities c2 = capabilities("chrome", "", Platform.ANY, true);

    assertGreaterThan(c1, c2);
  }

  @Test
  public void shouldIgnoreVersionIfNullOnAnInput() {
    comparator = compareBy(capabilities("firefox", "6", Platform.ANY, true));

    Capabilities c1 = capabilities("firefox", null, Platform.ANY, true);
    Capabilities c2 = capabilities("firefox", "7", Platform.ANY, true);
    assertGreaterThan(c1, c2);

    Capabilities c3 = capabilities("firefox", "7", Platform.ANY, true);
    Capabilities c4 = capabilities("firefox", null, Platform.ANY, true);
    assertGreaterThan(c4, c3);
  }

  @Test
  public void shouldMatchByVersion_assumingAllOtherPropertiesAreTheSame_versionSpecified() {
    comparator = compareBy(capabilities("firefox", "6", Platform.ANY, true));

    Capabilities c1 = capabilities("firefox", "6", Platform.ANY, true);
    Capabilities c2 = capabilities("firefox", "7", Platform.ANY, true);
    Capabilities c3 = capabilities("firefox", null, Platform.ANY, true);

    assertGreaterThan(c1, c2);
    assertGreaterThan(c1, c3);
  }

  @Test
  public void shouldMatchByVersion_assumingAllOtherPropertiesAreTheSame_emptyVersion() {
    comparator = compareBy(capabilities("firefox", "", Platform.ANY, true));

    Capabilities c1 = capabilities("firefox", "", Platform.ANY, true);
    Capabilities c2 = capabilities("firefox", "6", Platform.ANY, true);
    Capabilities c3 = capabilities("firefox", null, Platform.ANY, true);

    assertGreaterThan(c1, c2);
    assertGreaterThan(c1, c3);
  }

  @Test
  public void shouldMatchByVersion_assumingAllOtherPropertiesAreTheSame_nullVersion() {
    comparator = compareBy(capabilities("firefox", null, Platform.ANY, true));

    Capabilities c1 = capabilities("firefox", null, Platform.ANY, true);
    Capabilities c2 = capabilities("firefox", "", Platform.ANY, true);
    Capabilities c3 = capabilities("firefox", "6", Platform.ANY, true);

    assertGreaterThan(c1, c2);
    assertGreaterThan(c1, c3);
  }

  @Test
  public void shouldMatchByPlatform_assumingAllOtherPropertiesAreTheSame() {
    comparator = compareBy(capabilities("firefox", "6", Platform.ANY, true));

    Capabilities c1 = capabilities("firefox", "6", Platform.ANY, true);
    Capabilities c2 = capabilities("firefox", "6", Platform.LINUX, true);

    assertGreaterThan(c1, c2);
  }

  @Test
  public void shouldPickCorrectBrowser() {
    Capabilities chrome = DesiredCapabilities.chrome();
    Capabilities firefox = DesiredCapabilities.firefox();
    Capabilities opera = DesiredCapabilities.opera();
    List<Capabilities> list = Lists.newArrayList(chrome, firefox, opera);

    DesiredCapabilities desired = new DesiredCapabilities();

    desired.setBrowserName("chrome");
    assertThat(getBestMatch(desired, list), equalTo(chrome));

    desired.setBrowserName("firefox");
    assertThat(getBestMatch(desired, list), equalTo(firefox));

    desired.setBrowserName("opera");
    assertThat(getBestMatch(desired, list), equalTo(opera));
  }

  @Test
  public void shouldPickAnyIfPlatformChoicesAreAnyOrWindowsAndDesireLinux() {
    Capabilities any = capabilities("firefox", "", Platform.ANY, true);
    Capabilities windows = capabilities("firefox", "", Platform.WINDOWS, true);
    Capabilities linux = capabilities("firefox", "", Platform.LINUX, true);

    assertThat(getBestMatch(linux, Lists.newArrayList(any, windows)), equalTo(any));
    // Registration order should not matter.
    assertThat(getBestMatch(linux, Lists.newArrayList(windows, any)), equalTo(any));
  }

  @Test
  public void shouldPickWindowsIfPlatformChoiceIsAny() {
    Capabilities any = capabilities("internet explorer", "", Platform.ANY, true);
    Capabilities windows = capabilities("internet explorer", "", Platform.WINDOWS, true);
    assertThat(getBestMatch(any, Lists.newArrayList(windows)), equalTo(windows));
  }

  @Test
  public void shouldPickMostSpecificOperatingSystem() {
    Capabilities any = capabilities("internet explorer", "", Platform.ANY, true);
    Capabilities windows = capabilities("internet explorer", "", Platform.WINDOWS, true);
    Capabilities xp = capabilities("internet explorer", "", Platform.XP, true);
    Capabilities vista = capabilities("internet explorer", "", Platform.VISTA, true);

    List<Capabilities> list = newArrayList(any, windows, xp, vista);
    assertThat(getBestMatch(any, list), equalTo(any));
    assertThat(getBestMatch(windows, list), equalTo(windows));
    assertThat(getBestMatch(xp, list), equalTo(xp));
    assertThat(getBestMatch(vista, list), equalTo(vista));
  }

  @Test
  public void pickingWindowsFromVariousLists() {
    Capabilities any = capabilities("internet explorer", "", Platform.ANY, true);
    Capabilities windows = capabilities("internet explorer", "", Platform.WINDOWS, true);
    Capabilities xp = capabilities("internet explorer", "", Platform.XP, true);
    Capabilities vista = capabilities("internet explorer", "", Platform.VISTA, true);

    assertThat(getBestMatch(windows, newArrayList(any)), equalTo(any));
    assertThat(getBestMatch(windows, newArrayList(any, windows)), equalTo(windows));
    assertThat(getBestMatch(windows, newArrayList(windows, xp, vista)), equalTo(windows));
    assertThat(getBestMatch(windows, newArrayList(xp, vista)),
        anyOf(equalTo(xp), equalTo(vista)));
    assertThat(getBestMatch(windows, newArrayList(xp)), equalTo(xp));
    assertThat(getBestMatch(windows, newArrayList(vista)), equalTo(vista));
  }

  @Test
  public void pickingXpFromVariousLists() {
    Capabilities any = capabilities("internet explorer", "", Platform.ANY, true);
    Capabilities windows = capabilities("internet explorer", "", Platform.WINDOWS, true);
    Capabilities xp = capabilities("internet explorer", "", Platform.XP, true);
    Capabilities vista = capabilities("internet explorer", "", Platform.VISTA, true);

    assertThat(getBestMatch(xp, newArrayList(any)), equalTo(any));
    assertThat(getBestMatch(xp, newArrayList(any, windows)), equalTo(windows));
    assertThat(getBestMatch(xp, newArrayList(windows, xp, vista)), equalTo(xp));
    assertThat(getBestMatch(xp, newArrayList(windows, xp)), equalTo(xp));
    assertThat(getBestMatch(xp, newArrayList(xp, vista)), equalTo(xp));
    assertThat(getBestMatch(xp, newArrayList(xp)), equalTo(xp));
    assertThat(getBestMatch(xp, newArrayList(vista)), equalTo(vista));
  }

  @Test
  public void pickingVistaFromVariousLists() {
    Capabilities any = capabilities("internet explorer", "", Platform.ANY, true);
    Capabilities windows = capabilities("internet explorer", "", Platform.WINDOWS, true);
    Capabilities xp = capabilities("internet explorer", "", Platform.XP, true);
    Capabilities vista = capabilities("internet explorer", "", Platform.VISTA, true);

    assertThat(getBestMatch(vista, newArrayList(any)), equalTo(any));
    assertThat(getBestMatch(vista, newArrayList(any, windows)), equalTo(windows));
    assertThat(getBestMatch(vista, newArrayList(windows, xp, vista)), equalTo(vista));
    assertThat(getBestMatch(vista, newArrayList(windows, xp)), equalTo(windows));
    assertThat(getBestMatch(vista, newArrayList(xp, vista)), equalTo(vista));
    assertThat(getBestMatch(vista, newArrayList(xp)), equalTo(xp));
    assertThat(getBestMatch(vista, newArrayList(vista)), equalTo(vista));
  }

  @Test
  public void pickingUnixFromVariousLists() {
    Capabilities any = capabilities("firefox", "", Platform.ANY, true);
    Capabilities mac = capabilities("firefox", "", Platform.MAC, true);
    Capabilities unix = capabilities("firefox", "", Platform.UNIX, true);
    Capabilities linux = capabilities("firefox", "", Platform.LINUX, true);

    assertThat(getBestMatch(unix, newArrayList(any)), equalTo(any));
    assertThat(getBestMatch(unix, newArrayList(any, mac)), equalTo(any));
    assertThat(getBestMatch(unix, newArrayList(any, unix)), equalTo(unix));
    assertThat(getBestMatch(unix, newArrayList(any, unix, linux)), equalTo(unix));
    assertThat(getBestMatch(unix, newArrayList(unix, linux)), equalTo(unix));
    assertThat(getBestMatch(unix, newArrayList(linux)), equalTo(linux));
  }

  @Test
  public void pickingLinuxFromVariousLists() {
    Capabilities any = capabilities("firefox", "", Platform.ANY, true);
    Capabilities mac = capabilities("firefox", "", Platform.MAC, true);
    Capabilities unix = capabilities("firefox", "", Platform.UNIX, true);
    Capabilities linux = capabilities("firefox", "", Platform.LINUX, true);

    assertThat(getBestMatch(linux, newArrayList(any)), equalTo(any));
    assertThat(getBestMatch(linux, newArrayList(any, mac)), equalTo(any));
    assertThat(getBestMatch(linux, newArrayList(any, unix)), equalTo(unix));
    assertThat(getBestMatch(linux, newArrayList(any, unix, linux)), equalTo(linux));
    assertThat(getBestMatch(linux, newArrayList(unix, linux)), equalTo(linux));
    assertThat(getBestMatch(linux, newArrayList(linux)), equalTo(linux));
    assertThat(getBestMatch(linux, newArrayList(unix)), equalTo(unix));
  }

  @Test
  public void matchesByCapabilitiesProvided() {
    DesiredCapabilities sparse = new DesiredCapabilities();
    sparse.setBrowserName("firefox");

    Capabilities windows = capabilities("internet explorer", "", Platform.WINDOWS, true);
    Capabilities firefox = capabilities("firefox", "", Platform.WINDOWS, true);

    assertThat(getBestMatch(sparse, Lists.newArrayList(windows, firefox)),
        equalTo(firefox));

    sparse.setBrowserName("internet explorer");
    assertThat(getBestMatch(sparse, Lists.newArrayList(windows, firefox)),
        equalTo(windows));
  }

  private void assertGreaterThan(Capabilities a, Capabilities b) {
    assertThat(comparator.compare(a, b), greaterThan(0));
    assertThat(comparator.compare(b, a), lessThan(0));
  }

  private static Comparator<Capabilities> compareBy(Capabilities capabilities) {
    return new CapabilitiesComparator(capabilities);
  }

  private static Capabilities capabilities(String browserName, String version,
      Platform platform, boolean isJavaScriptEnabled) {
    DesiredCapabilities dc = new DesiredCapabilities(browserName, version, platform);
    dc.setJavascriptEnabled(isJavaScriptEnabled);
    return dc;
  }

}


text:
// 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.

#include <string>

#include "gandiva/configuration.h"
#include "gandiva/jni/config_holder.h"
#include "gandiva/jni/env_helper.h"
#include "jni/org_apache_arrow_gandiva_evaluator_ConfigurationBuilder.h"

using gandiva::ConfigHolder;
using gandiva::Configuration;
using gandiva::ConfigurationBuilder;

/*
 * Class:     org_apache_arrow_gandiva_evaluator_ConfigBuilder
 * Method:    buildConfigInstance
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL
Java_org_apache_arrow_gandiva_evaluator_ConfigurationBuilder_buildConfigInstance(
    JNIEnv* env, jobject configuration) {
  ConfigurationBuilder configuration_builder;
  std::shared_ptr<Configuration> config = configuration_builder.build();
  return ConfigHolder::MapInsert(config);
}

/*
 * Class:     org_apache_arrow_gandiva_evaluator_ConfigBuilder
 * Method:    buildConfigInstance
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL
Java_org_apache_arrow_gandiva_evaluator_ConfigurationBuilder_buildConfigInstance(
    JNIEnv* env, jobject configuration, jboolean optimize) {
  ConfigurationBuilder configuration_builder;
  std::shared_ptr<Configuration> config = configuration_builder.build(optimize);
  return ConfigHolder::MapInsert(config);
}

/*
 * Class:     org_apache_arrow_gandiva_evaluator_ConfigBuilder
 * Method:    releaseConfigInstance
 * Signature: (J)V
 */
JNIEXPORT void JNICALL
Java_org_apache_arrow_gandiva_evaluator_ConfigurationBuilder_releaseConfigInstance(
    JNIEnv* env, jobject configuration, jlong config_id) {
  ConfigHolder::MapErase(config_id);
}


text:
@interface TestMantleModel : MTLModel <MTLJSONSerializing>

@property (nonatomic, copy) NSString *show;

@end

@implementation TestMantleModel

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
    return nil;
}

@end

@interface TestJSONModel : JSONModel

@end

@implementation TestJSONModel

@end

@interface TestObjectModel : NSObject

@property (nonatomic, copy) NSString *show;

@end

@implementation TestObjectModel

@end

@interface GQModelAdapterTests : XCTestCase

@property (nonatomic, copy) NSDictionary *jsonObject;

@property (nonatomic, copy) NSArray *jsonArray;

@end

@implementation GQModelAdapterTests

- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.

    self.jsonObject = @{@"show" : @"me"};

    self.jsonArray = @[self.jsonObject];
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testDefaultAdapter
{
    GQDefaultAdapter *adapter = [[GQDefaultAdapter alloc] initWithJSONObject:self.jsonObject modelClass:nil];

    XCTAssertTrue([[adapter modelObject] isKindOfClass:[NSDictionary class]]);

    XCTAssertNil([adapter modelObjectList]);
}

- (void)testDefaultAdapter2
{
    GQDefaultAdapter *adapter = [[GQDefaultAdapter alloc] initWithJSONObject:self.jsonArray modelClass:nil];

    XCTAssertTrue([[adapter modelObjectList][0] isKindOfClass:[NSDictionary class]]);

    XCTAssertNil([adapter modelObject]);
}

- (void)testMantleAdapter
{
    GQMantleAdapter *adapter = [[GQMantleAdapter alloc] initWithJSONObject:self.jsonObject
                                                                modelClass:[TestMantleModel class]];

    XCTAssertTrue([[adapter modelObject] isKindOfClass:[TestMantleModel class]]);

    XCTAssertNil([adapter modelObjectList]);
}

- (void)testMantleAdapter2
{
    GQMantleAdapter *adapter = [[GQMantleAdapter alloc] initWithJSONObject:self.jsonArray
                                                                modelClass:[TestMantleModel class]];

    XCTAssertTrue([[adapter modelObjectList][0] isKindOfClass:[TestMantleModel class]]);

    XCTAssertNil([adapter modelObject]);
}

- (void)testJSONModelAdapter
{
    GQJSONModelAdapter *adapter = [[GQJSONModelAdapter alloc] initWithJSONObject:self.jsonObject modelClass:[TestJSONModel class]];

    XCTAssertTrue([[adapter modelObject] isKindOfClass:[TestJSONModel class]]);

    XCTAssertNil([adapter modelObjectList]);
}

- (void)testJSONModelAdapter2
{
    GQJSONModelAdapter *adapter = [[GQJSONModelAdapter alloc] initWithJSONObject:self.jsonArray modelClass:[TestJSONModel class]];

    XCTAssertTrue([[adapter modelObjectList][0] isKindOfClass:[TestJSONModel class]]);

    XCTAssertNil([adapter modelObject]);
}

- (void)testYYModelAdapter
{
    GQYYModelAdapter *adapter = [[GQYYModelAdapter alloc] initWithJSONObject:self.jsonObject modelClass:[TestObjectModel class]];

    XCTAssertTrue([[adapter modelObject] isKindOfClass:[TestObjectModel class]]);

    XCTAssertNil([adapter modelObjectList]);
}

- (void)testYYModelAdapter2
{
    GQYYModelAdapter *adapter = [[GQYYModelAdapter alloc] initWithJSONObject:self.jsonArray modelClass:[TestObjectModel class]];

    XCTAssertTrue([[adapter modelObjectList][0] isKindOfClass:[TestObjectModel class]]);

    XCTAssertNil([adapter modelObject]);
}

- (void)testMJExtensionAdapter
{
    GQMJExtensionAdapter *adapter = [[GQMJExtensionAdapter alloc] initWithJSONObject:self.jsonObject modelClass:[TestObjectModel class]];

    XCTAssertTrue([[adapter modelObject] isKindOfClass:[TestObjectModel class]]);

    XCTAssertNil([adapter modelObjectList]);
}

- (void)testMJExtensionAdapter2
{
    GQMJExtensionAdapter *adapter = [[GQMJExtensionAdapter alloc] initWithJSONObject:self.jsonArray modelClass:[TestObjectModel class]];

    XCTAssertTrue([[adapter modelObjectList][0] isKindOfClass:[TestObjectModel class]]);

    XCTAssertNil([adapter modelObject]);
}

@end


text:
namespace GlobalcachingApplication.Plugins.GAPPDataStorage
{
    partial class SettingsPanel
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.numericUpDown2 = new System.Windows.Forms.NumericUpDown();
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).BeginInit();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(15, 15);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(95, 17);
            this.label1.TabIndex = 0;
            this.label1.Text = "Backup folder";
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(18, 34);
            this.textBox1.Name = "textBox1";
            this.textBox1.ReadOnly = true;
            this.textBox1.Size = new System.Drawing.Size(371, 22);
            this.textBox1.TabIndex = 1;
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(395, 33);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(31, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "...";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // numericUpDown1
            //
            this.numericUpDown1.Location = new System.Drawing.Point(378, 63);
            this.numericUpDown1.Name = "numericUpDown1";
            this.numericUpDown1.Size = new System.Drawing.Size(48, 22);
            this.numericUpDown1.TabIndex = 3;
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(15, 65);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(274, 17);
            this.label2.TabIndex = 4;
            this.label2.Text = "Remove older then days (0=don\'t remove)";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(15, 93);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(268, 17);
            this.label3.TabIndex = 6;
            this.label3.Text = "Keep maximum backups (0=no maximum)";
            //
            // numericUpDown2
            //
            this.numericUpDown2.Location = new System.Drawing.Point(378, 91);
            this.numericUpDown2.Name = "numericUpDown2";
            this.numericUpDown2.Size = new System.Drawing.Size(48, 22);
            this.numericUpDown2.TabIndex = 5;
            //
            // SettingsPanel
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.label3);
            this.Controls.Add(this.numericUpDown2);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.numericUpDown1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.Name = "SettingsPanel";
            this.Size = new System.Drawing.Size(463, 175);
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.NumericUpDown numericUpDown1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.NumericUpDown numericUpDown2;
    }
}


text:
class CustomHandlerController < ApplicationController

# Implementation of server callback for Ubudu uBeacon SDK grammar
#
# @params format [Symbol] the format type, `:json`
# @params case [String] the test_case you want to test
# @return [JSON] the response a JSON object in the format that can be handled by the UbuduSDK.
# the format is a json containing {decision : "enable"|"disable"|"notify", optional_parameters (notify_user, open_url, open_pbk, data)}
# Example : /custom_handler/execute_callback?case=enable&data_type=beacon&id=3
  def execute_callback
    test_case = params[:case]
    response = Hash.new
    response[:version] = 3
    extra = {}
    err=false
    case test_case
    when "disable"
      #Simulate a decision to halt the execution of the action stored on the client.
      response[:decision] = "disable"
    when "sms"
      response[:decision] = "disable"
      #Simulate a decision to halt the execution of the action stored on the client and trigger an action on the server i.e. sending an SMS
      #Now for instance trigger an SMS to be send or a push notification
      # Add your own implementation here
      #SmsHelper::send_sms("xxxxxxxx","Alerte VIP","xxx en magasin")
    when "enable"
      response[:decision] = "enable"
      if (params[:data_type] && params[:id])
        data_type=params[:data_type]
        case data_type
        when "geofence"
           #Simulate a decision to continue execution of the action but provide "fresh" data to the client to execute the action
           # Now get the stored informations on the geofence and return it back
           # Add your own implementation here
           # geofence = UGeofence.where(:id => params[:id]).first
           # response[:data] = geofence.as_json({:api_version => 2})
        when "beacon"
              #Simulate a decision to continue execution of the action but provide "fresh" data to the client to execute the action
             # Now get the stored informations on the beacon and return it back
             # Add your own implementation here
             #beacon = UBeacon.where(:id => params[:id]).first
             #response[:data] = beacon.as_json({:api_version => 2})
        end
      end
    when "notify_user"
       #Simulate a decision to overule locally stored actions with a simple notification message without custom payload
      # Add your own implementation here
      response[:notify_user] = "{\"alertBody\":\"This is a simple notification message\",\"payload\": {} }"
    when "open_url"
      response[:decision] = "notify"
      #Simulate a decision to overule locally stored actions with notification message following by the opening of an URL in a web-view
      # Add your own implementation here
      response[:notify_user] =  "{\"alertBody\":\"This is a notification redirecting to Yahoo\",\"payload\": {} }"
      response[:open_url] = "http://www.yahoo.com"
    when "open_pbk"
      response[:decision] = "notify"
      #Simulate a decision to overule locally stored actions with notification message following by the opening of a passbook indicated in a URL
      #Add your own implementation here
      response[:notify_user] = "{\"alertBody\":\"Benefit from a coupon\",\"payload\": {} }"
      response[:open_pbk] = "https://deals-images-eu-prod.s3.amazonaws.com/passbooks/atollesopticiens_passid73_coupon__ucodenone_2013-06-14.pkpass"
    when "err"
      #Simulate an error on the server
      #Add your own implementation here
      err=true
    end
    if (!err)
     respond_to do |format|
       # the format is a json containing {decision : "enable"|"disable"|"notify", optional_parameters (notify_user, open_url, open_pbk, data)}
       format.json  { render :json => response }
      end
    else
      respond_to do |format|
       format.json  { render :json => {"error" => "fake_error"}, :status => 420 }
      end
    end
  end

end


text:
package com.sedsoftware.xyzreader.injection.modules;

import android.app.Application;
import android.content.Context;
import com.jakewharton.rxrelay2.BehaviorRelay;
import com.sedsoftware.xyzreader.data.RequestState;
import com.sedsoftware.xyzreader.data.remote.ArticlesService;
import com.sedsoftware.xyzreader.data.remote.ServiceFactory;
import com.sedsoftware.xyzreader.injection.ApplicationContext;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;

@Module
public class ApplicationModule {

  private final Application application;

  public ApplicationModule(Application application) {
    this.application = application;
  }

  @Provides
  @ApplicationContext
  Context provideContext() {
    return application;
  }

  @Provides
  Application provideApplication() {
    return application;
  }

  @Provides
  @Singleton
  ArticlesService provideArticlesService() {
    return ServiceFactory.createFrom(ArticlesService.class, ArticlesService.ENDPOINT);
  }

  @Provides
  @Singleton
  BehaviorRelay<Integer> provideBehaviorRelay() {
    return BehaviorRelay.createDefault(RequestState.IDLE);
  }
}


text:
*******
CANTERA
*******

Version 2.2.0 (stable)

License Information
===================

See the file "License.txt" for information on the terms & conditions for usage,
and a DISCLAIMER OF ALL WARRANTIES.

All trademarks referenced herein are property of their respective holders.

Web Resources
=============

1. *The Cantera Github site*

   https://github.com/Cantera/cantera

   This site contains the Cantera source code, the issue tracker for bugs and
   enhancement requests, downloads of Cantera releases and binary installers,
   and the Cantera wiki.

2. *The Cantera SourceForge site*

   http://sourceforge.net/projects/cantera

   Alternative download location for Cantera releases and binary installers.

3. *Cantera Documentation*

   http://cantera.github.com/docs/sphinx/html/index.html

   This site contains documentation for the current stable version of Cantera.

   http://cantera.github.com/dev-docs/sphinx/html/index.html

   This site contains documentation for the development version of Cantera.

4. *The Cantera Users' Group*

   http://groups.google.com/group/cantera-users

   This site has a message board for discussions amongst Cantera users.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="numberOfPullUpdateReport">
        <item quantity="other">%d éléments mis à jour.</item>
        <item quantity="one">%d élément mis à jour.</item>
    </plurals>
    <plurals name="numberFoot">
        <item quantity="other">%s pieds</item>
        <item quantity="one">%s pied</item>
    </plurals>
    <plurals name="numberInch">
        <item quantity="other">%s pouces</item>
        <item quantity="one">%s pouce</item>
    </plurals>
    <plurals name="weight_match_user">
        <item quantity="other">%1$d matches.</item>
        <item quantity="one">%1$d match.</item>
    </plurals>
</resources>


text:
import fs from 'fs';
import path from 'path';
import {remote} from 'electron';

export function readdir(dirPath) {
	return new Promise(function(resolve, reject){
		fs.readdir(dirPath, function(err, dirListing){
			//check if there's an error with reading this directory.
			if(err) {
				reject(err);
				return;
			}
			//set up the parent directory, as this will be part of the folder listing
			let parentDirPath = path.resolve(dirPath, '..');
			let foldersInit = [];
			if(parentDirPath != dirPath) {
				let accessOk = true;
				try {
					fs.accessSync(parentDirPath, fs.R_OK);	//throws if there's a problem with access rights at the parent directory.
				} catch (e) {
					accessOk = false;
				}
				foldersInit.push({ name: '..', path: parentDirPath, info: fs.statSync(parentDirPath), readable: accessOk});
			}
			let { files, folders } = dirListing.reduce(function(prev, current){
				try {
					let fullPath = path.join(dirPath, current);
					let fileStats = fs.statSync(fullPath);
					let accessOk = true;
					try {
						fs.accessSync(fullPath, fs.R_OK);
					} catch (e) {
						accessOk = false;
					}
					let info = { name: current, path: fullPath, info: fileStats, readable: accessOk};
					if(fileStats.isDirectory()) {
						prev.folders.push(info);
					} else {
						prev.files.push(info);
					}
				} catch(e) {
					console.error(e);
				}
				return prev;
			}, { files: [], folders: foldersInit});

			resolve({folder: dirPath, files, folders});
			return;
		});

	});
}


text:
var tests = [
  {
    name: "HTTP cache uses content after PATCH request with response containing Content-Location and cache-allowing header",
    requests: [
      {
        request_method: "PATCH",
        request_body: "abc",
        response_status: [200, "OK"],
        response_headers: [
          ['Cache-Control', "private, max-age=1000"],
          ['Content-Location', ""]
        ],
        response_body: "abc"
      },
      {
        expected_type: "cached"
      }
    ]
  },
  {
    name: "HTTP cache uses content after POST request with response containing Content-Location and cache-allowing header",
    requests: [
      {
        request_method: "POST",
        request_body: "abc",
        response_status: [200, "OK"],
        response_headers: [
          ['Cache-Control', "private, max-age=1000"],
          ['Content-Location', ""]
        ],
        response_body: "abc"
      },
      {
        expected_type: "cached"
      }
    ]
  }
];
run_tests(tests);


text:
package com.github.lukaszkusek.xml.comparator;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

import com.github.lukaszkusek.xml.comparator.diff.DifferenceCode;
import com.github.lukaszkusek.xml.comparator.diff.DifferenceInformation;
import com.github.lukaszkusek.xml.comparator.node.Node;
import com.google.common.collect.Maps;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(value = Parameterized.class)
public class DifferenceInformationParametrizedTest {

    private Node node1;
    private Node node2;
    private String attributeName;
    private DifferenceCode differenceCode;

    private String expectedXpath;
    private String expectedMessage;

    public DifferenceInformationParametrizedTest(
            Node node1, Node node2, String attributeName, DifferenceCode differenceCode,
            String expectedXpath, String expectedMessage) {

        this.node1 = node1;
        this.node2 = node2;
        this.attributeName = attributeName;
        this.differenceCode = differenceCode;

        this.expectedXpath = expectedXpath;
        this.expectedMessage = expectedMessage;
    }

    @Parameterized.Parameters
    public static Collection<Object[]> parameters() {
        //@formatter:off
        return Arrays
                .asList(new Object[][]{
                        {new NodeBuilder().withXpath("/xpath1").get(),
                                new NodeBuilder().withXpath("/xpath2").get(),
                                null,
                                DifferenceCode.DIFFERENT_ROOT_NODE,
                                null,
                                "First root node: /xpath1 is different from second root node: /xpath2"},

                        {new NodeBuilder().withXpath("/xpath1").get(),
                                null,
                                null,
                                DifferenceCode.MISSING_ELEMENT_IN_SECOND_DOCUMENT,
                                "/xpath1",
                                "Xpath exists in first xml document but doesn't exist in second one."},

                        {null,
                                new NodeBuilder().withXpath("/xpath2").get(),
                                null,
                                DifferenceCode.MISSING_ELEMENT_IN_FIRST_DOCUMENT,
                                "/xpath2",
                                "Xpath exists in second xml document but doesn't exist in first one."},

                        {new NodeBuilder().withXpath("/xpath").withValue("value1").get(),
                                new NodeBuilder().withXpath("/xpath").withValue("value2").get(),
                                null,
                                DifferenceCode.DIFFERENT_VALUE,
                                "/xpath/text()",
                                "Value differs. First: value1. Second: value2"},

                        {new NodeBuilder().withXpath("/xpath").withAttribute("attribute", "value1").get(),
                                new NodeBuilder().withXpath("/xpath").withAttribute("attribute", "value2").get(),
                                "attribute",
                                DifferenceCode.DIFFERENT_ATTRIBUTE_VALUE,
                                "/xpath/@attribute",
                                "Attribute value differs. First: value1. Second: value2"},

                        {new NodeBuilder().withXpath("/xpath").get(),
                                new NodeBuilder().withXpath("/xpath").get(),
                                null,
                                DifferenceCode.INCORRECT_ORDER,
                                "/xpath",
                                "Element from first document exists in first in incorrect order."},
                });
        //@formatter:on
    }

    @Test
    public void shouldReturnXpath() {
        // given
        DifferenceInformation differenceInformation =
                new DifferenceInformation(node1, node2, attributeName, differenceCode);

        // when
        String xpath = differenceInformation.getXPath();

        // then
        assertThat(xpath).isEqualTo(expectedXpath);
    }

    @Test
    public void shouldReturnMessage() {
        // given
        DifferenceInformation differenceInformation =
                new DifferenceInformation(node1, node2, attributeName, differenceCode);

        // when
        String message = differenceInformation.getMessage();

        // then
        assertThat(message).isEqualTo(expectedMessage);
    }

    private static class NodeBuilder {
        private String xpath;
        private String value;
        private Map<String, String> attributes;

        private NodeBuilder() {
            attributes = Maps.newHashMap();
        }

        public NodeBuilder withXpath(String xpath) {
            this.xpath = xpath;
            return this;
        }

        public NodeBuilder withValue(String value) {
            this.value = value;
            return this;
        }

        public NodeBuilder withAttribute(String attribute, String value) {
            this.attributes.put(attribute, value);
            return this;
        }

        public Node get() {
            Node node = new Node(0, xpath);
            node.setValue(value);

            attributes.entrySet().forEach(attribute -> node.putAttribute(attribute.getKey(), attribute.getValue()));

            return node;
        }
    }
}


text:
'use strict';

const path = require('path');
const {app, Menu} = require('electron');

function bindClickEvent(menu) {
	menu.click = function (menuItem, browserWindow) {
		app.emit('menuitem-click', {
			event: menu.event,
			menuItem,
			browserWindow
		});
	};

	return menu;
}

module.exports = function (file, opts) {
	opts = opts || {
		appMenu: true
	};

	// read manifest listmenu
	// dynamic import is not supported in ES2015 import
	let manifest;

	if (typeof file === 'object') {
		manifest = file;
	} else {
		manifest = require(path.resolve(process.cwd(), file));
	}

	if (!manifest) {
		throw new Error('Invalud menu manifest file path');
	}

	let tpl = [];

	for (const list in manifest) {
		if (manifest[list].submenu) {
			for (const submenu of manifest[list].submenu) {
				// event custom prop will be replaced by click prop
				if (submenu.event) {
					bindClickEvent(submenu);
				}
			}
		}

		tpl = tpl.concat(manifest[list]);
	}

	const menu = Menu.buildFromTemplate(tpl);

	if (opts.appMenu) {
		app.on('ready', () => {
			Menu.setApplicationMenu(menu);
		});
	}

	return menu;
};


text:
from datetime import timedelta
import re

from django.utils import timezone
from django.db import transaction
from django.contrib.sessions.models import Session

from froide.helper.email_sending import (
    send_mail, mail_middleware_registry, mail_registry
)

from . import account_canceled, account_merged
from .models import User
from .tasks import make_account_private_task

POSTCODE_RE = re.compile(r'(\d{5})\s+(.*)')
TRAILING_COMMA = re.compile(r'\s*,\s*$')

EXPIRE_UNCONFIRMED_USERS_AGE = timedelta(days=30)
CANCEL_DEACTIVATED_USERS_AGE = timedelta(days=100)

def send_mail_users(subject, body, users,
              **kwargs):
    for user in users:
        send_mail_user(
            subject, body, user,
            **kwargs
        )

class OnlyActiveUsersMailMiddleware:
    def should_mail(self, mail_intent, context, email_kwargs):
        user = context.get('user')
        if not user:
            # No user, not our concern here
            return

        if not email_kwargs.get('ignore_active', False) and not user.is_active:
            return False
        if not user.email:
            return False

mail_middleware_registry.register(OnlyActiveUsersMailMiddleware())

def send_mail_user(subject, body, user: User,
                   ignore_active=False, **kwargs):
    if not ignore_active and not user.is_active:
        return
    if not user.email:
        return

    return send_mail(subject, body, user.email, bounce_check=False, **kwargs)

user_email = mail_registry.register(
    'account/emails/user_email',
    ('subject', 'body')
)

def send_template_mail(user: User, subject: str, body: str, **kwargs):
    mail_context = {
        'first_name': user.first_name,
        'last_name': user.last_name,
        'name': user.get_full_name(),
        'url': user.get_autologin_url('/'),
    }
    user_subject = subject.format(**mail_context)
    user_body = body.format(**mail_context)
    return user_email.send(
        user=user,
        context={
            'subject': user_subject,
            'body': user_body
        }, **kwargs
    )

def make_account_private(user):
    user.private = True
    user.save()

    make_account_private_task.delay(user.id)

def merge_accounts(old_user, new_user):
    account_merged.send(
        sender=User, old_user=old_user, new_user=new_user
    )
    start_cancel_account_process(old_user)

def move_ownership(model, attr, old_user, new_user, dupe=None):
    qs = model.objects.filter(**{attr: old_user})

    if dupe:
        collision_key = dupe[1]
        collision_list = model.objects.filter(
            **{attr: new_user}
        ).values_list(collision_key, flat=True)
        qs = qs.exclude(
            **{'%s__in' % collision_key: collision_list}
        )

    qs.update(**{attr: new_user})

    if dupe is None:
        return

    # rest are collisions, delete
    qs = model.objects.filter(**{attr: old_user}).delete()

def all_unexpired_sessions_for_user(user):
    user_sessions = []
    all_sessions = Session.objects.filter(expire_date__gte=timezone.now())
    for session in all_sessions:
        session_data = session.get_decoded()
        if user.pk == session_data.get('_auth_user_id'):
            user_sessions.append(session.pk)
    return Session.objects.filter(pk__in=user_sessions)

def delete_all_unexpired_sessions_for_user(user, session_to_omit=None):
    session_list = all_unexpired_sessions_for_user(user)
    if session_to_omit is not None:
        session_list.exclude(session_key=session_to_omit.session_key)
    session_list.delete()

def start_cancel_account_process(user, delete=False):
    from .tasks import cancel_account_task

    user.private = True
    user.email = None
    user.is_active = False
    user.set_unusable_password()
    user.date_deactivated = timezone.now()

    user.save()
    delete_all_unexpired_sessions_for_user(user)

    # Asynchronously delete account
    # So more expensive anonymization can run in the background
    cancel_account_task.delay(user.pk, delete=delete)

def cancel_user(user, delete=False):
    with transaction.atomic():
        account_canceled.send(sender=User, user=user)

    delete_all_unexpired_sessions_for_user(user)

    if delete:
        user.delete()
        return

    user.organization = ''
    user.organization_url = ''
    user.private = True
    user.terms = False
    user.address = ''
    user.profile_text = ''
    user.profile_photo.delete()
    user.save()
    user.first_name = ''
    user.last_name = ''
    user.is_trusted = False
    user.is_staff = False
    user.is_superuser = False
    user.is_active = False
    user.date_deactivated = timezone.now()
    user.is_deleted = True
    user.date_left = timezone.now()
    user.email = None
    user.set_unusable_password()
    user.username = 'u%s' % user.pk
    user.save()

def delete_unconfirmed_users():
    time_ago = timezone.now() - EXPIRE_UNCONFIRMED_USERS_AGE
    expired_users = User.objects.filter(
        is_active=False,
        is_deleted=False,
        last_login__isnull=True,
        date_joined__lt=time_ago
    )
    for user in expired_users:
        start_cancel_account_process(user, delete=True)

def delete_deactivated_users():
    time_ago = timezone.now() - CANCEL_DEACTIVATED_USERS_AGE
    expired_users = User.objects.filter(
        is_active=False,
        is_deleted=False,
        date_deactivated__lt=time_ago
    )
    for user in expired_users:
        start_cancel_account_process(user)

def parse_address(address):
    match = POSTCODE_RE.search(address)
    if match is None:
        return {}
    postcode = match.group(1)
    city = match.group(2)
    refined = address.replace(match.group(0), '').strip().splitlines()
    street = refined or ['']
    street = TRAILING_COMMA.sub('', street[0])
    return {
        'address': street,
        'postcode': postcode,
        'city': city
    }


text:
// Copyright 2014 Paul Hammond.
// This software is licensed under the MIT license, see LICENSE.txt for details.

/*
Stringfs encodes a net/http FileSystem into a string.

Most web applications require a number of static assets such as images,
CSS stylesheets etc. Stringfs provides a way to compile those assets into a
single application binary for easier deployment.

Usage:
    stringfs [flags] directory outputfile

Stringfs takes a directory and an output file. It encodes all files within the
directory into a string in specified output source file.

The flags are:
    -var
        The variable the encoded string will be assigned to. Defaults to
        "fileSystem"
    -pkg
        The package this file will be part of. If not specified stringfs will
        autodetect the package name by checking other files in the same
        directory.

The file created by stringfs does not declare the variable, it just assigns a
value. You are expected to declare the variable yourself in another file,
giving you control over initialization.

A typical usage is to declare the variable with a fallback value. This allows
you to remove the generated file during development, avoiding an extra
compilation step. For example:

    var assets http.FileSystem = http.Dir("./assets")

Alternatively you can initialize the variable and later check for the nil
value. For example:

	// at the top level
	var assets http.FileSystem

	// inside a function
	if assets == nil {
		// working with precompiled assets
	} else {
		// no precompiled assets
	}
*/
package main

import (
	"bytes"
	"flag"
	"fmt"
	"go/parser"
	"go/token"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"github.com/paulhammond/stringfs/fs"
)

func check(err error) {
	if err != nil {
		fmt.Println("error:", err)
		os.Exit(1)
	}
}

func findPackage(dir string) string {
	pkgs, err := parser.ParseDir(token.NewFileSet(), dir, nil, parser.PackageClauseOnly)
	check(err)
	if len(pkgs) != 1 {
		fmt.Println("Could not autodetect package name, try -pkg flag")
		os.Exit(1)
	}
	for pkg, _ := range pkgs {
		return pkg
	}
	panic("unreachable")
}

func main() {

	var varName = flag.String("var", "fileSystem", "Variable Name")
	var pkgName = flag.String("pkg", "", "Package Name")
	flag.Parse()

	logger := log.New(os.Stdout, "", 0)

	args := flag.Args()
	src := args[0]
	dest := args[1]
	destDir := filepath.Dir(dest)

	if *pkgName == "" {
		*pkgName = findPackage(destDir)
	}

	s, err := fs.CreateString(http.Dir(src), logger)
	check(err)

	code := new(bytes.Buffer)
	fmt.Fprintf(code, "// generated with `%v`\n\n", strings.Join(os.Args, " "))
	fmt.Fprintf(code, "package %s\n\n", *pkgName)
	fmt.Fprintf(code, "import \"github.com/paulhammond/stringfs/fs\"\n\n")
	fmt.Fprintf(code, "func init() {\n")
	fmt.Fprintf(code, "\t%s = fs.Must(fs.New(%q))\n", *varName, s)
	fmt.Fprintf(code, "}\n")

	err = os.MkdirAll(destDir, 0777)
	check(err)

	err = ioutil.WriteFile(dest, code.Bytes(), 0666)
	check(err)
	logger.Printf("Wrote %s", dest)
}


text:
var level     = require('level-test')()
var SubLevel  = require('level-sublevel')
var delay     = require('delay-stream')
var Model     = require('scuttlebutt/model')
var LevelScuttlebutt
              = require('../')
var MapReduce = require('map-reduce')
var Client    = require('../client')
var mac       = require('macgyver')().autoValidate()
var tape      = require('tape')

tape('test', function (t) {

  var A, B

  var db = SubLevel(level('level-scuttlebutt-test-A'))

  var schema = {
    test: function () {
      return Model()
    }
  }

  LevelScuttlebutt(db, 'test1', schema)

  db.views['all'] =
    MapReduce(db, 'all',
      function (key, scuttle, emit) {
        console.log(key.split('!'), scuttle)
        return emit(key.split('!'), 1)
      },
      function (acc, item) {
        return '' + (Number(acc) + Number(item))
      },
      '0'
    )

  //open a scuttlebutt, then close the connection to the database,
  //then reopen the connection, then the scuttlebutt should be reconnected.

  var local  = db.scuttlebutt
  var remote = Client(schema, 'test1-client')

  local.open('test!thing1',  mac(function remoteOpen (err, a) {
    if(err) t.fail(err)
    a.set('x', Math.random())
    a.set('y', Math.random())
    a.set('z', Math.random())
  }).once())

  local.open('test!thing2',  mac(function remoteOpen (err, a) {
    if(err) t.fail(err)
    a.set('x', Math.random())
    a.set('y', Math.random())
    a.set('z', Math.random())
  }).once())

  var rv = []
  var lv = []
  var ended = 0
  function onEnd () {
    if(!ended++) return
    t.deepEqual(rv, lv)
//    console.log(rv, lv)
//    console.log('passed?')
    t.end()
  }

  remote.view({
    name: 'all', range: ['test', true]
  }).on('data', function (data) {
    console.log('remote view', data)
    rv.push(data)
    if(rv.length > 1) onEnd()
  })

  local.view({
    name: 'all', range: ['test', true]
  }).on('data', function (data) {
    console.log('local view', data)
    lv.push(data)
    if(lv.length > 1) onEnd()
  })

  var ls = local.createRemoteStream()
  var rs = remote.createStream()

  ls.pipe(rs).pipe(ls)

})