text:
module ConnectNGame

  #The Prudent bot picks the move with the highest score.
  class Prudent < Player

    #Build the player
    def initialize(name = "Prudent")
      super(name, "Minimum tactical analysis with some defense.", :silicon)
    end

    #Make a move. This bot picks the move with the highest score.
    #
Parameters
    #* game - the game being played.
    #* piece - the piece to be played, 1 or 2.
    #
Returns
    #* A move, 1 .. rack.width
    def make_move(game, piece)
      #Compute the moves of the first ply.
      first_ply = (game.rack.weights.each_with_index.map do |weight, index|
        channel = index + 1
        [weight + game.rack.score_move(channel, piece), channel]
      end).sort.show_weights("Scan 1")

      #If we're done, stop.
      return first_ply.last[1] if first_ply.last[0] >= game.rack.order

      #Factor in the behavior of the opponent.
      (0...(first_ply.length)).each do |index|
        copy = game.rack.clone.deep_clone

        copy.rack[first_ply[index][1]-1] << piece
        first_ply[index][0] -= check_opponent(copy, (piece % 2) + 1)
      end

      first_ply.sort.show_weights("Scan 2").last[1]
    end

    #Check for the opponent's best moves at this level
    def check_opponent(rack, piece)
      threshold = rack.order - 1
      result = 0

      (1..rack.width).each do |channel|
        score = rack.score_move(channel, piece)
        score *= 2 if score > threshold
        result += score if score >= threshold
      end

      result
    end

    #The thrill of victory.
    def winners_comments
      "#{name} says 'Good moves must give way to better!'"
    end

    #The agony of defeat
    def losers_comments
      "#{name} says 'How could I have missed this?'"
    end

  end

  Player.players << Prudent.new
end


text:
package fi.mabrosim.shoppinglist.ui;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

import fi.mabrosim.shoppinglist.BuildConfig;
import fi.mabrosim.shoppinglist.tasks.ImportItemsTaskFactory;
import fi.mabrosim.shoppinglist.utils.Dog;

public class ImportFromFileActivity extends Activity {
    private static final int    FILE_SELECT_CODE = 0;
    private static final String TAG              = "ImportFromFileActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Dog.d(TAG, "onCreate: " + getIntent().getAction());
        Intent intent = getIntent();
        String action = intent.getAction();
        Uri uri = intent.getData();

        if (action != null) {
            if (action.compareTo(Intent.ACTION_VIEW) == 0) {
                String scheme = intent.getScheme();
                if (scheme != null && ((BuildConfig.DEBUG && scheme.compareTo(ContentResolver.SCHEME_FILE) == 0) ||
                        (scheme.compareTo(ContentResolver.SCHEME_CONTENT) == 0))) {
                    ImportItemsTaskFactory.createAndExecute(getApplicationContext(), uri);
                }
            }
            finish();
        } else {
            showFileChooser();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    // Get the Uri of the selected file
                    Uri uri = data.getData();
                    ImportItemsTaskFactory.createAndExecute(getApplicationContext(), uri);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
        finish();
    }

    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(
                    Intent.createChooser(intent, "Select a File to Upload"),
                    FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(this, "Please install a File Manager.",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Ems\Validation;

use Closure;
use Ems\Contracts\Core\Containers\ByTypeContainer;
use Ems\Contracts\Core\Subscribable;
use Ems\Contracts\Core\SupportsCustomFactory;
use Ems\Contracts\Validation\Validator;
use Ems\Contracts\Validation\ValidatorFabricationException;
use Ems\Contracts\Validation\ValidatorFactory as ValidatorFactoryContract;
use Ems\Core\Checker;
use Ems\Core\Exceptions\UnsupportedParameterException;
use Ems\Core\Patterns\SubscribableTrait;
use Ems\Core\Support\CustomFactorySupport;
use Ems\Validation\Validator as ValidatorObject;
use ReflectionException;

use function get_class;
use function is_callable;
use function is_object;
use function is_string;
use function spl_object_hash;

class ValidatorFactory implements ValidatorFactoryContract, SupportsCustomFactory, Subscribable
{
    use CustomFactorySupport {
        createWithoutFactory as traitCreateWithoutFactory;
    }
    use SubscribableTrait {
        on as traitOn;
    }

    /**
     * @var ByTypeContainer
     */
    protected $factories;

    /**
     * @var callable
     */
    protected $createFactory;

    /**
     * @var Validator|null
     */
    protected $lastPublishedValidator;

    public function __construct(callable $factory = null)
    {
        $this->factories = new ByTypeContainer();
        if ($factory) {
            $this->createObjectsBy($factory);
        }
    }

    /**
     * {@inheritDoc}
     *
     * @param array $rules
     * @param string $ormClass
     * @return Validator
     */
    public function create(array $rules, string $ormClass = ''): Validator
    {
        $factory = $this->getCreateFactory();
        if (!$ormClass) {
            return $factory($rules, $ormClass);
        }
        $validator = $factory($rules, $ormClass);
        $this->publish($ormClass, $validator);
        return $validator;
    }

    /**
     * {@inheritDoc}
     *
     * @param string $ormClass
     * @return Validator
     * @throws ValidatorFabricationException
     */
    public function get(string $ormClass): Validator
    {
        $validator = $this->validator($ormClass);
        $this->publish($ormClass, $validator);
        return $validator;
    }

    /**
     * {@inheritDoc}
     *
     * @param array $rules
     * @param array $input
     * @param object|null $ormObject
     * @param array $formats
     *
     * @return array
     */
    public function validate(array $rules, array $input, $ormObject = null, array $formats = []): array
    {
        $ormClass = is_object($ormObject) ? get_class($ormObject) : '';
        $validator = $this->create($rules, $ormClass);
        return $validator->validate($input, $ormObject, $formats);
    }

    /**
     * Register a validator for $ormClass.
     *
     * @param string $ormClass
     * @param string|callable $validatorClassOrFactory
     * @return void
     */
    public function register(string $ormClass, $validatorClassOrFactory)
    {
        $this->factories[$ormClass] = $this->checkAndReturn($validatorClassOrFactory);
    }

    /**
     * Get the factory that is used inside create.
     *
     * @return callable
     */
    public function getCreateFactory() : callable
    {
        if (!$this->createFactory) {
            $this->createFactory = $this->makeCreateFactory();
        }
        return $this->createFactory;
    }

    /**
     * Set the factory that is used in create.
     *
     * @param callable $factory
     * @return $this
     */
    public function setCreateFactory(callable $factory) : ValidatorFactory
    {
        $this->createFactory = $factory;
        return $this;
    }

    /**
     * Register a listener that gets informed if a validator for ormClass $event
     * is returned (by create or get).
     *
     * @param string $event The orm class
     * @param callable $listener
     *
     * @return ValidatorFactory
     */
    public function on($event, callable $listener) : ValidatorFactory
    {
        $this->traitOn($event, $listener);
        return $this;
    }

    /**
     * Use this method to forward resolving events from your container so that
     * the listeners will also be called.
     *
     * @param Validator $validator
     * @return void
     */
    public function forwardValidatorEvent(Validator $validator)
    {

        if (!$ormClass = $validator->ormClass()) {
            return;
        }
        $this->publish($ormClass, $validator);
    }

    /**
     * Make the default handler for creating fresh validators in self::create()
     *
     * @return Closure
     */
    protected function makeCreateFactory() : Closure
    {
        return function (array $rules, string $ormClass='') {
            return $this->createObject(ValidatorObject::class, [
                'rules'     => $rules,
                'ormClass'  => $ormClass,
                $this->createObject(CheckerBaseValidator::class)
            ]);
        };
    }

    /**
     * @param string $ormClass
     * @return Validator
     */
    protected function validator(string $ormClass) : Validator
    {
        if (!$factoryOrClass = $this->factories->forInstanceOf($ormClass)) {
            throw new ValidatorFabricationException("No handler registered for class '$ormClass'", ValidatorFabricationException::NO_FACTORY_FOR_ORM_CLASS);
        }

        try {
            $validator = is_callable($factoryOrClass) ? $factoryOrClass($ormClass) : $this->createObject($factoryOrClass);
        } catch (ReflectionException $e) {
            throw new ValidatorFabricationException(
                "ReflectionException while trying to create validator for '$ormClass'",
                ValidatorFabricationException::UNRESOLVABLE_BY_FACTORY,
                $e
            );
        }

        if ($validator instanceof Validator) {
            return $validator;
        }

        if (is_string($factoryOrClass)) {
            throw new ValidatorFabricationException(
                "The registered class or binding $factoryOrClass must implement " . Validator::class,
                ValidatorFabricationException::WRONG_TYPE_REGISTERED
            );
        }

        $type = is_object($factoryOrClass) ? get_class($factoryOrClass) : 'callable';

        throw new ValidatorFabricationException(
            "The registered factory of type '$type' did not return a " . Validator::class,
            ValidatorFabricationException::FACTORY_RETURNED_WRONG_TYPE
        );

    }

    /**
     * Check the factory before adding it.
     *
     * @param $validatorClassOrFactory
     * @return string|callable
     * @throws UnsupportedParameterException
     */
    protected function checkAndReturn($validatorClassOrFactory)
    {
        if ($validatorClassOrFactory instanceof Validator) {
            throw new UnsupportedParameterException("It is not allowed to register validators directly to avoid loading masses of classes on boot");
        }

        // Class or callable. Avoid checking for class existence to not load
        // files for nothing
        if (!is_string($validatorClassOrFactory) && !is_callable($validatorClassOrFactory)) {
            throw new UnsupportedParameterException('Factory has to be a class name or a callable.');
        }

        return $validatorClassOrFactory;
    }

    /**
     * Reimplemented over trait to accept class names.
     *
     * @param string $event
     * @return void
     */
    protected function checkEvent($event)
    {
        // Accept everything
    }

    /**
     * Overwritten in case of missing factory.
     *
     * @param string $abstract
     * @param array $parameters
     * @return CheckerBaseValidator|object
     * @throws ReflectionException
     */
    protected function createWithoutFactory($abstract, array $parameters = [])
    {
        if ($abstract === CheckerBaseValidator::class) {
            /** @noinspection PhpParamsInspection */
            return new CheckerBaseValidator($this->createObject(Checker::class));
        }
        return $this->traitCreateWithoutFactory($abstract, $parameters);
    }

    /**
     * Publish the validator by subscribable trait.
     *
     * @param string $ormClass
     * @param Validator $validator
     * @return void
     */
    protected function publish(string $ormClass, Validator $validator)
    {
        if ($this->isLastPublishedValidator($validator)) {
            return;
        }
        $this->lastPublishedValidator = $validator;
        $this->callOnListeners($ormClass, [$validator]);
    }

    /**
     * Check if the passed validator is the last published. This is needed to
     * avoid double events for validators.
     *
     * @param Validator $validator
     * @return bool
     */
    protected function isLastPublishedValidator(Validator $validator) : bool
    {
        if (!$this->lastPublishedValidator) {
            return false;
        }
        return spl_object_hash($validator) == spl_object_hash($this->lastPublishedValidator);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Elisha Mitchell scient. Soc. 55: 369 (1939)

#### Original name
Lepiota truncatispora Murrill

### Remarks
null


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @constructor
 * @param {MetadataCache} metadataCache Metadata cache service.
 * @param {cr.ui.ArrayDataModel} fileList The file list.
 * @param {boolean} showHidden If files starting with '.' are shown.
 */
function FileListContext(metadataCache, fileList, showHidden) {
  /**
   * @type {MetadataCache}
   */
  this.metadataCache = metadataCache;
  /**
   * @type {cr.ui.ArrayDataModel}
   */
  this.fileList = fileList;
  /**
   * @type Object.<string, Function>
   * @private
   */
  this.filters_ = {};
  this.setFilterHidden(!showHidden);
}

/**
 * @param {string} name Filter identifier.
 * @param {Function(Entry)} callback A filter — a function receiving an Entry,
 *     and returning bool.
 */
FileListContext.prototype.addFilter = function(name, callback) {
  this.filters_[name] = callback;
};

/**
 * @param {string} name Filter identifier.
 */
FileListContext.prototype.removeFilter = function(name) {
  delete this.filters_[name];
};

/**
 * @param {bool} value If do not show hidden files.
 */
FileListContext.prototype.setFilterHidden = function(value) {
  if (value) {
    this.addFilter(
        'hidden',
        function(entry) {return entry.name.substr(0, 1) !== '.';}
    );
  } else {
    this.removeFilter('hidden');
  }
};

/**
 * @return {boolean} If the files with names starting with "." are not shown.
 */
FileListContext.prototype.isFilterHiddenOn = function() {
  return 'hidden' in this.filters_;
};

/**
 * @param {Entry} entry File entry.
 * @return {bool} True if the file should be shown, false otherwise.
 */
FileListContext.prototype.filter = function(entry) {
  for (var name in this.filters_) {
    if (!this.filters_[name](entry))
      return false;
  }
  return true;
};

/**
 * This class is responsible for scanning directory (or search results),
 * and filling the fileList. Different descendants handle various types of
 * directory contents shown: basic directory, gdata search results, local search
 * results.
 * @constructor
 * @param {FileListContext} context The file list context.
 */
function DirectoryContents(context) {
  this.context_ = context;
  this.fileList_ = context.fileList;
  this.scanCompletedCallback_ = null;
  this.scanFailedCallback_ = null;
  this.scanCancelled_ = false;
  this.filter_ = context.filter.bind(context);
  this.allChunksFetched_ = false;
  this.pendingMetadataRequests_ = 0;
  this.fileList_.prepareSort = this.prepareSort_.bind(this);
}

/**
 * DirectoryModel extends cr.EventTarget.
 */
DirectoryContents.prototype.__proto__ = cr.EventTarget.prototype;

/**
 * Create the copy of the object, but without scan started.
 * @return {DirectoryContents} Object copy.
 */
DirectoryContents.prototype.clone = function() {
  return new DirectoryContents(this.context_);
};

/**
 * Use a given fileList instead of the fileList from the context.
 * @param {Array|cr.ui.ArrayDataModel} fileList The new file list.
 */
DirectoryContents.prototype.setFileList = function(fileList) {
  this.fileList_ = fileList;
  this.fileList_.prepareSort = this.prepareSort_.bind(this);
};

/**
 * Use the filelist from the context and replace its contents with the entries
 * from the current fileList.
 */
DirectoryContents.prototype.replaceContextFileList = function() {
  if (this.context_.fileList !== this.fileList_) {
    var spliceArgs = [].slice.call(this.fileList_);
    var fileList = this.context_.fileList;
    spliceArgs.unshift(0, fileList.length);
    fileList.splice.apply(fileList, spliceArgs);
    this.fileList_ = fileList;
  }
};

/**
 * @return {string} The path.
 */
DirectoryContents.prototype.getPath = function() {
  throw 'Not implemented.';
};

/**
 * @return {boolean} If the scan is active.
 */
DirectoryContents.prototype.isScanning = function() {
  return !this.scanCancelled_ &&
         (!this.allChunksFetched_ || this.pendingMetadataRequests_ > 0);
};

/**
 * @return {boolean} True if search results (gdata or local).
 */
DirectoryContents.prototype.isSearch = function() {
  return false;
};

/**
 * @return {DirectoryEntry} A DirectoryEntry for current directory. In case of
 *     search -- the top directory from which search is run
 */
DirectoryContents.prototype.getDirectoryEntry = function() {
  throw 'Not implemented.';
};

/**
 * @param {Entry} entry File entry for a file in current DC results.
 * @return {string} Display name.
 */
DirectoryContents.prototype.getDisplayName = function(entry) {
  return entry.name;
};

/**
 * Start directory scan/search operation. Either 'scan-completed' or
 * 'scan-failed' event will be fired upon completion.
 */
DirectoryContents.prototype.scan = function() {
  throw 'Not implemented.';
};

/**
 * Read next chunk of results from DirectoryReader.
 * @protected
 */
DirectoryContents.prototype.readNextChunk = function() {
  throw 'Not implemented.';
};

/**
 * Cancel the running scan.
 */
DirectoryContents.prototype.cancelScan = function() {
  this.scanCancelled_ = true;
  cr.dispatchSimpleEvent(this, 'scan-cancelled');
};

/**
 * Called in case scan has failed. Should send the event.
 * @protected
 */
DirectoryContents.prototype.onError = function() {
  cr.dispatchSimpleEvent(this, 'scan-failed');
};

/**
 * Called in case scan has completed succesfully. Should send the event.
 * @protected
 */
DirectoryContents.prototype.lastChunkReceived = function() {
  this.allChunksFetched_ = true;
  if (!this.scanCancelled_ && this.pendingMetadataRequests_ === 0)
    cr.dispatchSimpleEvent(this, 'scan-completed');
};

/**
 * Cache necessary data before a sort happens.
 *
 * This is called by the table code before a sort happens, so that we can
 * go fetch data for the sort field that we may not have yet.
 * @private
 * @param {string} field Sort field.
 * @param {function} callback Called when done.
 */
DirectoryContents.prototype.prepareSort_ = function(field, callback) {
  this.prefetchMetadata(this.fileList_.slice(), callback);
};

/**
 * @param {Array.<Entry>} entries Files.
 * @param {function} callback Callback on done.
 */
DirectoryContents.prototype.prefetchMetadata = function(entries, callback) {
  this.context_.metadataCache.get(entries, 'filesystem', callback);
};

/**
 * @protected
 * @param {Array.<Entry>} entries File list.
 */
DirectoryContents.prototype.onNewEntries = function(entries) {
  if (this.scanCancelled_)
    return;

  var entriesFiltered = [].filter.call(entries, this.filter_);

  var onPrefetched = function() {
    this.pendingMetadataRequests_--;
    if (this.scanCancelled_)
      return;
    this.fileList_.push.apply(this.fileList_, entriesFiltered);

    if (this.pendingMetadataRequests === 0 && this.allChunksFetched_) {
      cr.dispatchSimpleEvent(this, 'scan-completed');
    }

    if (!this.allChunksFetched_)
      this.readNextChunk();
  };

  this.pendingMetadataRequests_++;
  this.prefetchMetadata(entriesFiltered, onPrefetched.bind(this));
};

/**
 * @param {string} name Directory name.
 * @param {function} successCallback Called on success.
 * @param {function} errorCallback On error.
 */
DirectoryContents.prototype.createDirectory = function(
    name, successCallback, errorCallback) {
  throw 'Not implemented.';
};

/**
 * @constructor
 * @extends {DirectoryContents}
 * @param {FileListContext} context File list context.
 * @param {DirectoryEntry} entry DirectoryEntry for current directory.
 */
function DirectoryContentsBasic(context, entry) {
  DirectoryContents.call(this, context);
  this.entry_ = entry;
}

/**
 * Extends DirectoryContents
 */
DirectoryContentsBasic.prototype.__proto__ = DirectoryContents.prototype;

/**
 * Create the copy of the object, but without scan started.
 * @return {DirectoryContentsBasic} Object copy.
 */
DirectoryContentsBasic.prototype.clone = function() {
  return new DirectoryContentsBasic(this.context_, this.entry_);
};

/**
 * @return {string} Current path.
 */
DirectoryContentsBasic.prototype.getPath = function() {
  return this.entry_.fullPath;
};

/**
 * @return {DirectoryEntry?} DirectoryEntry of the current directory.
 */
DirectoryContentsBasic.prototype.getDirectoryEntry = function() {
  return this.entry_;
};

/**
 * Start directory scan.
 */
DirectoryContentsBasic.prototype.scan = function() {
  if (this.entry_ === DirectoryModel.fakeGDataEntry_)
    return;

  metrics.startInterval('DirectoryScan');
  this.reader_ = this.entry_.createReader();
  this.readNextChunk();
};

/**
 * Read next chunk of results from DirectoryReader.
 * @protected
 */
DirectoryContentsBasic.prototype.readNextChunk = function() {
  this.reader_.readEntries(this.onChunkComplete_.bind(this),
                           this.onError.bind(this));
};

/**
 * @private
 * @param {Array.<Entry>} entries File list.
 */
DirectoryContentsBasic.prototype.onChunkComplete_ = function(entries) {
  if (this.scanCancelled_)
    return;

  if (entries.length == 0) {
    this.lastChunkReceived();
    this.recordMetrics_();
    return;
  }

  this.onNewEntries(entries);
};

/**
 * @private
 */
DirectoryContentsBasic.prototype.recordMetrics_ = function() {
  metrics.recordInterval('DirectoryScan');
  if (this.entry_.fullPath === RootDirectory.DOWNLOADS) {
    metrics.recordMediumCount('DownloadsCount', this.fileList_.length);
  }
};

/**
 * @param {string} name Directory name.
 * @param {function} successCallback Called on success.
 * @param {function} errorCallback On error.
 */
DirectoryContentsBasic.prototype.createDirectory = function(
    name, successCallback, errorCallback) {
  var onSuccess = function(newEntry) {
    this.prefetchMetadata([newEntry], function() {successCallback(newEntry);});
  }

  this.entry_.getDirectory(name, {create: true, exclusive: true},
                           onSuccess.bind(this), errorCallback);
};

/**
 * Delay to be used for gdata search scan.
 * The goal is to reduce the number of server requests when user is typing the
 * query.
 */
DirectoryContentsGDataSearch.SCAN_DELAY = 200;

/**
 * Number of results at which we stop the search.
 * Note that max number of shown results is MAX_RESULTS + search feed size.
 */
DirectoryContentsGDataSearch.MAX_RESULTS = 999;

/**
 * @constructor
 * @extends {DirectoryContents}
 * @param {FileListContext} context File list context.
 * @param {DirectoryEntry} dirEntry Current directory.
 * @param {string} query Search query.
 */
function DirectoryContentsGDataSearch(context, dirEntry, query) {
  DirectoryContents.call(this, context);
  this.query_ = query;
  this.directoryEntry_ = dirEntry;
  this.nextFeed_ = '';
  this.done_ = false;
  this.fetchedResultsNum_ = 0;
}

/**
 * Extends DirectoryContents.
 */
DirectoryContentsGDataSearch.prototype.__proto__ = DirectoryContents.prototype;

/**
 * Create the copy of the object, but without scan started.
 * @return {DirectoryContentsBasic} Object copy.
 */
DirectoryContentsGDataSearch.prototype.clone = function() {
  return new DirectoryContentsGDataSearch(
      this.context_, this.directoryEntry_, this.query_);
};

/**
 * @return {boolean} True if this is search results (yes).
 */
DirectoryContentsGDataSearch.prototype.isSearch = function() {
  return true;
};

/**
 * @return {DirectoryEntry} DirectoryEntry for current directory.
 */
DirectoryContentsGDataSearch.prototype.getDirectoryEntry = function() {
  return this.directoryEntry_;
};

/**
 * @return {string} The path.
 */
DirectoryContentsGDataSearch.prototype.getPath = function() {
  return this.directoryEntry_.fullPath;
};

/**
 * Start directory scan.
 */
DirectoryContentsGDataSearch.prototype.scan = function() {
  // Let's give another search a chance to cancel us before we begin.
  setTimeout(this.readNextChunk.bind(this),
             DirectoryContentsGDataSearch.SCAN_DELAY);
};

/**
 * All the results are read in one chunk, so when we try to read second chunk,
 * it means we're done.
 */
DirectoryContentsGDataSearch.prototype.readNextChunk = function() {
  if (this.scanCancelled_)
    return;

  if (this.done_) {
    this.lastChunkReceived();
    return;
  }

  var searchCallback = (function(entries, nextFeed) {
    // TODO(tbarzic): Improve error handling.
    if (!entries) {
      console.log('Drive search encountered an error');
      this.lastChunkReceived();
      return;
    }
    this.nextFeed_ = nextFeed;
    this.fetchedResultsNum_ += entries.length;
    if (this.fetchedResultsNum_ >= DirectoryContentsGDataSearch.MAX_RESULTS)
      this.nextFeed_ = '';

    this.done_ = (this.nextFeed_ == '');
    this.onNewEntries(entries);
  }).bind(this);

  chrome.fileBrowserPrivate.searchGData(this.query_,
                                        this.nextFeed_,
                                        searchCallback);
};

/**
 * @constructor
 * @extends {DirectoryContents}
 * @param {FileListContext} context File list context.
 * @param {DirectoryEntry} dirEntry Current directory.
 * @param {string} query Search query.
 */
function DirectoryContentsLocalSearch(context, dirEntry, query) {
  DirectoryContents.call(this, context);
  this.directoryEntry_ = dirEntry;
  this.query_ = query.toLowerCase();
}

/**
 * Extends DirectoryContents
 */
DirectoryContentsLocalSearch.prototype.__proto__ = DirectoryContents.prototype;

/**
 * Create the copy of the object, but without scan started.
 * @return {DirectoryContentsBasic} Object copy.
 */
DirectoryContentsLocalSearch.prototype.clone = function() {
  return new DirectoryContentsLocalSearch(
      this.context_, this.directoryEntry_, this.query_);
};

/**
 * @return {string} The path.
 */
DirectoryContentsLocalSearch.prototype.getPath = function() {
  return this.directoryEntry_.fullPath;
};

/**
 * @return {boolean} True if search results (gdata or local).
 */
DirectoryContentsLocalSearch.prototype.isSearch = function() {
  return true;
};

/**
 * @return {DirectoryEntry} A DirectoryEntry for current directory. In case of
 *     search -- the top directory from which search is run
 */
DirectoryContentsLocalSearch.prototype.getDirectoryEntry = function() {
  return this.directoryEntry_;
};

/**
 * @param {Entry} entry File entry for a file in current DC results.
 * @return {string} Display name.
 */
DirectoryContentsLocalSearch.prototype.getDisplayName = function(entry) {
  return entry.name;
};

/**
 * Start directory scan/search operation. Either 'scan-completed' or
 * 'scan-failed' event will be fired upon completion.
 */
DirectoryContentsLocalSearch.prototype.scan = function() {
  this.pendingScans_ = 0;
  this.scanDirectory_(this.directoryEntry_);
};

/**
 * Scan a directory.
 * @param {DirectoryEntry} entry A directory to scan.
 * @private
 */
DirectoryContentsLocalSearch.prototype.scanDirectory_ = function(entry) {
  this.pendingScans_++;
  var reader = entry.createReader();
  var found = [];

  var onChunkComplete = function(entries) {
    if (this.scanCancelled_)
      return;

    if (entries.length === 0) {
      if (found.length > 0)
        this.onNewEntries(found);
      this.pendingScans_--;
      if (this.pendingScans_ === 0)
        this.lastChunkReceived();
      return;
    }

    for (var i = 0; i < entries.length; i++) {
      if (entries[i].name.toLowerCase().indexOf(this.query_) != -1) {
        found.push(entries[i]);
      }

      if (entries[i].isDirectory)
        this.scanDirectory_(entries[i]);
    }

    getNextChunk();
  }.bind(this);

  var getNextChunk = function() {
    reader.readEntries(onChunkComplete, this.onError.bind(this));
  }.bind(this);

  getNextChunk();
};

/**
 * We get results for each directory in one go in scanDirectory_.
 */
DirectoryContentsLocalSearch.prototype.readNextChunk = function() {
};


text:
using VocaDb.Model.Domain;

namespace VocaDb.Model.Service.Repositories {

	public interface IEntryReportRepository : IRepository<EntryReport> {

	}

}


text:
import random
try:
    from urllib.parse import urlparse, parse_qs
except ImportError:
    from urlparse import urlparse, parse_qs
import warnings
import json

from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.auth.models import AnonymousUser
from django.contrib.sites.models import Site
from django.conf import settings

from ..tests import MockedResponse, mocked_response, TestCase
from ..account import app_settings as account_settings
from ..account.models import EmailAddress
from ..account.utils import user_email, user_username
from ..utils import get_user_model, get_current_site

from .models import SocialApp, SocialAccount, SocialLogin
from .helpers import complete_social_login
from .views import signup
from . import providers

class OAuthTestsMixin(object):
    provider_id = None

    def get_mocked_response(self):
        pass

    def setUp(self):
        super(OAuthTestsMixin, self).setUp()
        self.provider = providers.registry.by_id(self.provider_id)
        app = SocialApp.objects.create(
            provider=self.provider.id,
            name=self.provider.id,
            client_id='app123id',
            key=self.provider.id,
            secret='dummy')
        app.sites.add(get_current_site())

    @override_settings(SOCIALACCOUNT_AUTO_SIGNUP=False)
    def test_login(self):
        resp_mocks = self.get_mocked_response()
        if resp_mocks is None:
            warnings.warn("Cannot test provider %s, no oauth mock"
                          % self.provider.id)
            return
        resp = self.login(resp_mocks)
        self.assertRedirects(resp, reverse('socialaccount_signup'))
        resp = self.client.get(reverse('socialaccount_signup'))
        sociallogin = resp.context['form'].sociallogin
        data = dict(email=user_email(sociallogin.user),
                    username=str(random.randrange(1000, 10000000)))
        resp = self.client.post(reverse('socialaccount_signup'),
                                data=data)
        self.assertRedirects(resp, 'http://testserver/accounts/profile/',
                             fetch_redirect_response=False)
        user = resp.context['user']
        self.assertFalse(user.has_usable_password())
        account = SocialAccount.objects.get(
            user=user,
            provider=self.provider.id)
        # The following lines don't actually test that much, but at least
        # we make sure that the code is hit.
        provider_account = account.get_provider_account()
        provider_account.get_avatar_url()
        provider_account.get_profile_url()
        provider_account.get_brand()
        provider_account.to_str()
        return account

    @override_settings(SOCIALACCOUNT_AUTO_SIGNUP=True,
                       SOCIALACCOUNT_EMAIL_REQUIRED=False,
                       ACCOUNT_EMAIL_REQUIRED=False)
    def test_auto_signup(self):
        resp_mocks = self.get_mocked_response()
        if not resp_mocks:
            warnings.warn("Cannot test provider %s, no oauth mock"
                          % self.provider.id)
            return
        resp = self.login(resp_mocks)
        self.assertRedirects(resp, 'http://testserver/accounts/profile/',
                             fetch_redirect_response=False)
        self.assertFalse(resp.context['user'].has_usable_password())

    def login(self, resp_mocks, process='login'):
        with mocked_response(MockedResponse(200,
                                            'oauth_token=token&'
                                            'oauth_token_secret=psst',
                                            {'content-type':
                                             'text/html'})):
            resp = self.client.get(reverse(self.provider.id + '_login'),
                                   dict(process=process))
        p = urlparse(resp['location'])
        q = parse_qs(p.query)
        complete_url = reverse(self.provider.id+'_callback')
        self.assertGreater(q['oauth_callback'][0]
                           .find(complete_url), 0)
        with mocked_response(self.get_access_token_response(),
                             *resp_mocks):
            resp = self.client.get(complete_url)
        return resp

    def get_access_token_response(self):
        return MockedResponse(
            200,
            'oauth_token=token&oauth_token_secret=psst',
            {'content-type': 'text/html'})

    def test_authentication_error(self):
        resp = self.client.get(reverse(self.provider.id + '_callback'))
        self.assertTemplateUsed(
            resp,
            'socialaccount/authentication_error.%s' % getattr(
                settings, 'ACCOUNT_TEMPLATE_EXTENSION', 'html'))

# For backward-compatibility with third-party provider tests that call
# create_oauth_tests() rather than using the mixin directly.
def create_oauth_tests(provider):
    class Class(OAuthTestsMixin, TestCase):
        provider_id = provider.id
    Class.__name__ = 'OAuthTests_' + provider.id
    return Class

class OAuth2TestsMixin(object):
    provider_id = None

    def get_mocked_response(self):
        pass

    def get_login_response_json(self, with_refresh_token=True):
        rt = ''
        if with_refresh_token:
            rt = ',"refresh_token": "testrf"'
        return """{
            "uid":"weibo",
            "access_token":"testac"
            %s }""" % rt

    def setUp(self):
        super(OAuth2TestsMixin, self).setUp()
        self.provider = providers.registry.by_id(self.provider_id)
        app = SocialApp.objects.create(provider=self.provider.id,
                                       name=self.provider.id,
                                       client_id='app123id',
                                       key=self.provider.id,
                                       secret='dummy')
        app.sites.add(get_current_site())

    @override_settings(SOCIALACCOUNT_AUTO_SIGNUP=False)
    def test_login(self):
        resp_mock = self.get_mocked_response()
        if not resp_mock:
            warnings.warn("Cannot test provider %s, no oauth mock"
                          % self.provider.id)
            return
        resp = self.login(resp_mock,)
        self.assertRedirects(resp, reverse('socialaccount_signup'))

    def test_account_tokens(self, multiple_login=False):
        email = 'some@mail.com'
        user = get_user_model().objects.create(
            username='user',
            is_active=True,
            email=email)
        user.set_password('test')
        user.save()
        EmailAddress.objects.create(user=user,
                                    email=email,
                                    primary=True,
                                    verified=True)
        self.client.login(username=user.username,
                          password='test')
        self.login(self.get_mocked_response(), process='connect')
        if multiple_login:
            self.login(
                self.get_mocked_response(),
                with_refresh_token=False,
                process='connect')
        # get account
        sa = SocialAccount.objects.filter(user=user,
                                          provider=self.provider.id).get()
        # The following lines don't actually test that much, but at least
        # we make sure that the code is hit.
        provider_account = sa.get_provider_account()
        provider_account.get_avatar_url()
        provider_account.get_profile_url()
        provider_account.get_brand()
        provider_account.to_str()
        # get token
        t = sa.socialtoken_set.get()
        # verify access_token and refresh_token
        self.assertEqual('testac', t.token)
        self.assertEqual(t.token_secret,
                         json.loads(self.get_login_response_json(
                             with_refresh_token=True)).get(
                                 'refresh_token', ''))

    def test_account_refresh_token_saved_next_login(self):
        """
        fails if a login missing a refresh token, deletes the previously
        saved refresh token. Systems such as google's oauth only send
        a refresh token on first login.
        """
        self.test_account_tokens(multiple_login=True)

    def login(self, resp_mock, process='login',
              with_refresh_token=True):
        resp = self.client.get(reverse(self.provider.id + '_login'),
                               dict(process=process))
        p = urlparse(resp['location'])
        q = parse_qs(p.query)
        complete_url = reverse(self.provider.id+'_callback')
        self.assertGreater(q['redirect_uri'][0]
                           .find(complete_url), 0)
        response_json = self \
            .get_login_response_json(with_refresh_token=with_refresh_token)
        with mocked_response(
                MockedResponse(
                    200,
                    response_json,
                    {'content-type': 'application/json'}),
                resp_mock):
            resp = self.client.get(complete_url,
                                   {'code': 'test',
                                    'state': q['state'][0]})
        return resp

    def test_authentication_error(self):
        resp = self.client.get(reverse(self.provider.id + '_callback'))
        self.assertTemplateUsed(
            resp,
            'socialaccount/authentication_error.%s' % getattr(
                settings, 'ACCOUNT_TEMPLATE_EXTENSION', 'html'))

# For backward-compatibility with third-party provider tests that call
# create_oauth2_tests() rather than using the mixin directly.
def create_oauth2_tests(provider):
    class Class(OAuth2TestsMixin, TestCase):
        provider_id = provider.id
    Class.__name__ = 'OAuth2Tests_' + provider.id
    return Class

class SocialAccountTests(TestCase):

    def setUp(self):
        super(SocialAccountTests, self).setUp()
        site = Site.objects.get_current()
        for provider in providers.registry.get_list():
            app = SocialApp.objects.create(
                provider=provider.id,
                name=provider.id,
                client_id='app123id',
                key='123',
                secret='dummy')
            app.sites.add(site)

    @override_settings(
        SOCIALACCOUNT_AUTO_SIGNUP=True,
        ACCOUNT_SIGNUP_FORM_CLASS=None,
        ACCOUNT_EMAIL_VERIFICATION=account_settings.EmailVerificationMethod.NONE  # noqa
    )
    def test_email_address_created(self):
        factory = RequestFactory()
        request = factory.get('/accounts/login/callback/')
        request.user = AnonymousUser()
        SessionMiddleware().process_request(request)
        MessageMiddleware().process_request(request)

        User = get_user_model()
        user = User()
        setattr(user, account_settings.USER_MODEL_USERNAME_FIELD, 'test')
        setattr(user, account_settings.USER_MODEL_EMAIL_FIELD, 'test@test.com')

        account = SocialAccount(provider='openid', uid='123')
        sociallogin = SocialLogin(user=user, account=account)
        complete_social_login(request, sociallogin)

        user = User.objects.get(
            **{account_settings.USER_MODEL_USERNAME_FIELD: 'test'}
        )
        self.assertTrue(
            SocialAccount.objects.filter(user=user, uid=account.uid).exists()
        )
        self.assertTrue(
            EmailAddress.objects.filter(user=user,
                                        email=user_email(user)).exists()
        )

    @override_settings(
        ACCOUNT_EMAIL_REQUIRED=True,
        ACCOUNT_UNIQUE_EMAIL=True,
        ACCOUNT_USERNAME_REQUIRED=True,
        ACCOUNT_AUTHENTICATION_METHOD='email',
        SOCIALACCOUNT_AUTO_SIGNUP=True)
    def test_email_address_clash_username_required(self):
        """Test clash on both username and email"""
        request, resp = self._email_address_clash(
            'test',
            'test@test.com')
        self.assertEqual(
            resp['location'],
            reverse('socialaccount_signup'))

        # POST different username/email to social signup form
        request.method = 'POST'
        request.POST = {
            'username': 'other',
            'email': 'other@test.com'}
        resp = signup(request)
        self.assertEqual(
            resp['location'], '/accounts/profile/')
        user = get_user_model().objects.get(
            **{account_settings.USER_MODEL_EMAIL_FIELD:
               'other@test.com'})
        self.assertEqual(user_username(user), 'other')

    @override_settings(
        ACCOUNT_EMAIL_REQUIRED=True,
        ACCOUNT_UNIQUE_EMAIL=True,
        ACCOUNT_USERNAME_REQUIRED=False,
        ACCOUNT_AUTHENTICATION_METHOD='email',
        SOCIALACCOUNT_AUTO_SIGNUP=True)
    def test_email_address_clash_username_not_required(self):
        """Test clash while username is not required"""
        request, resp = self._email_address_clash(
            'test',
            'test@test.com')
        self.assertEqual(
            resp['location'],
            reverse('socialaccount_signup'))

        # POST email to social signup form (username not present)
        request.method = 'POST'
        request.POST = {
            'email': 'other@test.com'}
        resp = signup(request)
        self.assertEqual(
            resp['location'], '/accounts/profile/')
        user = get_user_model().objects.get(
            **{account_settings.USER_MODEL_EMAIL_FIELD:
               'other@test.com'})
        self.assertNotEqual(user_username(user), 'test')

    @override_settings(
        ACCOUNT_EMAIL_REQUIRED=True,
        ACCOUNT_UNIQUE_EMAIL=True,
        ACCOUNT_USERNAME_REQUIRED=False,
        ACCOUNT_AUTHENTICATION_METHOD='email',
        SOCIALACCOUNT_AUTO_SIGNUP=True)
    def test_email_address_clash_username_auto_signup(self):
        # Clash on username, but auto signup still works
        request, resp = self._email_address_clash('test', 'other@test.com')
        self.assertEqual(
            resp['location'], '/accounts/profile/')
        user = get_user_model().objects.get(
            **{account_settings.USER_MODEL_EMAIL_FIELD:
               'other@test.com'})
        self.assertNotEqual(user_username(user), 'test')

    @override_settings(
        ACCOUNT_EMAIL_REQUIRED=True,
        ACCOUNT_USERNAME_BLACKLIST=['username', 'username1', 'username2'],
        ACCOUNT_UNIQUE_EMAIL=True,
        ACCOUNT_USERNAME_REQUIRED=True,
        ACCOUNT_AUTHENTICATION_METHOD='email',
        SOCIALACCOUNT_AUTO_SIGNUP=True)
    def test_populate_username_in_blacklist(self):
        factory = RequestFactory()
        request = factory.get('/accounts/twitter/login/callback/')
        request.user = AnonymousUser()
        SessionMiddleware().process_request(request)
        MessageMiddleware().process_request(request)

        User = get_user_model()
        user = User()
        setattr(user, account_settings.USER_MODEL_USERNAME_FIELD, 'username')
        setattr(user, account_settings.USER_MODEL_EMAIL_FIELD,
                'username@doe.com')

        account = SocialAccount(provider='twitter', uid='123')
        sociallogin = SocialLogin(user=user, account=account)
        complete_social_login(request, sociallogin)

        self.assertNotIn(request.user.username,
                         account_settings.USERNAME_BLACKLIST)

    def _email_address_clash(self, username, email):
        User = get_user_model()
        # Some existig user
        exi_user = User()
        user_username(exi_user, 'test')
        user_email(exi_user, 'test@test.com')
        exi_user.save()

        # A social user being signed up...
        account = SocialAccount(
            provider='twitter',
            uid='123')
        user = User()
        user_username(user, username)
        user_email(user, email)
        sociallogin = SocialLogin(user=user, account=account)

        # Signing up, should pop up the social signup form
        factory = RequestFactory()
        request = factory.get('/accounts/twitter/login/callback/')
        request.user = AnonymousUser()
        SessionMiddleware().process_request(request)
        MessageMiddleware().process_request(request)
        resp = complete_social_login(request, sociallogin)
        return request, resp

    def test_disconnect(self):
        User = get_user_model()
        # Some existig user
        user = User()
        user_username(user, 'test')
        user_email(user, 'test@test.com')
        user.set_password('test')
        user.save()

        account = SocialAccount.objects.create(
            uid='123',
            provider='twitter',
            user=user)

        self.client.login(
            username=user.username,
            password=user.username)
        resp = self.client.get(reverse('socialaccount_connections'))
        self.assertTemplateUsed(resp, 'socialaccount/connections.html')
        resp = self.client.post(
            reverse('socialaccount_connections'),
            {'account': account.pk})
        self.assertFalse(
            SocialAccount.objects.filter(pk=account.pk).exists())

    @override_settings(
        ACCOUNT_EMAIL_REQUIRED=True,
        ACCOUNT_EMAIL_VERIFICATION='mandatory',
        ACCOUNT_UNIQUE_EMAIL=True,
        ACCOUNT_USERNAME_REQUIRED=False,
        ACCOUNT_AUTHENTICATION_METHOD='email',
        SOCIALACCOUNT_AUTO_SIGNUP=False)
    def test_verified_email_change_at_signup(self):
        """
        Test scenario for when the user changes email at social signup. Current
        behavior is that both the unverified and verified email are added, and
        that the user is allowed to pass because he did provide a verified one.
        """
        session = self.client.session
        User = get_user_model()
        sociallogin = SocialLogin(
            user=User(
                email='verified@provider.com'),
            account=SocialAccount(
                provider='google'
            ),
            email_addresses=[
                EmailAddress(
                    email='verified@provider.com',
                    verified=True,
                    primary=True)])
        session['socialaccount_sociallogin'] = sociallogin.serialize()
        session.save()
        resp = self.client.get(reverse('socialaccount_signup'))
        form = resp.context['form']
        self.assertEquals(form['email'].value(), 'verified@provider.com')
        resp = self.client.post(
            reverse('socialaccount_signup'),
            data={'email': 'unverified@local.com'})
        self.assertRedirects(
            resp, '/accounts/profile/',
            fetch_redirect_response=False)
        user = User.objects.all()[0]
        self.assertEquals(
            user_email(user),
            'verified@provider.com'
        )
        self.assertTrue(
            EmailAddress.objects.filter(
                user=user,
                email='verified@provider.com',
                verified=True,
                primary=True
            ).exists())
        self.assertTrue(
            EmailAddress.objects.filter(
                user=user,
                email='unverified@local.com',
                verified=False,
                primary=False
            ).exists())

    @override_settings(
        ACCOUNT_EMAIL_REQUIRED=True,
        ACCOUNT_EMAIL_VERIFICATION='mandatory',
        ACCOUNT_UNIQUE_EMAIL=True,
        ACCOUNT_USERNAME_REQUIRED=False,
        ACCOUNT_AUTHENTICATION_METHOD='email',
        SOCIALACCOUNT_AUTO_SIGNUP=False)
    def test_unverified_email_change_at_signup(self):
        """
        Test scenario for when the user changes email at social signup, while
        his provider did not provide a verified email. In that case, email
        verification will kick in. Here, both email addresses are added as
        well.
        """
        session = self.client.session
        User = get_user_model()
        sociallogin = SocialLogin(
            user=User(
                email='unverified@provider.com'),
            account=SocialAccount(
                provider='google'
            ),
            email_addresses=[
                EmailAddress(
                    email='unverified@provider.com',
                    verified=False,
                    primary=True)])
        session['socialaccount_sociallogin'] = sociallogin.serialize()
        session.save()
        resp = self.client.get(reverse('socialaccount_signup'))
        form = resp.context['form']
        self.assertEquals(form['email'].value(), 'unverified@provider.com')
        resp = self.client.post(
            reverse('socialaccount_signup'),
            data={'email': 'unverified@local.com'})

        self.assertRedirects(resp, reverse('account_email_verification_sent'))
        user = User.objects.all()[0]
        self.assertEquals(
            user_email(user),
            'unverified@local.com'
        )
        self.assertTrue(
            EmailAddress.objects.filter(
                user=user,
                email='unverified@provider.com',
                verified=False,
                primary=False
            ).exists())
        self.assertTrue(
            EmailAddress.objects.filter(
                user=user,
                email='unverified@local.com',
                verified=False,
                primary=True
            ).exists())


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UmbracoCards.Models.Facebook
{
    class OAuthResponse
    {
    }
}


text:
using CrewChiefV3.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/**
 * Holds all the data collected from the memory mapped file for the current tick
 */
namespace CrewChiefV3.GameState
{
    public enum SessionType
    {
        Unavailable, Practice, Qualify, Race, HotLap
    }
    public enum SessionPhase
    {
        Unavailable, Garage, Gridwalk, Formation, Countdown, Green, Checkered, Finished
    }
    public enum ControlType
    {
        Unavailable, Player, AI, Remote, Replay
    }
    public enum PitWindow
    {
        Unavailable, Disabled, Closed, Open, StopInProgress, Completed
    }
    public enum TyreType
    {
        // separate enum for compound & weather, and prime / option?
        Hard, Medium, Soft, Wet, Intermediate, Prime, Option, Road, Bias_Ply, Unknown_Race
    }

    public enum BrakeType
    {
        // pretty coarse grained here.
        Iron_Road, Iron_Race, Ceramic, Carbon
    }

    public enum TyreCondition
    {
        UNKNOWN, NEW, SCRUBBED, MINOR_WEAR, MAJOR_WEAR, WORN_OUT
    }
    public enum TyreTemp
    {
        UNKNOWN, COLD, WARM, HOT, COOKING
    }
    public enum BrakeTemp
    {
        UNKNOWN, COLD, WARM, HOT, COOKING
    }
    public enum DamageLevel
    {
        UNKNOWN = 0, NONE = 1, TRIVIAL = 2, MINOR = 3, MAJOR = 4, DESTROYED = 5
    }
    public enum FlagEnum
    {
        // note that chequered isn't used at the moment
        GREEN, YELLOW, DOUBLE_YELLOW, BLUE, WHITE, BLACK, CHEQUERED, UNKNOWN
    }

    public class TransmissionData
    {
        // -2 = no data
        // -1 = reverse,
        //  0 = neutral
        //  1 = first gear
        // (... up to 7th)
        public int Gear = -2;
    }

    public class EngineData
    {
        // Engine speed
        public Single EngineRpm = 0;

        // Maximum engine speed
        public Single MaxEngineRpm = 0;

        // Unit: Celcius
        public Single EngineWaterTemp = 0;

        // Unit: Celcius
        public Single EngineOilTemp = 0;

        // Unit: ?
        public Single EngineOilPressure = 0;

        public int MinutesIntoSessionBeforeMonitoring = 0;

    }

    public class FuelData
    {
        // Unit: ?
        public Single FuelPressure = 0;

        // Current amount of fuel in the tank(s)
        // Unit: Liters (l)
        public Single FuelLeft = 0;

        // Maximum capacity of fuel tank(s)
        // Unit: Liters (l)
        public Single FuelCapacity = 0;

        public Boolean FuelUseActive = false;
    }

    public class CarDamageData
    {
        public Boolean DamageEnabled = false;

        public DamageLevel OverallTransmissionDamage = DamageLevel.UNKNOWN;

        public DamageLevel OverallEngineDamage = DamageLevel.UNKNOWN;

        public DamageLevel OverallAeroDamage = DamageLevel.UNKNOWN;

        public CornerData SuspensionDamageStatus = new CornerData();

        public CornerData BrakeDamageStatus = new CornerData();
    }

    public class SessionData
    {
        public List<String> formattedPlayerLapTimes = new List<String>();

        public TrackDefinition TrackDefinition = null;

        public Boolean IsDisqualified = false;

        public FlagEnum Flag = FlagEnum.GREEN;

        public Boolean IsNewSession = false;

        public Boolean SessionHasFixedTime = false;

        public SessionType SessionType = SessionType.Unavailable;

        public DateTime SessionStartTime;

        // in minutes, 0 if this session is a fixed number of laps rather than a fixed time.
        public float SessionRunTime = 0;

        public int SessionNumberOfLaps = 0;

        public int SessionStartPosition = 0;

        public int NumCarsAtStartOfSession = 0;

        // race number in ongoing championship (zero indexed)
        public int EventIndex = 0;

        // zero indexed - you multi iteration sessions like DTM qual
        public int SessionIteration = 0;

        // as soon as the player leaves the racing surface this is set to false
        public Boolean CurrentLapIsValid = true;

        public Boolean PreviousLapWasValid = true;

        public SessionPhase SessionPhase = SessionPhase.Unavailable;

        public Boolean IsNewLap = false;

        // How many laps the player has completed. If this value is 6, the player is on his 7th lap.
        public int CompletedLaps = 0;

        // Unit: Seconds (-1.0 = none)
        public Single LapTimePrevious = -1;

        public Single LapTimePreviousEstimateForInvalidLap = -1;

        // Unit: Seconds (-1.0 = none)
        public Single LapTimeCurrent = -1;

        public Boolean LeaderHasFinishedRace = false;

        // Current position (1 = first place)
        public int Position = 0;

        public int UnFilteredPosition = 0;

        public float GameTimeAtLastPositionFrontChange = 0;

        public float GameTimeAtLastPositionBehindChange = 0;

        // Number of cars (including the player) in the race
        public int NumCars = 0;

        public Single SessionRunningTime = 0;

        // ...
        public Single SessionTimeRemaining = 0;

        // ...
        public Single PlayerLapTimeSessionBest = -1;

        public Single OpponentsLapTimeSessionBestOverall = -1;

        public Single OpponentsLapTimeSessionBestPlayerClass = -1;

        public Single OverallSessionBestLapTime = -1;

        public Single PlayerClassSessionBestLapTime = -1;

        // ...
        public Single TimeDeltaFront = 0;

        // ...
        public Single TimeDeltaBehind = 0;

        // 0 means we don't know what sector we're in. This is 1-indexed
        public int SectorNumber = 0;

        public Boolean IsNewSector = false;

        // these are used for quick n dirty checks to see if we're racing the same opponent in front / behind,
        // without iterating over the Opponents list. Or for cases (like R3E) where we don't have an opponents list
        public Boolean IsRacingSameCarInFront = true;

        public Boolean IsRacingSameCarBehind = true;

        public Boolean HasLeadChanged = false;

        public Dictionary<int, float> SessionTimesAtEndOfSectors = new Dictionary<int, float>();

        public String DriverRawName;

        public float LastSector1Time = -1;
        public float LastSector2Time = -1;
        public float LastSector3Time = -1;

        // best sector times for the player
        public float PlayerBestSector1Time = -1;
        public float PlayerBestSector2Time = -1;
        public float PlayerBestSector3Time = -1;

        // sector times set on the player's fastest lap
        public float PlayerBestLapSector1Time = -1;
        public float PlayerBestLapSector2Time = -1;
        public float PlayerBestLapSector3Time = -1;

        // data sent by the game, rather than derived (useful for mid-session joining)
        public float SessionFastestLapTimeFromGame = -1;
        public float SessionFastestLapTimeFromGamePlayerClass = -1;

        public SessionData()
        {
            SessionTimesAtEndOfSectors.Add(1, -1);
            SessionTimesAtEndOfSectors.Add(2, -1);
            SessionTimesAtEndOfSectors.Add(3, -1);
        }
    }

    public class PositionAndMotionData
    {
        // Unit: Meter per second (m/s).
        public Single CarSpeed = 0;

        // distance (m) from the start line (around the track)
        public Single DistanceRoundTrack = 0;

        // other stuff like X/Y/Z co-ordinates, acceleration, orientation, ...
    }

    public class OpponentData
    {
        // set this to false if this opponent drops out of the race (i.e. leaves a server)
        public Boolean IsActive = true;

        // the name read directly from the game data - might be a 'handle' with all kinds of random crap in it
        public String DriverRawName = null;

        public int Position = 0;

        public int UnFilteredPosition = 0;

        public float SessionTimeAtLastPositionChange = -1;

        public int CompletedLaps = 0;

        public int CurrentSectorNumber = 0;

        public float Speed = 0;

        public float[] WorldPosition;

        public Boolean IsNewLap = false;

        public float DistanceRoundTrack = 0;

        public float CurrentBestLapTime = -1;

        public float PreviousBestLapTime = -1;

        public float bestSector1Time = -1;

        public float bestSector2Time = -1;

        public float bestSector3Time = -1;

        public float LastLapTime = -1;

        public Boolean LastLapValid = true;

        public List<LapData> OpponentLapData = new List<LapData>();

        public CarData.CarClass CarClass = CarData.getDefaultCarClass();

        // for DTM 2015
        public Boolean HasStartedExtraLap = false;

        public TyreType CurrentTyres = TyreType.Unknown_Race;

        public LapData getCurrentLapData()
        {
            if (OpponentLapData.Count > 0)
            {
                return OpponentLapData[OpponentLapData.Count - 1];
            }
            else
            {
                return null;
            }
        }

        public LapData getLastLapData()
        {
            if (OpponentLapData.Count > 1)
            {
                return OpponentLapData[OpponentLapData.Count - 2];
            }
            else
            {
                return null;
            }
        }

        public float[] getTimeAndSectorsForBestLapInWindow(int lapsToCheck)
        {
            float[] bestLapTimeAndSectorsSectors = new float[] {-1, -1, -1, -1};
            if (OpponentLapData.Count > 1)
            {
                if (lapsToCheck == -1)
                {
                    lapsToCheck = OpponentLapData.Count;
                }
                // count-2 because we're not interested in the current lap
                for (int i = OpponentLapData.Count - 2; i >= OpponentLapData.Count - lapsToCheck && i >= 0; i--)
                {
                    LapData thisLapTime = OpponentLapData[i];
                    if (bestLapTimeAndSectorsSectors[0] == -1 ||
                        (thisLapTime.IsValid && thisLapTime.LapTime != -1 && thisLapTime.LapTime < bestLapTimeAndSectorsSectors[0]))
                    {
                        bestLapTimeAndSectorsSectors[0] = thisLapTime.LapTime;
                        int sectorCount = thisLapTime.SectorTimes.Count();
                        if (sectorCount > 0)
                        {
                            bestLapTimeAndSectorsSectors[1] = thisLapTime.SectorTimes[0];
                        }
                        if (sectorCount > 1)
                        {
                            bestLapTimeAndSectorsSectors[2] = thisLapTime.SectorTimes[1];
                        }
                        if (sectorCount > 2)
                        {
                            bestLapTimeAndSectorsSectors[3] = thisLapTime.SectorTimes[2];
                        }
                    }
                }
            }
            return bestLapTimeAndSectorsSectors;
        }

        public Boolean isEnteringPits()
        {
            LapData currentLap = getCurrentLapData();
            return currentLap != null && currentLap.InLap;
        }

        public Boolean isExitingPits()
        {
            LapData currentLap = getCurrentLapData();
            return currentLap != null && currentLap.OutLap;
        }

        public float getLastLapTime()
        {
            LapData lastLap = getLastLapData();
            if (lastLap != null)
            {
                return lastLap.LapTime;
            }
            else
            {
                return -1;
            }
        }

        public float getGameTimeWhenSectorWasLastCompleted(int sectorNumber)
        {
            if (OpponentLapData.Count > 0)
            {
                if (OpponentLapData[OpponentLapData.Count - 1].GameTimeAtSectorEnd.Count > sectorNumber)
                {
                    return OpponentLapData[OpponentLapData.Count - 1].GameTimeAtSectorEnd[sectorNumber];
                }
            }
            if (OpponentLapData.Count > 1)
            {
                if (OpponentLapData[OpponentLapData.Count - 2].GameTimeAtSectorEnd.Count > sectorNumber)
                {
                    return OpponentLapData[OpponentLapData.Count - 2].GameTimeAtSectorEnd[sectorNumber];
                }
            }
            return -1;
        }

        public void StartNewLap(int lapNumber, int position, Boolean inPits, float gameTimeAtStart, Boolean isRaining, float trackTemp, float airTemp)
        {
            LapData thisLapData = new LapData();
            thisLapData.Conditions.Add(new LapConditions(isRaining, trackTemp, airTemp));
            thisLapData.GameTimeAtLapStart = gameTimeAtStart;
            thisLapData.OutLap = inPits;
            thisLapData.PositionAtStart = position;
            thisLapData.LapNumber = lapNumber;
            OpponentLapData.Add(thisLapData);
        }

        public void CompleteLapWithEstimatedLapTime(int position, float gameTimeAtLapEnd, float worldRecordLapTime,
            Boolean lapIsValid, Boolean isRaining, float trackTemp, float airTemp)
        {
            AddSectorData(position, -1, gameTimeAtLapEnd, lapIsValid, isRaining, trackTemp, airTemp);
            if (OpponentLapData.Count > 0)
            {
                LapData lapData = OpponentLapData[OpponentLapData.Count - 1];
                if (lapData.SectorTimes.Count > 2)
                {
                    float estimatedLapTime = lapData.SectorTimes.Sum();
                    LastLapValid = lapData.IsValid;
                    if (estimatedLapTime > worldRecordLapTime - 0.1)
                    {
                        lapData.LapTime = estimatedLapTime;
                        LastLapTime = estimatedLapTime;
                        if (lapData.IsValid && (CurrentBestLapTime == -1 || CurrentBestLapTime > lapData.LapTime))
                        {
                            PreviousBestLapTime = CurrentBestLapTime;
                            CurrentBestLapTime = lapData.LapTime;
                        }
                    }
                    else
                    {
                        LastLapValid = false;
                        LastLapTime = -1;
                    }
                }
            }
        }

        public void CompleteLapWithProvidedLapTime(int position, float gameTimeAtLapEnd, float providedLapTime,
            Boolean lapIsValid, Boolean isRaining, float trackTemp, float airTemp)
        {
            if (OpponentLapData.Count > 0)
            {
                LapData lapData = OpponentLapData[OpponentLapData.Count - 1];
                AddSectorData(position, providedLapTime, gameTimeAtLapEnd, lapIsValid, isRaining, trackTemp, airTemp);
                lapData.LapTime = providedLapTime;
                LastLapTime = providedLapTime;
                if (lapData.IsValid && (CurrentBestLapTime == -1 || CurrentBestLapTime > lapData.LapTime))
                {
                    PreviousBestLapTime = CurrentBestLapTime;
                    CurrentBestLapTime = lapData.LapTime;
                }
                LastLapValid = lapData.IsValid;
            }
        }

        public void AddSectorData(int position, float cumulativeSectorTime, float gameTimeAtSectorEnd, Boolean lapIsValid, Boolean isRaining, float trackTemp, float airTemp)
        {
            if (OpponentLapData.Count > 0)
            {
                LapData lapData = OpponentLapData[OpponentLapData.Count - 1];
                if (cumulativeSectorTime <= 0)
                {
                    cumulativeSectorTime = gameTimeAtSectorEnd - lapData.GameTimeAtLapStart;
                }
                float thisSectorTime = cumulativeSectorTime;
                int sectorNumber = 1;
                foreach (float sectorTime in lapData.SectorTimes)
                {
                    sectorNumber++;
                    thisSectorTime = thisSectorTime - sectorTime;
                }
                lapData.SectorTimes.Add(thisSectorTime);
                if (lapIsValid && thisSectorTime > 0)
                {
                    if (sectorNumber == 1 && (bestSector1Time == -1 || thisSectorTime < bestSector1Time))
                    {
                        bestSector1Time = thisSectorTime;
                    }
                    if (sectorNumber == 2 && (bestSector2Time == -1 || thisSectorTime < bestSector2Time))
                    {
                        bestSector2Time = thisSectorTime;
                    }
                    if (sectorNumber == 3 && (bestSector3Time == -1 || thisSectorTime < bestSector3Time))
                    {
                        bestSector3Time = thisSectorTime;
                    }
                }
                lapData.SectorPositions.Add(position);
                lapData.GameTimeAtSectorEnd.Add(gameTimeAtSectorEnd);
                if (lapData.IsValid && !lapIsValid)
                {
                    lapData.IsValid = false;
                }
                lapData.Conditions.Add(new LapConditions(isRaining, trackTemp, airTemp));
            }
        }

        public void setInLap()
        {
            if (OpponentLapData.Count > 0)
            {
                OpponentLapData[OpponentLapData.Count - 1].InLap = true;
            }
        }

        public OpponentDelta getTimeDifferenceToPlayer(SessionData playerSessionData)
        {

            int lastSectorPlayerCompleted = playerSessionData.SectorNumber == 1 ? 3 : playerSessionData.SectorNumber - 1;
            float playerLapTimeToUse = playerSessionData.LapTimePrevious;
            if (playerLapTimeToUse == 0 || playerLapTimeToUse == -1)
            {
                playerLapTimeToUse = playerSessionData.LapTimePreviousEstimateForInvalidLap;
            }

            if (playerSessionData.SessionTimesAtEndOfSectors[lastSectorPlayerCompleted] == -1 || getGameTimeWhenSectorWasLastCompleted(lastSectorPlayerCompleted - 1) == -1)
            {
                return null;
            }
            float timeDifference;
            if (Position == playerSessionData.Position + 1)
            {
                timeDifference = -1 * playerSessionData.TimeDeltaBehind;
            }
            else if (Position == playerSessionData.Position - 1)
            {
                timeDifference = playerSessionData.TimeDeltaFront;
            }
            else
            {
                timeDifference = playerSessionData.SessionTimesAtEndOfSectors[lastSectorPlayerCompleted] - getGameTimeWhenSectorWasLastCompleted(lastSectorPlayerCompleted - 1);
            }
            // if the player is ahead, the time difference is negative

            if (((playerSessionData.CompletedLaps == CompletedLaps + 1 && timeDifference < 0 && CurrentSectorNumber < playerSessionData.SectorNumber) ||
                playerSessionData.CompletedLaps > CompletedLaps + 1 ||
                (playerSessionData.CompletedLaps == CompletedLaps - 1 && timeDifference > 0 && CurrentSectorNumber >= playerSessionData.SectorNumber) ||
                playerSessionData.CompletedLaps < CompletedLaps - 1))
            {
                // there's more than a lap difference
                return new OpponentDelta(-1, playerSessionData.CompletedLaps - CompletedLaps);
            }
            else if (playerSessionData.CompletedLaps == CompletedLaps + 1 && timeDifference > 0)
            {
                // the player has completed 1 more lap but is behind on track
                return new OpponentDelta(timeDifference - playerLapTimeToUse, 0);
            }
            else if (playerSessionData.CompletedLaps == CompletedLaps - 1 && timeDifference < 0)
            {
                // the player has completed 1 less lap but is ahead on track
                return new OpponentDelta(playerLapTimeToUse - timeDifference, 0);
            }
            else
            {
                return new OpponentDelta(timeDifference, 0);
            }
        }

        public class OpponentDelta
        {
            public float time;
            public int lapDifference;
            public OpponentDelta(float time, int lapDifference)
            {
                this.time = time;
                this.lapDifference = lapDifference;
            }
        }
    }

    public class LapData
    {
        public int LapNumber = 0;
        public int PositionAtStart = 0;
        public Boolean IsValid = true;
        public float LapTime = -1;
        public float GameTimeAtLapStart = 0;
        public List<float> SectorTimes = new List<float>();
        public List<float> GameTimeAtSectorEnd = new List<float>();
        public List<LapConditions> Conditions = new List<LapConditions>();
        public List<int> SectorPositions = new List<int>();
        public Boolean OutLap = false;
        public Boolean InLap = false;
    }

    public class LapConditions
    {
        public Boolean Wet = false;
        public float TrackTemp = 30;
        public float AirTemp = 25;
        public LapConditions(Boolean wet, float trackTemp, float airTemp)
        {
            this.Wet = wet;
            this.TrackTemp = trackTemp;
            this.AirTemp = airTemp;
        }
    }

    public class ControlData
    {
        // ...
        public ControlType ControlType = ControlType.Unavailable;

        // ...
        public Single ThrottlePedal = 0;

        // ...
        public Single BrakePedal = 0;

        // ...
        public Single ClutchPedal = 0;

        // ...
        public Single BrakeBias = 0;
    }

    public class PitData
    {
        public PitWindow PitWindow = PitWindow.Unavailable;

        // The minute/lap into which you're allowed/obligated to pit
        // Unit: Minutes in time-based sessions, otherwise lap

        public Boolean InPitlane = false;

        public Boolean OnInLap = false;

        public Boolean OnOutLap = false;

        public Boolean IsMakingMandatoryPitStop = false;

        // this is true for one tick, when the player is about to exit the pits
        public Boolean IsAtPitExit = false;

        public Boolean IsRefuellingAllowed = false;

        public Boolean HasRequestedPitStop = false;

        public Boolean LeaderIsPitting = false;

        public Boolean CarInFrontIsPitting = false;

        public Boolean CarBehindIsPitting = false;

        // yuk...
        public OpponentData OpponentForLeaderPitting = null;
        public OpponentData OpponentForCarAheadPitting = null;
        public OpponentData OpponentForCarBehindPitting = null;

        // TODO: will this always be an Integer?
        public int PitWindowStart = 0;

        // The minute/lap into which you can/should pit
        // Unit: Minutes in time based sessions, otherwise lap
        public int PitWindowEnd = 0;

        public Boolean HasMandatoryPitStop = false;

        public Boolean HasMandatoryTyreChange = false;

        public Boolean HasMandatoryDriverChange = false;

        public TyreType MandatoryTyreChangeRequiredTyreType = TyreType.Unknown_Race;

        // might be a number of laps or a number of minutes. These are (currently) for DTM 2014. If we start on Options,
        // MaxPermittedDistanceOnCurrentTyre will be half race distance (rounded down), if we start on Primes
        // MinPermittedDistanceOnCurrentTyre will be half race distance (rounded up)
        public int MaxPermittedDistanceOnCurrentTyre = -1;
        public int MinPermittedDistanceOnCurrentTyre = -1;
    }

    public class PenatiesData
    {
        public Boolean HasDriveThrough = false;

        public Boolean HasStopAndGo = false;

        // from R3E data - what is this??
        public Boolean HasPitStop = false;

        public Boolean HasTimeDeduction = false;

        public Boolean HasSlowDown = false;

        // Number of penalties pending for the player
        public int NumPenalties = 0;

        // Total number of cut track warnings
        public int CutTrackWarnings = 0;

        public Boolean IsOffRacingSurface = false;
    }

    public class TyreData
    {
        public Boolean LeftFrontAttached = true;
        public Boolean RightFrontAttached = true;
        public Boolean LeftRearAttached = true;
        public Boolean RightRearAttached = true;

        public Boolean TireWearActive = false;

        // true if all tyres are the same type
        public Boolean HasMatchedTyreTypes = true;

        public TyreType FrontLeftTyreType = TyreType.Unknown_Race;
        public TyreType FrontRightTyreType = TyreType.Unknown_Race;
        public TyreType RearLeftTyreType = TyreType.Unknown_Race;
        public TyreType RearRightTyreType = TyreType.Unknown_Race;

        public Single FrontLeft_LeftTemp = 0;
        public Single FrontLeft_CenterTemp = 0;
        public Single FrontLeft_RightTemp = 0;

        public Single FrontRight_LeftTemp = 0;
        public Single FrontRight_CenterTemp = 0;
        public Single FrontRight_RightTemp = 0;

        public Single RearLeft_LeftTemp = 0;
        public Single RearLeft_CenterTemp = 0;
        public Single RearLeft_RightTemp = 0;

        public Single RearRight_LeftTemp = 0;
        public Single RearRight_CenterTemp = 0;
        public Single RearRight_RightTemp = 0;

        public Single PeakFrontLeftTemperatureForLap = 0;
        public Single PeakFrontRightTemperatureForLap = 0;
        public Single PeakRearLeftTemperatureForLap = 0;
        public Single PeakRearRightTemperatureForLap = 0;

        public float FrontLeftPercentWear = 0;
        public float FrontRightPercentWear = 0;
        public float RearLeftPercentWear = 0;
        public float RearRightPercentWear = 0;

        public Single FrontLeftPressure = 0;
        public Single FrontRightPressure = 0;
        public Single RearLeftPressure = 0;
        public Single RearRightPressure = 0;

        public CornerData TyreTempStatus = new CornerData();

        public CornerData TyreConditionStatus = new CornerData();

        public CornerData BrakeTempStatus = new CornerData();

        public Single LeftFrontBrakeTemp = 0;
        public Single RightFrontBrakeTemp = 0;
        public Single LeftRearBrakeTemp = 0;
        public Single RightRearBrakeTemp = 0;

        public Boolean LeftFrontIsLocked = false;
        public Boolean RightFrontIsLocked = false;
        public Boolean LeftRearIsLocked = false;
        public Boolean RightRearIsLocked = false;
        public Boolean LeftFrontIsSpinning = false;
        public Boolean RightFrontIsSpinning = false;
        public Boolean LeftRearIsSpinning = false;
        public Boolean RightRearIsSpinning = false;
    }

    public class Conditions
    {
        public class ConditionsSample
        {
            public DateTime Time;
            public int LapCount;
            public int SectorNumber;
            // copied straight from PCars
            public float AmbientTemperature;
            public float TrackTemperature;
            public float RainDensity;
            public float WindSpeed;
            public float WindDirectionX;
            public float WindDirectionY;
            public float CloudBrightness;

            public ConditionsSample(DateTime time, int lapCount, int sectorNumber, float AmbientTemperature, float TrackTemperature, float RainDensity,
                float WindSpeed, float WindDirectionX, float WindDirectionY, float CloudBrightness)
            {
                this.Time = time;
                this.LapCount = lapCount;
                this.SectorNumber = sectorNumber;
                this.AmbientTemperature = AmbientTemperature;
                this.TrackTemperature = TrackTemperature;
                this.RainDensity = RainDensity;
                this.WindSpeed = WindSpeed;
                this.WindDirectionX = WindDirectionX;
                this.WindDirectionY = WindDirectionY;
                this.CloudBrightness = CloudBrightness;
            }
        }

        public DateTime timeOfMostRecentSample = DateTime.MinValue;
        public List<ConditionsSample> samples = new List<ConditionsSample>();

        public void addSample(DateTime time, int lapCount, int sectorNumber, float AmbientTemperature, float TrackTemperature, float RainDensity,
                float WindSpeed, float WindDirectionX, float WindDirectionY, float CloudBrightness)
        {
            timeOfMostRecentSample = time;
            samples.Add(new ConditionsSample(time, lapCount, sectorNumber, AmbientTemperature, TrackTemperature, RainDensity,
                WindSpeed, WindDirectionX, WindDirectionY, CloudBrightness));
        }

        public ConditionsSample getMostRecentConditions()
        {
            if (samples.Count == 0)
            {
                return null;
            }
            else
            {
                return samples[samples.Count - 1];
            }
        }
    }

    public class OvertakingAids
    {
        public Boolean PushToPassAvailable = false;
	    public Boolean PushToPassEngaged = false;
	    public int PushToPassActivationsRemaining = 0;
	    public Single PushToPassEngagedTimeLeft = 0;
	    public Single PushToPassWaitTimeLeft = 0;

        public Boolean DrsEnabled = false;
        public Boolean DrsAvailable = false;
        public Boolean DrsEngaged = false;
        public Single DrsRange = 0;
    }

    public class GameStateData
    {
        public long Ticks;

        public DateTime Now;

        public CarData.CarClass carClass = CarData.getDefaultCarClass();

        public EngineData EngineData = new EngineData();

        public TransmissionData TransmissionData = new TransmissionData();

        public FuelData FuelData = new FuelData();

        public CarDamageData CarDamageData = new CarDamageData();

        public ControlData ControlData = new ControlData();

        public SessionData SessionData = new SessionData();

        public PitData PitData = new PitData();

        public PenatiesData PenaltiesData = new PenatiesData();

        public TyreData TyreData = new TyreData();

        public PositionAndMotionData PositionAndMotionData = new PositionAndMotionData();

        public Dictionary<Object, OpponentData> OpponentData = new Dictionary<Object, OpponentData>();

        public Conditions Conditions = new Conditions();

        public OvertakingAids OvertakingAids = new OvertakingAids();

        public GameStateData(long ticks)
        {
            this.Ticks = ticks;
            this.Now = new DateTime(ticks);
        }

        // some convenience methods
        public Boolean isLast()
        {
            return SessionData.UnFilteredPosition == SessionData.NumCars;
        }

        public List<String> getRawDriverNames()
        {
            List<String> rawDriverNames = new List<String>();
            foreach (KeyValuePair<Object, OpponentData> entry in OpponentData)
            {
                if (!rawDriverNames.Contains(entry.Value.DriverRawName))
                {
                    rawDriverNames.Add(entry.Value.DriverRawName);
                }
            }
            rawDriverNames.Sort();
            return rawDriverNames;
        }

        public OpponentData getOpponentAtPosition(int position, Boolean useUnfilteredPosition)
        {
            Object opponentKey = getOpponentKeyAtPosition(position, useUnfilteredPosition);
            if (opponentKey != null && OpponentData.ContainsKey(opponentKey))
            {
                return OpponentData[opponentKey];
            }
            else
            {
                return null;
            }
        }

        public Object getOpponentKeyInFrontOnTrack()
        {
            Object opponentKeyClosestInFront = null;
            Object opponentKeyFurthestBehind = null;
            float closestDistanceFront = SessionData.TrackDefinition.trackLength;
            float furthestDistanceBehind = 0;
            foreach (KeyValuePair<Object, OpponentData> opponent in OpponentData)
            {
                if (opponent.Value.Speed > 0.5 && !opponent.Value.isEnteringPits())
                {
                    if (opponent.Value.DistanceRoundTrack > PositionAndMotionData.DistanceRoundTrack &&
                        opponent.Value.DistanceRoundTrack - PositionAndMotionData.DistanceRoundTrack < closestDistanceFront)
                    {
                        closestDistanceFront = opponent.Value.DistanceRoundTrack - PositionAndMotionData.DistanceRoundTrack;
                        opponentKeyClosestInFront = opponent.Key;
                    }
                    else if (opponent.Value.DistanceRoundTrack < PositionAndMotionData.DistanceRoundTrack &&
                        PositionAndMotionData.DistanceRoundTrack - opponent.Value.DistanceRoundTrack > furthestDistanceBehind)
                    {
                        furthestDistanceBehind = PositionAndMotionData.DistanceRoundTrack - opponent.Value.DistanceRoundTrack;
                        opponentKeyFurthestBehind = opponent.Key;
                    }
                }
            }
            if (opponentKeyClosestInFront != null)
            {
                return opponentKeyClosestInFront;
            }
            else
            {
                return opponentKeyFurthestBehind;
            }
        }

        public Object getOpponentKeyBehindOnTrack()
        {
            Object opponentKeyClosestBehind = null;
            Object opponentKeyFurthestInFront = null;
            float closestDistanceBehind = SessionData.TrackDefinition.trackLength;
            float furthestDistanceInFront = 0;
            foreach (KeyValuePair<Object, OpponentData> opponent in OpponentData)
            {
                if (opponent.Value.Speed > 0.5 && !opponent.Value.isEnteringPits())
                {
                    if (PositionAndMotionData.DistanceRoundTrack > opponent.Value.DistanceRoundTrack &&
                        PositionAndMotionData.DistanceRoundTrack - opponent.Value.DistanceRoundTrack < closestDistanceBehind)
                    {
                        closestDistanceBehind = PositionAndMotionData.DistanceRoundTrack - opponent.Value.DistanceRoundTrack;
                        opponentKeyClosestBehind = opponent.Key;
                    }
                    else if (PositionAndMotionData.DistanceRoundTrack < opponent.Value.DistanceRoundTrack &&
                        opponent.Value.DistanceRoundTrack - PositionAndMotionData.DistanceRoundTrack > furthestDistanceInFront)
                    {
                        furthestDistanceInFront = opponent.Value.DistanceRoundTrack - PositionAndMotionData.DistanceRoundTrack;
                        opponentKeyFurthestInFront = opponent.Key;
                    }
                }
            }
            if (opponentKeyClosestBehind != null)
            {
                return opponentKeyClosestBehind;
            }
            else
            {
                return opponentKeyFurthestInFront;
            }
        }

        public Object getOpponentKeyInFront(Boolean useUnfilteredPosition)
        {
            if (SessionData.Position > 1)
            {
                return getOpponentKeyAtPosition(SessionData.Position - 1, useUnfilteredPosition);
            }
            else
            {
                return null;
            }
        }

        public Object getOpponentKeyBehind(Boolean useUnfilteredPosition)
        {
            if (SessionData.Position < SessionData.NumCars)
            {
                return getOpponentKeyAtPosition(SessionData.Position + 1, useUnfilteredPosition);
            }
            else
            {
                return null;
            }
        }

        public Object getOpponentKeyAtPosition(int position, Boolean useUnfilteredPosition)
        {
            if (OpponentData.Count != 0)
            {
                foreach (KeyValuePair<Object, OpponentData> entry in OpponentData)
                {
                    if (useUnfilteredPosition)
                    {
                        if (entry.Value.UnFilteredPosition == position)
                        {
                            return entry.Key;
                        }
                    }
                    else
                    {
                        if (entry.Value.Position == position)
                        {
                            return entry.Key;
                        }
                    }
                }
            }
            return null;
        }

        public void display()
        {
            Console.WriteLine("Laps completed = " + SessionData.CompletedLaps);
            Console.WriteLine("Time elapsed = " + SessionData.SessionRunningTime);
            Console.WriteLine("Position = " + SessionData.Position);
            Console.WriteLine("Session phase = " + SessionData.SessionPhase);
        }

        public void displayOpponentData()
        {
            Console.WriteLine("got " + OpponentData.Count + " opponents");
            foreach (KeyValuePair<Object, OpponentData> opponent in OpponentData)
            {
                Console.WriteLine("last laptime " + opponent.Value.getLastLapTime() + " completed laps " + opponent.Value.CompletedLaps +
                    " ID " + opponent.Key + " name " + opponent.Value.DriverRawName + " active " + opponent.Value.IsActive +
                    " approx speed " + opponent.Value.Speed + " position " + opponent.Value.Position);
            }
        }

        public float[] getTimeAndSectorsForBestOpponentLapInWindow(int lapsToCheck, CarData.CarClassEnum carClassToCheck)
        {
            CarData.CarClassEnum defaultCarClass = CarData.getDefaultCarClass().carClassEnum;
            float[] bestLapWithSectors =  new float[] { -1, -1, -1, -1 };
            foreach (KeyValuePair<Object, OpponentData> entry in OpponentData)
            {
                // if we don't know the opponent's car class, include him
                if (carClassToCheck == defaultCarClass || entry.Value.CarClass.carClassEnum == defaultCarClass || entry.Value.CarClass.carClassEnum == carClassToCheck)
                {
                    float[] thisOpponentsBest = entry.Value.getTimeAndSectorsForBestLapInWindow(lapsToCheck);
                    if (bestLapWithSectors[0] == -1 || (thisOpponentsBest[0] > 0 && thisOpponentsBest[0] < bestLapWithSectors[0]))
                    {
                        bestLapWithSectors = thisOpponentsBest;
                    }
                }
            }

            // special case for practice and qual - if we're looking for all the laps in the session, we might want to use the data sent by the game
            // because the play may have joined mid-session. In these cases there might be an historical lap (before the player joined) that's actually faster.
            if (lapsToCheck == -1 && SessionData.SessionFastestLapTimeFromGamePlayerClass > 0 &&
                (SessionData.PlayerLapTimeSessionBest == -1 || SessionData.PlayerLapTimeSessionBest > SessionData.SessionFastestLapTimeFromGamePlayerClass))
            {
                // the player isn't the fastest in his class. This means that the game-sent best lap data will be an opponent lap
                if (bestLapWithSectors[0] == -1 || bestLapWithSectors[0] > SessionData.SessionFastestLapTimeFromGamePlayerClass)
                {
                    // there's an historical lap which is quicker than all the data we currently hold. Due to limitations in the shared memory blocks,
                    // we never have sector times for this historical lap, so we have to remove them and disable sector deltas until a better lap is recorded
                    bestLapWithSectors[0] = SessionData.SessionFastestLapTimeFromGamePlayerClass;
                    bestLapWithSectors[1] = -1;
                    bestLapWithSectors[2] = -1;
                    bestLapWithSectors[3] = -1;
                }
            }
            return bestLapWithSectors;
        }
    }
}


text:
<?php

namespace IpTraceable\Fixture;

use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class SupperClassExtension extends MappedSupperClass
{
    /**
     * @ORM\Column(length=128)
     * @Gedmo\Translatable
     */
    private $title;

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }
}


text:
yum -q -y update

curl -fsSL https://get.docker.com/ | sh

#yum -q -y install docker

systemctl start docker

/usr/bin/docker version

if ! [ -x /usr/bin/weave ] ; then
  echo "Installing current version of Weave Net"
  curl --silent --location http://git.io/weave --output /usr/bin/weave
  chmod +x /usr/bin/weave
  /usr/bin/weave setup
fi

/usr/bin/weave version

docker pull gcr.io/kubeadm/installer
docker pull gcr.io/kubeadm/hyperkube

case "$(hostname)" in
  kube-master-0)
    ;;
  ## kube-[5..N] are the cluster nodes
  kube-node-*)
    ;;
esac


text:
@interface BNFIndex : BNFIndexPath

@property (nonatomic, retain) NSMutableArray *nodes;

- (void)addNode:(BNFIndexNode *)node;

- (BNFIndexPath *)path:(NSString *)path;

@end