text:
#region Usings

using System;
using System.Linq;

using org.GraphDefined.Vanaheimr.Styx;

#endregion

namespace org.GraphDefined.Vanaheimr.Balder
{

    /// <summary>
    /// A pipe emitting the vertices of the received generic property edges.
    /// </summary>
    /// <typeparam name="TIdVertex">The type of the vertex identifiers.</typeparam>
    /// <typeparam name="TRevIdVertex">The type of the vertex revision identifiers.</typeparam>
    /// <typeparam name="TVertexLabel">The type of the vertex type.</typeparam>
    /// <typeparam name="TKeyVertex">The type of the vertex property keys.</typeparam>
    /// <typeparam name="TValueVertex">The type of the vertex property values.</typeparam>
    ///
    /// <typeparam name="TIdEdge">The type of the edge identifiers.</typeparam>
    /// <typeparam name="TRevIdEdge">The type of the edge revision identifiers.</typeparam>
    /// <typeparam name="TEdgeLabel">The type of the edge label.</typeparam>
    /// <typeparam name="TKeyEdge">The type of the edge property keys.</typeparam>
    /// <typeparam name="TValueEdge">The type of the edge property values.</typeparam>
    ///
    /// <typeparam name="TIdMultiEdge">The type of the multiedge identifiers.</typeparam>
    /// <typeparam name="TRevIdMultiEdge">The type of the multiedge revision identifiers.</typeparam>
    /// <typeparam name="TMultiEdgeLabel">The type of the multiedge label.</typeparam>
    /// <typeparam name="TKeyMultiEdge">The type of the multiedge property keys.</typeparam>
    /// <typeparam name="TValueMultiEdge">The type of the multiedge property values.</typeparam>
    ///
    /// <typeparam name="TIdHyperEdge">The type of the hyperedge identifiers.</typeparam>
    /// <typeparam name="TRevIdHyperEdge">The type of the hyperedge revision identifiers.</typeparam>
    /// <typeparam name="THyperEdgeLabel">The type of the hyperedge label.</typeparam>
    /// <typeparam name="TKeyHyperEdge">The type of the hyperedge property keys.</typeparam>
    /// <typeparam name="TValueHyperEdge">The type of the hyperedge property values.</typeparam>
    public class VertexPipe<TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                            TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                            TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                            TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge>

                            : AbstractPipe<IReadOnlyGenericPropertyEdge<TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                                                                        TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                                                                        TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                                                                        TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge>,

                                           IReadOnlyGenericPropertyVertex<TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                                                                          TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                                                                          TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                                                                          TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge>>

        where TIdVertex        : IEquatable<TIdVertex>,       IComparable<TIdVertex>,       IComparable, TValueVertex
        where TIdEdge          : IEquatable<TIdEdge>,         IComparable<TIdEdge>,         IComparable, TValueEdge
        where TIdMultiEdge     : IEquatable<TIdMultiEdge>,    IComparable<TIdMultiEdge>,    IComparable, TValueMultiEdge
        where TIdHyperEdge     : IEquatable<TIdHyperEdge>,    IComparable<TIdHyperEdge>,    IComparable, TValueHyperEdge

        where TRevIdVertex     : IEquatable<TRevIdVertex>,    IComparable<TRevIdVertex>,    IComparable, TValueVertex
        where TRevIdEdge       : IEquatable<TRevIdEdge>,      IComparable<TRevIdEdge>,      IComparable, TValueEdge
        where TRevIdMultiEdge  : IEquatable<TRevIdMultiEdge>, IComparable<TRevIdMultiEdge>, IComparable, TValueMultiEdge
        where TRevIdHyperEdge  : IEquatable<TRevIdHyperEdge>, IComparable<TRevIdHyperEdge>, IComparable, TValueHyperEdge

        where TVertexLabel     : IEquatable<TVertexLabel>,    IComparable<TVertexLabel>,    IComparable, TValueVertex
        where TEdgeLabel       : IEquatable<TEdgeLabel>,      IComparable<TEdgeLabel>,      IComparable, TValueEdge
        where TMultiEdgeLabel  : IEquatable<TMultiEdgeLabel>, IComparable<TMultiEdgeLabel>, IComparable, TValueMultiEdge
        where THyperEdgeLabel  : IEquatable<THyperEdgeLabel>, IComparable<THyperEdgeLabel>, IComparable, TValueHyperEdge

        where TKeyVertex       : IEquatable<TKeyVertex>,      IComparable<TKeyVertex>,      IComparable
        where TKeyEdge         : IEquatable<TKeyEdge>,        IComparable<TKeyEdge>,        IComparable
        where TKeyMultiEdge    : IEquatable<TKeyMultiEdge>,   IComparable<TKeyMultiEdge>,   IComparable
        where TKeyHyperEdge    : IEquatable<TKeyHyperEdge>,   IComparable<TKeyHyperEdge>,   IComparable

    {

        #region Data

        private readonly Func<IReadOnlyGenericPropertyEdge  <TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                                                             TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                                                             TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                                                             TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge>,

                              IReadOnlyGenericPropertyVertex<TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                                                             TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                                                             TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                                                             TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge>> Edge2VertexDelegate;

        private IReadOnlyGenericPropertyVertex<TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                                               TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                                               TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                                               TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge> _NextVertex;

        /// <summary>
        /// An array of vertex labels to traverse (OR-logic).
        /// </summary>
        protected readonly TVertexLabel[] VertexLabels;

        /// <summary>
        /// A delegate for vertex filtering.
        /// </summary>
        protected readonly VertexFilter<TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                                        TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                                        TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                                        TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge> VertexFilter;

        #endregion

        #region Constructor(s)

        #region VertexPipe(Edges, TraversalDirection, params VertexLabels)

        /// <summary>
        /// Creates a pipe emitting the vertices of the received generic property edges
        /// having the given vertex labels.
        /// </summary>
        /// <param name="Edges">A pipe emitting generic property edges.</param>
        /// <param name="TraversalDirection">The next vertices to visit.</param>
        /// <param name="VertexLabels">An optional array of vertex labels to traverse (OR-logic).</param>
        public VertexPipe(IEndPipe<IReadOnlyGenericPropertyEdge<TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                                                                TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                                                                TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                                                                TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge>> Edges,

                          TraversalDirection TraversalDirection,

                          params TVertexLabel[] VertexLabels)

            : base(Edges)

        {

            switch (TraversalDirection)
            {
                case Balder.TraversalDirection.In:   Edge2VertexDelegate = Edge => (Edge != null) ? Edge.InVertex  : null; break;
                case Balder.TraversalDirection.Out:  Edge2VertexDelegate = Edge => (Edge != null) ? Edge.OutVertex : null; break;
                case Balder.TraversalDirection.Both: Edge2VertexDelegate = Edge2BothVertices;                              break;
            }

            this.VertexLabels = VertexLabels.Any() ? VertexLabels : null;

        }

        #endregion

        #region VertexPipe(Edges, TraversalDirection, IncludeFilter = null)

        /// <summary>
        /// Creates a pipe emitting the vertices of the incoming generic property edges
        /// filtered by the given vertex filter delegate.
        /// </summary>
        /// <param name="Edges">A pipe emitting generic property edges.</param>
        /// <param name="TraversalDirection">The next vertices to visit.</param>
        /// <param name="IncludeFilter">An optional delegate for vertex filtering.</param>
        public VertexPipe(IEndPipe<IReadOnlyGenericPropertyEdge<TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                                                                TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                                                                TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                                                                TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge>> Edges,

                          TraversalDirection TraversalDirection,

                          VertexFilter<TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                                       TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                                       TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                                       TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge> IncludeFilter = null)

            : base(Edges)

        {

            switch (TraversalDirection)
            {
                case Balder.TraversalDirection.In:   Edge2VertexDelegate = Edge => (Edge != null) ? Edge.InVertex  : null; break;
                case Balder.TraversalDirection.Out:  Edge2VertexDelegate = Edge => (Edge != null) ? Edge.OutVertex : null; break;
                case Balder.TraversalDirection.Both: Edge2VertexDelegate = Edge2BothVertices;                              break;
            }

            this.VertexFilter = (IncludeFilter != null) ? IncludeFilter : v => true;

        }

        #endregion

        #endregion

        #region (private) Edge2BothVertices(Edge)

        private IReadOnlyGenericPropertyVertex<TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                                               TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                                               TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                                               TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge>

            Edge2BothVertices(IReadOnlyGenericPropertyEdge<TIdVertex,    TRevIdVertex,    TVertexLabel,    TKeyVertex,    TValueVertex,
                                                           TIdEdge,      TRevIdEdge,      TEdgeLabel,      TKeyEdge,      TValueEdge,
                                                           TIdMultiEdge, TRevIdMultiEdge, TMultiEdgeLabel, TKeyMultiEdge, TValueMultiEdge,
                                                           TIdHyperEdge, TRevIdHyperEdge, THyperEdgeLabel, TKeyHyperEdge, TValueHyperEdge> Edge)

        {

            if (_NextVertex == null)
            {
                _NextVertex = SourcePipe.Current.OutVertex;
                return SourcePipe.Current.InVertex;
            }

            _NextVertex = null;

            return _NextVertex;

        }

        #endregion

        #region MoveNext()

        /// <summary>
        /// Advances the enumerator to the next element of the collection.
        /// </summary>
        /// <returns>
        /// True if the enumerator was successfully advanced to the next
        /// element; false if the enumerator has passed the end of the
        /// collection.
        /// </returns>
        public override Boolean MoveNext()
        {

            if (SourcePipe == null)
                return false;

            if (VertexLabels != null)
            {
                while (SourcePipe.MoveNext())
                {
                    if (VertexLabels.Any(VertexLabel => Edge2VertexDelegate(SourcePipe.Current).Label.Equals(VertexLabel)))
                    {
                        _CurrentElement = Edge2VertexDelegate(SourcePipe.Current);
                        return true;
                    }
                }
            }

            else if (VertexFilter != null)
            {
                while (SourcePipe.MoveNext())
                {
                    if (VertexFilter(_CurrentElement))
                    {
                        _CurrentElement = Edge2VertexDelegate(SourcePipe.Current);
                        return true;
                    }
                }
            }

            else
            {
                while (SourcePipe.MoveNext())
                {
                    _CurrentElement = Edge2VertexDelegate(SourcePipe.Current);
                    return true;
                }
            }

            return false;

        }

        #endregion

    }

}


text:
phantom.__defineErrorSignalHandler__ = function (obj, page, handlers) {
  var handlerName = 'onError';

  Object.defineProperty(obj, handlerName, {
    set: function (f) {
      // Disconnect previous handler (if any)
      var handlerObj = handlers[handlerName];
      if (!!handlerObj && typeof handlerObj.callback === 'function' && typeof handlerObj.connector === 'function') {
        try {
          page.javaScriptErrorSent.disconnect(handlerObj.connector);
        } catch (e) {}
      }

      // Delete the previous handler
      delete handlers[handlerName];

      if (typeof f === 'function') {
        var connector = function (message, lineNumber, source, stack) {
          var revisedStack = JSON.parse(stack).map(function (item) {
            return {
              file: item.url,
              line: item.lineNumber,
              function: item.functionName
            };
          });
          if (revisedStack.length === 0)
            revisedStack = [{
              file: source,
              line: lineNumber
            }];

          f(message, revisedStack);
        };
        // Store the new handler for reference
        handlers[handlerName] = {
          callback: f,
          connector: connector
        };

        page.javaScriptErrorSent.connect(connector);
      }
    },
    get: function () {
      var handlerObj = handlers[handlerName];
      return (!!handlerObj && typeof handlerObj.callback === 'function' && typeof handlerObj.connector === 'function') ?
        handlers[handlerName].callback :
        undefined;
    },
    configurable: true
  });
};

(function () {
  var handlers = {};
  phantom.__defineErrorSignalHandler__(phantom, phantom.page, handlers);
})();

// TODO: Make this output to STDERR
phantom.defaultErrorHandler = function (message, stack) {
  console.log(message + '\n');

  stack.forEach(function (item) {
    var message = item.file + ':' + item.line;
    if (item['function'])
      message += ' in ' + item['function'];
    console.log('  ' + message);
  });
};

phantom.onError = phantom.defaultErrorHandler;

phantom.callback = function (callback) {
  var ret = phantom.createCallback();
  ret.called.connect(function (args) {
    var retVal = callback.apply(this, args);
    ret.returnValue = retVal;
  });
  return ret;
};

(function () {
  // CommonJS module implementation follows

  window.global = window;
  // fs is loaded at the end, when everything is ready
  var fs;
  var cache = {};
  var paths = [];
  // use getters to initialize lazily
  // (for future, now both fs and system are loaded anyway)
  var nativeExports = {
    get fs() {
      return phantom.createFilesystem();
    },
    get child_process() {
      return phantom._createChildProcess();
    },
    get system() {
      return phantom.createSystem();
    }
  };
  var extensions = {
    '.js': function (module, filename) {
      var code = fs.read(filename);
      module._compile(code);
    },

    '.json': function (module, filename) {
      module.exports = JSON.parse(fs.read(filename));
    }
  };

  function loadFs() {
    var file, code, module, filename = ':/modules/fs.js';

    module = new Module(filename);
    cache[filename] = module;
    module.exports = nativeExports.fs;

    file = module.exports._open(filename, {
      mode: 'r'
    });
    code = file.read();
    file.close();
    module._compile(code);

    return module.exports;
  }

  function dirname(path) {
    var replaced = path.replace(/\/[^/]*\/?$/, '');
    if (replaced === path) {
      replaced = '';
    }
    return replaced;
  }

  function basename(path) {
    return path.replace(/.*\//, '');
  }

  function joinPath() {
    // It should be okay to hard-code a slash here.
    // The FileSystem module returns a platform-specific
    // separator, but the JavaScript engine only expects
    // the slash.
    var args = Array.prototype.slice.call(arguments);
    return args.join('/');
  }

  function tryFile(path) {
    if (fs.isFile(path)) return path;
    return null;
  }

  function tryExtensions(path) {
    var filename, exts = Object.keys(extensions);
    for (var i = 0; i < exts.length; ++i) {
      filename = tryFile(path + exts[i]);
      if (filename) return filename;
    }
    return null;
  }

  function tryPackage(path) {
    var filename, package, packageFile = joinPath(path, 'package.json');
    if (fs.isFile(packageFile)) {
      package = JSON.parse(fs.read(packageFile));
      if (!package || !package.main) return null;

      filename = fs.absolute(joinPath(path, package.main));

      return tryFile(filename) || tryExtensions(filename) ||
        tryExtensions(joinPath(filename, 'index'));
    }
    return null;
  }

  function Module(filename, stubs) {
    if (filename) this._setFilename(filename);
    this.exports = {};
    this.stubs = {};
    for (var name in stubs) {
      this.stubs[name] = stubs[name];
    }
  }

  Module.prototype._setFilename = function (filename) {
    this.id = this.filename = filename;
    this.dirname = dirname(filename);
  };

  Module.prototype._isNative = function () {
    return this.filename && this.filename[0] === ':';
  };

  Module.prototype._getPaths = function (request) {
    var _paths = [],
      dir;

    if (request[0] === '.') {
      _paths.push(fs.absolute(joinPath(phantom.webdriverMode ? ':/ghostdriver' : this.dirname, request)));
    } else if (fs.isAbsolute(request)) {
      _paths.push(fs.absolute(request));
    } else {
      // first look in PhantomJS modules
      _paths.push(joinPath(':/modules', request));
      // then look in node_modules directories
      if (!this._isNative()) {
        dir = this.dirname;
        while (dir) {
          _paths.push(joinPath(dir, 'node_modules', request));
          dir = dirname(dir);
        }
      }
    }

    for (var i = 0; i < paths.length; ++i) {
      if (fs.isAbsolute(paths[i])) {
        _paths.push(fs.absolute(joinPath(paths[i], request)));
      } else {
        _paths.push(fs.absolute(joinPath(this.dirname, paths[i], request)));
      }
    }

    return _paths;
  };

  Module.prototype._getFilename = function (request) {
    var path, filename = null,
      _paths = this._getPaths(request);

    for (var i = 0; i < _paths.length && !filename; ++i) {
      path = _paths[i];
      filename = tryFile(path) || tryExtensions(path) || tryPackage(path) ||
        tryExtensions(joinPath(path, 'index'));
    }

    return filename;
  };

  Module.prototype._getRequire = function () {
    var self = this;

    function require(request) {
      return self.require(request);
    }
    require.cache = cache;
    require.extensions = extensions;
    require.paths = paths;
    require.stub = function (request, exports) {
      self.stubs[request] = {
        exports: exports
      };
    };

    return require;
  };

  Module.prototype._load = function () {
    var ext = this.filename.match(/\.[^.]+$/)[0];
    if (!ext) ext = '.js';
    extensions[ext](this, this.filename);
  };

  Module.prototype._compile = function (code) {
    phantom.loadModule(code, this.filename);
  };

  Module.prototype.require = function (request) {
    var filename, module;

    // first see if there are any stubs for the request
    if (this.stubs.hasOwnProperty(request)) {
      if (this.stubs[request].exports instanceof Function) {
        this.stubs[request].exports = this.stubs[request].exports();
      }
      return this.stubs[request].exports;
    }

    // else look for a file
    filename = this._getFilename(request);
    if (!filename) {
      throw new Error(`Cannot find module "${request}"`);
    }

    if (cache.hasOwnProperty(filename)) {
      return cache[filename].exports;
    }

    module = new Module(filename, this.stubs);
    if (module._isNative()) {
      module.exports = nativeExports[request] || {};
    }
    cache[filename] = module;
    module._load();

    return module.exports;
  };

  (function () {
    var cwd, mainFilename, mainModule = new Module();
    window.require = mainModule._getRequire();
    fs = loadFs();
    cwd = fs.absolute(phantom.libraryPath);
    mainFilename = joinPath(cwd, basename(require('system').args[0]) || 'repl');
    mainModule._setFilename(mainFilename);
  }());
}());

// Legacy way to use WebPage
window.WebPage = require('webpage').create;

redpajama_set_name: RedPajamaGithub


text:
@interface ViewController ()
@property (nonatomic) NSInteger timerCount;
@property (nonatomic) NSInteger readyTimerCount;
@property (weak, nonatomic) IBOutlet UILabel *timerLabel;
@property (weak, nonatomic) IBOutlet UILabel *guess;
@property (nonatomic) NSInteger rightCount;
@property (weak, nonatomic) IBOutlet UIView *readyView;
@property (weak, nonatomic) IBOutlet UILabel *readyLabel;

@property (nonatomic) NSInteger whichAnswerAreWeAt;
@property (nonatomic) NSInteger totalGuesses;
@property (nonatomic) AFHTTPSessionManager *manager;
@property (weak, nonatomic) IBOutlet UIImageView *backgroundImage;
@property (nonatomic) SDWebImageManager *SDmanager;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.SDmanager = [SDWebImageManager sharedManager];
    self.whichAnswerAreWeAt = 0;
    self.rightCount = 0;
    self.totalGuesses = 1;
//    self.guess.text = self.answers[self.whichAnswerAreWeAt];
    self.readyLabel.text = @"3";

    [self setupReadyTimer];
    self.readyView.backgroundColor = [UIColor colorWithGradientStyle:UIGradientStyleTopToBottom withFrame: self.view.frame andColors:@[[UIColor flatWhiteColorDark], [UIColor flatWhiteColor]]];

    self.manager = [[AFHTTPSessionManager alloc] init];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [self showNextGuess];

}

# pragma mark - gesture methods
- (void) setUpGestureRecognizers {
    UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    leftSwipe.direction= UISwipeGestureRecognizerDirectionLeft;

    UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;

    [self.view addGestureRecognizer:leftSwipe];
    [self.view addGestureRecognizer:rightSwipe];

}

- (void) handleSwipe: (UISwipeGestureRecognizer *) gesture {
    if (self.whichAnswerAreWeAt==self.answers.count-1) {
        self.whichAnswerAreWeAt = 0;
    }
    else{
        self.whichAnswerAreWeAt++;
    }

    switch (gesture.direction) {
        case  UISwipeGestureRecognizerDirectionRight:
            [self animateViewWith:[UIColor flatWatermelonColorDark]];
            self.totalGuesses++;
            [self showNextGuess];
            break;
        case UISwipeGestureRecognizerDirectionLeft:
            [self animateViewWith:[UIColor flatMintColorDark]];
            self.rightCount++;
            self.totalGuesses++;
            [self showNextGuess];
            break;
        default:
            break;
    }
}

-(void) showNextGuess{
    NSString *currGuess = self.answers[self.whichAnswerAreWeAt];
    self.backgroundImage.image = nil;
    self.guess.text = currGuess;
    NSString * url = [[NSString stringWithFormat:@"http://api.duckduckgo.com/?q=%@&format=json", currGuess] stringByAddingPercentEscapesUsingEncoding:
                      NSASCIIStringEncoding];

    [self. manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];

        NSURL * imageUrl = [NSURL URLWithString:[json objectForKey:@"Image"]];
        [self.SDmanager downloadImageWithURL:imageUrl
                                   options:0
                                  progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                                      // progression tracking code
                                  }
                                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                                     if (image) {
                                         self.backgroundImage.image = image;
                                     }

                                 }];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];

}

-(void) animateViewWith:(UIColor* )color{
    [UIView animateWithDuration:0.5
                     animations:^{
                         self.view.backgroundColor = color;
                     } completion:^(BOOL finished) {
                         self.view.backgroundColor = [UIColor whiteColor];
                     }];
}

# pragma mark - timer methods
-(void) setupReadyTimer
{
    self.readyTimerCount = 2;
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(handleReadyTimer:) userInfo:nil repeats:YES];

    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}

- (void) handleReadyTimer: (NSTimer * ) timer {

    self.readyLabel.text = [NSString stringWithFormat: @"%ld", (long)self.readyTimerCount];
    self.readyTimerCount--;

    if (self.readyTimerCount < 0 ) {
        self.readyLabel.text = @"Go!";
        [UIView animateWithDuration:1.0
                         animations:^{
                             self.readyView.transform = CGAffineTransformMakeScale(1.5, 1.5);
                         } completion:^(BOOL finished) {
                             self.readyView.hidden = YES;
                         }];

        [self setupTimer];
        [timer invalidate];
        //hide ready screen
    }

}

-(void) setupTimer
{
    self.timerCount = 30;
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(handleGameTimer:) userInfo:nil repeats:YES];

    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    //[timer fire];
    [self setUpGestureRecognizers];
}

- (void) handleGameTimer: (NSTimer * ) timer {

    self.timerLabel.text = [NSString stringWithFormat: @"%ld", (long)self.timerCount];
    self.timerCount--;

    if (self.timerCount < 0 ) {
        [timer invalidate];

        //show score
        NSString * endGameText = [NSString stringWithFormat:@"you got %ld out of %ld right", (long)self.rightCount, self.totalGuesses];
        SIAlertView *alertView = [[SIAlertView alloc] initWithTitle:@"Game Over" andMessage:endGameText];

        [alertView addButtonWithTitle:@"Play Again"
                                 type:SIAlertViewButtonTypeDefault
                              handler:^(SIAlertView *alert) {

                              }];

        alertView.didDismissHandler = ^(SIAlertView *alertView) {
            [self dismissViewControllerAnimated:YES completion:nil];
        };

        alertView.transitionStyle = SIAlertViewTransitionStyleBounce;

        [alertView show];

        //end game

        //
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
'use strict';

/**
 * @ngdoc function
 * @name tomTomApp.controller:NavbarTopLinksCtrl
 * @description
 * # NavbarTopLinksCtrl
 * Controller of the tomTomApp
 */
angular.module('tomTomApp')
    .controller('NavbarTopLinksCtrl', function($rootScope, $scope, $state, simpleLogin, FBURL, Firebase, $firebase, People, Ticket) {

        $scope.tickets = Ticket;
        $scope.people = People;

        $scope.messages = [];

        $scope.logout = function() {
            simpleLogin.logout();
            $state.go('login');
        };
        $scope.user = simpleLogin.getUser();

        simpleLogin.watch(update, $rootScope);

        function update(check) {
            $scope.user = check;
            // console.log(check);
            if (check.uid) {
                var ref = new Firebase(FBURL).child('users').child(check.uid);
                var u = $firebase(ref).$asObject();
                u.$loaded(function() {
                    var ref2 = new Firebase(FBURL).child('people').child(u.peopleId);
                    $scope.userPerson = $firebase(ref2).$asObject();
                    // console.log($scope.userPerson);
                });
            }
        }

    });


text:
package autosignr

import (
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"
)

// The OID for Puppet's pp_preshared_key in the Certificate Extensions
// https://docs.puppetlabs.com/puppet/latest/reference/ssl_attributes_extensions.html
const puppetPSKoid string = "1.3.6.1.4.1.34380.1.1.4"

// ErrNoPemData is returned when the data expected to be a PEM encoded cert is not actually a cert
var ErrNoPemData = errors.New("no PEM data found in block")

// ErrNoPSK is returned when a certificate does not contain a preshared key
var ErrNoPSK = errors.New("certificate did not contain a PSK")

// regexpPSK limits what the PSK can contain to alphanumeric chars plus '_', '-', and '.'
var regexpPSK = regexp.MustCompile("([a-zA-Z0-9_\\-\\.]+)")

// CertnameFromFilename returns the name of a cert given the path to the file
func CertnameFromFilename(file string) string {
	return strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
}

// CheckCert checks if the cert is valid
func CheckCert(conf *Config, file string) (bool, error) {
	name := CertnameFromFilename(file)
	log.Debugf("CheckCert %s", name)
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return false, err
	}

	result, err := ValidateCert(conf, data, name)

	if err != nil {
		return false, err
	}

	if !result {
		log.Warningf("Unable to validate instance %s", name)
	}

	return result, nil
}

// ValidateCert validates the cert
func ValidateCert(conf *Config, data []byte, certname string) (bool, error) {
	log.Debugf("ValidateCert %s", certname)
	if conf.CheckPSK {
		psk, err := PuppetPSKFromCSR(data)
		if err != nil {
			log.WithFields(log.Fields{
				"certname": certname,
				"err":      err,
			}).Warning("psk-extract-error")
			return false, err
		}
		if _, ok := conf.PresharedKeys[psk]; !ok {
			log.WithFields(log.Fields{
				"certname": certname,
				"psk":      psk,
			}).Warning("invalid-psk")
			return false, errors.New("Invalid PSK")
		}
	}

	result := false
	for _, acct := range conf.Accounts {
		result = acct.Check(certname)
		if result {
			break
		}
	}

	return result, nil
}

// SignCert will run the puppet command to sign the cert
func SignCert(conf *Config, certname string) {
	cmd := fmt.Sprintf(conf.CmdSign, certname)
	pieces := strings.Split(cmd, " ")

	cmdOut, err := exec.Command(pieces[0], pieces[1:]...).CombinedOutput()
	if err != nil {
		log.WithFields(log.Fields{
			"certname": certname,
			"err":      err,
			"output":   string(cmdOut),
		}).Error("signing-failure")
		return
	}
	log.WithFields(log.Fields{
		"certname": certname,
	}).Info("signing-success")
}

// ExistingCerts checks existing certs in directory
func ExistingCerts(conf *Config) error {
	matches, err := filepath.Glob(fmt.Sprintf("%s/*.pem", conf.Dir))
	if err != nil {
		return errors.Wrap(err, "globbing")
	}

	for _, cert := range matches {
		log.WithFields(log.Fields{
			"file": cert,
		}).Info("existing-csr")
		result, _ := CheckCert(conf, cert)

		if result {
			SignCert(conf, CertnameFromFilename(cert))
		}
	}

	return nil
}

// PuppetPSKFromCSRFile return the CSR file data
func PuppetPSKFromCSRFile(file string) (string, error) {
	var f string

	data, err := ioutil.ReadFile(file)
	if err != nil {
		return f, err
	}

	return PuppetPSKFromCSR(data)
}

// PuppetPSKFromCSR decodes and parses the cert data
func PuppetPSKFromCSR(data []byte) (string, error) {
	block, _ := pem.Decode(data)
	if block == nil {
		return "", ErrNoPemData
	}

	parsedcsr, err := x509.ParseCertificateRequest(block.Bytes)
	if err != nil {
		return "", err
	}

	for _, e := range parsedcsr.Extensions {
		if e.Id.String() == puppetPSKoid {
			match := regexpPSK.FindStringSubmatch(string(e.Value))
			if len(match) > 0 {
				return match[1], nil
			}
		}
	}

	return "", ErrNoPSK
}


text:
package org.apache.geronimo.system.repository;

import java.io.File;
import java.io.IOException;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URISyntaxException;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoBuilder;
import org.apache.geronimo.gbean.GBeanLifecycle;
import org.apache.geronimo.kernel.repository.Repository;
import org.apache.geronimo.kernel.repository.ListableRepository;
import org.apache.geronimo.kernel.repository.WriteableRepository;
import org.apache.geronimo.kernel.repository.FileWriteMonitor;
import org.apache.geronimo.system.serverinfo.ServerInfo;

/**
 * A listable, writeable repository that stores its entries in a directory on
 * the local filesystem.
 *
 * @version $Rev$ $Date$
 */
public class FileSystemRepository implements Repository, ListableRepository, WriteableRepository, GBeanLifecycle {
    private static final Log log = LogFactory.getLog(FileSystemRepository.class);
    private final static int TRANSFER_NOTIFICATION_SIZE = 10240;  // announce every this many bytes
    private final static int TRANSFER_BUF_SIZE = 10240;  // try this many bytes at a time
    private final URI root;
    private final ServerInfo serverInfo;
    private URI rootURI;
    private File rootFile;

    public FileSystemRepository(URI root, ServerInfo serverInfo) {
        if (!root.toString().endsWith("/")) {
            try {
                root = new URI(root.toString() + "/");
            } catch (URISyntaxException e) {
                throw new RuntimeException("Invalid repository root (does not end with / ) and can't add myself", e);
            }
        }
        this.root = root;
        this.serverInfo = serverInfo;
    }

    public boolean hasURI(URI uri) {
        uri = resolve(uri);
        if(uri == null) {
            return false;
        }
        if ("file".equals(uri.getScheme())) {
            File f = new File(uri);
            return f.exists() && f.canRead();
        } else {
            return false;
        }
    }

    public URL getURL(URI uri) throws MalformedURLException {
        URL url = resolve(uri).toURL();
        if (!url.getProtocol().equals("file")) {
            return null;
        }
        return url;
    }

    private URI resolve(final URI uri) {
        String[] bits = uri.toString().split("/");
        if(bits.length < 3) {
            log.warn("Unable to resolve URI '"+uri+"' as a repository entry");
            return null;
        }
        StringBuffer buf = new StringBuffer(bits[0]).append('/');
        String type = bits.length >= 4 ? bits[3] : "jar";
        buf.append(type).append('s').append('/').append(bits[1]).append('-').append(bits[2]).append('.').append(type);
        return rootURI.resolve(buf.toString());
    }

    //thanks to Brett Porter for this regex lifted from a maven1-2 porting tool
    private static final Pattern pattern = Pattern.compile("(.+)/(.+)s/(.+)-([0-9].+)\\.([^0-9]+)");

    public URI[] listURIs() throws URISyntaxException {
        String[] names = getFiles(rootFile, "");
        List results = new ArrayList(names.length);
        Matcher matcher = pattern.matcher("");
        for (int i = 0; i < names.length; i++) {
            matcher.reset(names[i]);
            if (matcher.matches()) {
                String groupId = matcher.group(1);
                String artifactId = matcher.group(3);
                String version = matcher.group(4);
                String type = matcher.group(5);
                StringBuffer buf = new StringBuffer(groupId).append("/").append(artifactId).append("/").append(version).append("/").append(type);
                results.add(new URI(buf.toString()));
            } else {
            	log.warn("could not resolve URI for malformed repository entry: " + names[i] +
            	" - the filename should look like: <groupId>/<type>s/<artifactId>-<version>.<type>   "+
                "Perhaps you put in a file without a version number in the name?");
            }

        }
       	return (URI[])results.toArray(new URI[results.size()]);
    }

    public String[] getFiles(File base, String prefix) {
        if (!base.canRead() || !base.isDirectory()) {
            throw new IllegalArgumentException(base.getAbsolutePath());
        }
        List list = new ArrayList();
        File[] hits = base.listFiles();
        for (int i = 0; i < hits.length; i++) {
            File hit = hits[i];
            if (hit.canRead()) {
                if (hit.isDirectory()) {
                    list.addAll(Arrays.asList(getFiles(hit, prefix.equals("") ? hit.getName() : prefix + "/" + hit.getName())));
                } else {
                    list.add(prefix.equals("") ? hit.getName() : prefix + "/" + hit.getName());
                }
            }
        }
        return (String[]) list.toArray(new String[list.size()]);
    }

    public void copyToRepository(File source, URI destination, FileWriteMonitor monitor) throws IOException {
        if (!source.exists() || !source.canRead() || source.isDirectory()) {
            throw new IllegalArgumentException("Cannot read source file at " + source.getAbsolutePath());
        }
        copyToRepository(new FileInputStream(source), destination, monitor);
    }

    public void copyToRepository(InputStream source, URI destination, FileWriteMonitor monitor) throws IOException {
        if (!rootFile.canWrite()) {
            throw new IllegalStateException("This repository is not writable: " + rootFile.getAbsolutePath() + ")");
        }

        File dest = new File(resolve(destination));
        if (dest.exists()) {
            throw new IllegalArgumentException("Destination " + dest.getAbsolutePath() + " already exists!");
        }
        final File parent = dest.getParentFile();
        if (!parent.exists() && !parent.mkdirs()) {
            throw new RuntimeException("Unable to create directories from " + rootFile.getAbsolutePath() + " to " + parent.getAbsolutePath());
        }
        if (monitor != null) {
            monitor.writeStarted(destination.toString());
        }
        int total = 0;
        try {
            int threshold = TRANSFER_NOTIFICATION_SIZE;
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
            BufferedInputStream in = new BufferedInputStream(source);
            byte[] buf = new byte[TRANSFER_BUF_SIZE];
            int count;
            while ((count = in.read(buf)) > -1) {
                out.write(buf, 0, count);
                if (monitor != null) {
                    total += count;
                    if (total > threshold) {
                        threshold += TRANSFER_NOTIFICATION_SIZE;
                        monitor.writeProgress(total);
                    }
                }
            }
            out.flush();
            out.close();
            in.close();
        } finally {
            if (monitor != null) {
                monitor.writeComplete(total);
            }
        }
    }

    public void doStart() throws Exception {
        if (rootURI == null) {
            if (serverInfo != null) {
                rootURI = serverInfo.resolve(root);
            } else {
                rootURI = root;
            }
            if (!rootURI.getScheme().equals("file")) {
                throw new IllegalStateException("FileSystemRepository must have a root that's a local directory (not " + rootURI + ")");
            }
            rootFile = new File(rootURI);
            if (!rootFile.exists() || !rootFile.isDirectory() || !rootFile.canRead()) {
                throw new IllegalStateException("FileSystemRepository must have a root that's a valid readable directory (not " + rootFile.getAbsolutePath() + ")");
            }
        }
        log.debug("Repository root is " + rootFile.getAbsolutePath());
    }

    public void doStop() throws Exception {
    }

    public void doFail() {
    }

    public static final GBeanInfo GBEAN_INFO;

    static {
        GBeanInfoBuilder infoFactory = GBeanInfoBuilder.createStatic(FileSystemRepository.class);

        infoFactory.addAttribute("root", URI.class, true);

        infoFactory.addReference("ServerInfo", ServerInfo.class, "GBean");

        infoFactory.addInterface(Repository.class);
        infoFactory.addInterface(ListableRepository.class);
        infoFactory.addInterface(WriteableRepository.class);

        infoFactory.setConstructor(new String[]{"root", "ServerInfo"});

        GBEAN_INFO = infoFactory.getBeanInfo();
    }

    public static GBeanInfo getGBeanInfo() {
        return GBEAN_INFO;
    }
}


text:
package org.kohsuke.github;

import com.fasterxml.jackson.annotation.JacksonInject;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

import java.util.Objects;

/**
 * Defines a base class that all classes in this library that interact with GitHub inherit from.
 *
 * Ensures that all data references to GitHub connection are transient.
 *
 * Classes that do not need to interact with GitHub after they are instantiated do not need to inherit from this class.
 *
 * @author Liam Newman
 */
abstract class GitHubInteractiveObject {
    @JacksonInject
    @CheckForNull
    private transient final GitHub root;

    GitHubInteractiveObject() {
        root = null;
    }

    GitHubInteractiveObject(GitHub root) {
        this.root = root;
    }

    /**
     * Get the root {@link GitHub} instance for this object.
     *
     * @return the root {@link GitHub} instance
     *
     * @deprecated For access to the {@link GitHub} instance, use a local copy instead of pulling it out of objects.
     */
    @Deprecated
    @SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Expected behavior")
    public GitHub getRoot() {
        return root();
    }

    /**
     * Get the root {@link GitHub} instance for this object.
     *
     * @return the root {@link GitHub} instance
     */
    @NonNull
    GitHub root() {
        return Objects.requireNonNull(root,
                "The root GitHub reference for this instance is null. Probably caused by deserializing this class without using a GitHub instance. If you must do this, use the MappingObjectReader from GitHub.getMappingObjectReader().");
    }

    /**
     * Object is offline.
     *
     * @return true if GitHub instance is null or offline.
     */
    boolean isOffline() {
        return root == null || root.isOffline();
    }
}


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

namespace LodViewProvider {

	public enum SelectionType {
		Single = 0,
		Multiple = 1,
		All = 2
	}

	public class SingleSelection : IRequestable {

		public string Variable { get; private set; }
		public string Condition { get; private set; }
		public string Operator { get; private set; }
		public SelectionType SelectionType { get; private set; }
		public string ConditionType { get; private set; }

		public SingleSelection( string variable, string condition = "", string oper = "", string conditionType = "System.String" ) {
			Variable = variable.Trim( '\"' );
			Condition = condition.Trim( '\"' );
			Operator = oper;
			SelectionType = LodViewProvider.SelectionType.Single;
			ConditionType = conditionType;
		}

		public override string ToString() {
			var strb = new StringBuilder();
			strb.Append( "{" );
			strb.Append( String.Format( "t:{0},", "cond" ) );
			strb.Append( String.Format( "v:{0},", Variable ) );
			strb.Append( String.Format( "op:{0},", Operator ) );
			strb.Append( String.Format( "c:{0}", Condition ) );
			strb.Append( "}" );
			return strb.ToString();
		}
	}

	public class MultipleSelection : IRequestable	{
		public SelectionType SelectionType { get; private set; }
		public List<SingleSelection> Variables { get; private set; }

		public MultipleSelection()
			: this( new List<SingleSelection>() ) {}

		public MultipleSelection( List<SingleSelection> variables ) {
			Variables = variables;
			SelectionType = LodViewProvider.SelectionType.Multiple;
		}

		public override string ToString() {
			StringBuilder strb = new StringBuilder();
			Variables.ForEach( s => strb.Append( s.ToString() ) );
			return strb.ToString();
		}
	}

	public class All : IRequestable {
		public SelectionType SelectionType { get; private set; }
		public All() {
			SelectionType = LodViewProvider.SelectionType.All;
		}
	}
}


text:
package org.spongepowered.common.data;

import com.google.common.base.Optional;
import org.spongepowered.api.data.DataTransactionResult;
import org.spongepowered.api.data.key.Key;
import org.spongepowered.api.data.manipulator.DataManipulator;
import org.spongepowered.api.data.manipulator.mutable.CommandData;
import org.spongepowered.api.data.manipulator.mutable.MobSpawnerData;
import org.spongepowered.api.data.manipulator.mutable.entity.HealthData;
import org.spongepowered.api.data.value.BaseValue;
import org.spongepowered.api.data.value.ValueContainer;
import org.spongepowered.api.data.value.mutable.CollectionValue;
import org.spongepowered.api.data.value.mutable.Value;
import org.spongepowered.api.entity.Entity;

/**
 * An implementation processor for handling a particular {@link BaseValue}.
 * Usually every {@linkplain ValueProcessor} will deal only with
 * {@link Value}s associated with the key returned by {@link #getKey()}.
 *
 * @param <E> The type of element within the value
 * @param <V> The type of Value
 */
public interface ValueProcessor<E, V extends BaseValue<E>> {

    /**
     * Gets the associated {@link Key} that this {@link ValueProcessor}
     * will handle.
     *
     * @return The associated key for this processor
     */
    Key<? extends BaseValue<E>> getKey();

    /**
     * Gets the priority of this processor. A single {@link Key} can have
     * multiple {@link ValueProcessor}s such that mods introducing
     * changes to the game can provide their own {@link ValueProcessor}s
     * for specific cases. The notion is that the higher the priority, the
     * earlier the processor is used. If for any reason a processor's method
     * is returning an {@link Optional#absent()} or
     * {@link DataTransactionResult} with a failure, the next processor in
     * line will be used. By default, all Sponge processors are with a
     * priority of 100.
     *
     * @return The priority of the processor
     */
    int getPriority();

    /**
     * Gets the underlying value as an {@link Optional}. This is the direct
     * implementation of {@link ValueContainer#get(Key)}. As well, since the
     * return type is {@link Optional}, this method too is applicable for
     * {@link ValueContainer#getOrNull(Key)} and
     * {@link ValueContainer#getOrElse(Key, Object)} as they are simply
     * additional methods called from {@link Optional#orNull()} and
     * {@link Optional#or(Object)}.
     *
     *
To truly understand the use of this method, the thought process
     * is that a {@link ValueContainer} being mixed in to existing minecraft
     * classes will require a pseudo lookup of the {@link Key} to associate to
     * a field belonging to provided {@link ValueContainer}. Being that the
     * {@link Value} is very specific, the only assumption of mixed in
     * implementations will have no room for extra possibilities. Therefor,
     * this method serves as a "guarantee" that we've found the type of
     * {@link Value} we want to retrieve, and all we need to do is validate
     * that the {@link Value} is infact compatible with the provided
     * {@link ValueContainer}.

     *
     *
An example of this type of interaction is getting the health from an
     * {@link Entity}. Normally, when you have an {@link Entity}, you can
     * grab health two ways:

{@code entity.get(Keys.HEALTH)}

     *

{@code entity.get(HealthData.class).health()}

     *
The advantage of the first is that the use of
     * {@link Entity#get(Key)} will result in a call to this method for a
     * {@link ValueProcessor} handling specifically the health value. The
     * second case will use the same {@link ValueProcessor} but be retrieving
     * the values directly from the {@link HealthData} {@link DataManipulator}.
     * This differs with object creation as the second method will result in an
     * unecessary {@link DataManipulator} to be created, and then finally a
     * {@link ValueProcessor} method call for the {@link DataManipulator}
     * instead of the {@link Entity} having a direct call.

     *
     *
The cases where this type of value usage is not preferable is with
     * more complex {@link Value}s, such as {@link CollectionValue},
     * values found for {@link MobSpawnerData} and {@link CommandData}. Using
     * the {@link ValueContainer#get(Key)} and
     * {@link DataManipulator#set(Key, Object)} remains to be the optimal methods
     * to use as they do not rely on the implementation attempting to guess which
     * {@link Key}, {@link Value} and {@link ValueProcessor} is needed to
     * manipulate the data.

     *
     * @param container The value container to retrieve the value froms
     * @return The value, if available and compatible
     */
    Optional<E> getValueFromContainer(ValueContainer<?> container);

    /**
     * Gets the actual {@link Value} object wrapping around the underlying value
     * desired from the provided {@link ValueContainer}. This is very similar to
     * {@link #getValueFromContainer(ValueContainer)} except that instead of an
     * actual value, a {@link Value} or extension there of is returned.
     *
     * @param container The container to get the API value from
     * @return The {@link Value} typed value
     */
    Optional<V> getApiValueFromContainer(ValueContainer<?> container);

    /**
     * Checks if the provided {@link ValueContainer} is compatible with the
     * value of data associated with this {@link ValueProcessor}.
     *
     * @param container The value container to check
     * @return True if the container supports the value
     */
    boolean supports(ValueContainer<?> container);

    /**
     * Offers the provided {@link BaseValue} containing a value of the
     * appropriate value type of this {@link ValueProcessor} to offer
     * back to the {@link ValueContainer}.
     *
     * @param container The value container
     * @param value The value
     * @return The transaction result
     */
    DataTransactionResult offerToStore(ValueContainer<?> container, E value);

    /**
     * Attempts to remove the known keyed data associated with this
     * {@link ValueProcessor} from the provided {@link ValueContainer}. If
     * the result is not possible, the result will be an expected
     * {@link org.spongepowered.api.data.DataTransactionResult.Type#FAILURE}.
     *
     * @param container The value container to remove data from
     * @return The transaction result
     */
    DataTransactionResult removeFrom(ValueContainer<?> container);

}


text:
/**
 * \file
 * \brief Unit Test for GPIO string
 *
 * \author Uilian Ries <uilianries@gmail.com>
 */
#include <catch.hpp>

#include "bbbgpio/string.hpp"

namespace bbb {
namespace test {

    /**
     * \brief Convert pin_level and compare to string
    */
    TEST_CASE("ToString", "[string]")
    {
        REQUIRE("high" == bbb::gpio::to_string(bbb::gpio::pin_level::high));
        REQUIRE("low" == bbb::gpio::to_string(bbb::gpio::pin_level::low));
    }

} // namespace test
} // namespace bbb


text:
<?php

# End of file
# Location /system/helpers/database_helper.php


text:
package model.interfaces;

/**
 * Assignment interface for SADI
 *
 * @author Caspar Ryan
 *
 */
public interface WheelCallback
{
	/**
	 * called when the next number on the wheel comes up use this to update your
	 * display
	 *
	 * @param nextNumber
	 *            the current number as the wheel spins
	 * @param engine
	 *            a reference to the engine so the receiver can call methods as
	 *            necessary
	 * @see model.interfaces.GameEngine
	 */
	public void nextNumber(int nextNumber, GameEngine engine);

	/**
	 *
	 * called when wheel has stopped process bets here
	 *
	 * @param result
	 *            the number the wheel stopped on
	 * @param engine
	 *            a reference to the engine so the receiver can call methods as
	 *            necessary
	 */
	public void result(int result, GameEngine engine);
}


text:
namespace mojo {

template <typename T>
class Array;

template <typename K, typename V>
class Map;

template <typename T>
class WTFArray;

namespace internal {

template <typename T>
class Array_Data;

class ArrayValidateParams;

class Buffer;

template <typename K, typename V>
class Map_Data;

struct SerializationContext;

template <typename T>
struct ShouldUseNativeSerializer;

// -----------------------------------------------------------------------------
// Forward declaration for native types.

template <typename T>
size_t GetSerializedSizeNative_(const T& value, SerializationContext* context);

template <typename T>
void SerializeNative_(const T& value,
                      Buffer* buffer,
                      Array_Data<uint8_t>** out,
                      SerializationContext* context);

template <typename T>
bool DeserializeNative_(Array_Data<uint8_t>* data,
                        T* out,
                        SerializationContext* context);

}  // namespace internal

// -----------------------------------------------------------------------------
// Forward declaration for Array.

template <typename E>
inline size_t GetSerializedSize_(const Array<E>& input,
                                 internal::SerializationContext* context);

template <typename E, typename F>
inline void SerializeArray_(
    Array<E> input,
    internal::Buffer* buf,
    internal::Array_Data<F>** output,
    const internal::ArrayValidateParams* validate_params,
    internal::SerializationContext* context);

template <typename E, typename F>
inline bool Deserialize_(internal::Array_Data<F>* input,
                         Array<E>* output,
                         internal::SerializationContext* context);

// -----------------------------------------------------------------------------
// Forward declaration for WTFArray.

template <typename E>
inline size_t GetSerializedSize_(const WTFArray<E>& input,
                                 internal::SerializationContext* context);

template <typename E, typename F>
inline void SerializeArray_(
    WTFArray<E> input,
    internal::Buffer* buf,
    internal::Array_Data<F>** output,
    const internal::ArrayValidateParams* validate_params,
    internal::SerializationContext* context);

template <typename E, typename F>
inline bool Deserialize_(internal::Array_Data<F>* input,
                         WTFArray<E>* output,
                         internal::SerializationContext* context);

// -----------------------------------------------------------------------------
// Forward declaration for Map.

template <typename MapKey, typename MapValue>
inline size_t GetSerializedSize_(const Map<MapKey, MapValue>& input,
                                 internal::SerializationContext* context);

template <typename MapKey,
          typename MapValue,
          typename DataKey,
          typename DataValue>
inline void SerializeMap_(
    Map<MapKey, MapValue> input,
    internal::Buffer* buf,
    internal::Map_Data<DataKey, DataValue>** output,
    const internal::ArrayValidateParams* value_validate_params,
    internal::SerializationContext* context);

template <typename MapKey,
          typename MapValue,
          typename DataKey,
          typename DataValue>
inline bool Deserialize_(internal::Map_Data<DataKey, DataValue>* input,
                         Map<MapKey, MapValue>* output,
                         internal::SerializationContext* context);

}  // namespace mojo

#endif  // MOJO_PUBLIC_CPP_BINDINGS_LIB_SERIALIZATION_FORWARD_H_


text:
function tsip_challenge(o_stack, b_isproxy, s_scheme, s_realm, s_nonce, s_opaque, s_algorithm, s_qop) {
    this.o_stack = o_stack;
    this.b_isproxy = b_isproxy;
	this.s_scheme = s_scheme;
	this.s_realm = s_realm;
	this.s_nonce = s_nonce;
	this.s_opaque = s_opaque;
	this.s_algorithm = s_algorithm;
	this.s_cnonce = null;
	this.i_nc = 0;
	if (s_qop) {
	    this.s_qop = tsk_string_contains(s_qop, s_qop.length, "auth-int") ? "auth-int" :
					(tsk_string_contains(s_qop, s_qop.length, "auth") ? "auth" : null);
	    this.reset_cnonce();
	}
}

tsip_challenge.prototype.get_username = function(){
    return this.o_stack.identity.s_impi;
}

tsip_challenge.prototype.get_password = function(){
    return this.o_stack.identity.s_password;
}

tsip_challenge.prototype.reset_cnonce = function () {
    if (this.s_qop) {
        this.s_cnonce = MD5.hexdigest(tsk_string_random(21));
        this.i_nc = 1;
    }
}

tsip_challenge.prototype.get_response = function (s_method, s_uristring, o_entity_body) {
    if (tsk_string_iequals(this.s_scheme, "Digest")) {
        var s_nc = "";

        /* ===
        Calculate HA1 = MD5(A1) = M5(username:realm:secret)
        */
        var s_ha1 = tsip_auth_digest_HA1(this.get_username(), this.s_realm, this.get_password());

        /* ===
        HA2
        */
        var s_ha2 = tsip_auth_digest_HA2(s_method, s_uristring, o_entity_body, this.s_qop);

        /* RESPONSE */
        if (this.i_nc) {
            s_nc = tsip_challenge.prototype.Ncount2String(this.i_nc);
        }
        var s_md5_response = tsip_auth_digest_response(s_ha1, this.s_nonce, s_nc, this.s_cnonce, this.s_qop, s_ha2);

        if (this.s_qop) {
            ++this.i_nc;
        }
        return s_md5_response;
    }
    return null;
}

tsip_challenge.prototype.update = function (s_scheme, s_realm, s_nonce, s_opaque, s_algorithm, s_qop) {
    var b_noncechanged = !tsk_string_iequals(this.s_nonce, s_nonce);

    this.s_scheme = s_scheme;
    this.s_realm = s_realm;
    this.s_nonce = s_nonce;
    this.s_opaque = s_opaque;
    this.s_algorithm = s_algorithm;
    if (s_qop) {
        this.s_qop = tsk_string_contains(s_qop, s_qop.length, "auth-int") ? "auth-int" :
					(tsk_string_contains(s_qop, s_qop.length, "auth") ? "auth" : null);
    }

    if (b_noncechanged && this.s_qop) {
        this.reset_cnonce();
    }
    return 0;
}

tsip_challenge.prototype.create_header_authorization = function(o_request){
	var s_nc = null;
	var s_uristring = null;
	var o_header = null;

    if(!(s_uristring = tsip_uri_tostring(o_request.line.request.o_uri, true, false))){
        tsk_utils_log_error("Failed to parse URI: " + o_request.line.request.o_uri);
        return null;
    }

	/* We compute the nc here because @ref tsip_challenge_get_response function will increment it's value. */
	if (this.i_nc) {
        s_nc = tsip_challenge.prototype.Ncount2String(this.i_nc);
    }

	/* entity_body ==> request-content */
    var s_response = this.get_response(o_request.line.request.s_method, s_uristring, o_request.o_content);

    o_header = new tsip_header_Authorization();
    o_header.e_type = this.b_isproxy ? tsip_header_type_e.Proxy_Authorization : tsip_header_type_e.Authorization;
	o_header.s_scheme = this.s_scheme;
	o_header.s_username = this.get_username();
	o_header.s_realm = this.s_realm;
	o_header.s_nonce = this.s_nonce;
	o_header.s_uri = s_uristring;
	o_header.s_response = s_response;
	o_header.s_algorithm = this.s_algorithm ? this.s_algorithm : "MD5";
	o_header.s_cnonce = this.i_nc ? this.s_cnonce : null;
	o_header.s_opaque = this.s_opaque;
	o_header.s_qop = this.s_qop;
	o_header.s_nc = s_nc;

	return o_header;
}

tsip_challenge.prototype.CreateEmptyHeaderAuthorization = function(s_username, s_realm, s_uristring){
	var o_header = new tsip_header_Authorization();

	if(o_header){
        o_header.e_type = tsip_header_type_e.Authorization;
		o_header.s_scheme = "Digest";
		o_header.s_username = s_username;
		o_header.s_realm = s_realm;
		o_header.s_nonce = "";
		o_header.s_response = "";
		o_header.s_uri = s_uristring;
	}

	return o_header;
}

tsip_challenge.prototype.Ncount2String = function (i_nc) {
    var i = 7;
    var s_nc = "";
    do {
        s_nc += "0123456789abcdef"[(i_nc >> i * 4) & 0xF];
    }
    while (i--);
    //return s_nc.split("").reverse().join("");
    return s_nc;
}


text:
<?php
namespace backend\modules\admin\controllers;

use backend\library\AdminController;
use fayfox\models\tables\Users;
use fayfox\models\Setting;
use fayfox\core\Response;

class SystemController extends AdminController{
	public function isCellphoneExist(){
		if(Users::model()->fetchRow(array(
			'cellphone = ?'=>$this->input->post('value', 'trim'),
			'id != ?'=>$this->input->request('id', 'intval')
		))){
			echo json_encode(array(
				'status'=>0,
				'message'=>'该手机号码已被注册',
			));
		}else{
			echo json_encode(array(
				'status'=>1,
			));
		}
	}

	public function isEmailExist(){
		if(Users::model()->fetchRow(array(
			'email = ?'=>$this->input->post('value', 'trim'),
			'id != ?'=>$this->input->request('id', 'intval')
		))){
			echo json_encode(array(
				'status'=>0,
				'message'=>'该邮箱已被注册',
			));
		}else{
			echo json_encode(array(
				'status'=>1,
			));
		}
	}

	public function isUsernameExist(){
		if(Users::model()->fetchRow(array(
			'username = ?'=>$this->input->post('value', 'trim'),
			'id != ?'=>$this->input->request('id', 'intval')
		))){
			echo json_encode(array(
				'status'=>0,
				'message'=>'该用户名已被注册',
			));
		}else{
			echo json_encode(array(
				'status'=>1,
			));
		}
	}

	public function setting(){
		if($this->input->post()){
			if($this->form('setting')
				->setModel(Setting::model())
				->check()){
				$data = $this->form('setting')->getAllData();
				$key = $data['_key'];
				unset($data['_key']);
				Setting::model()->set($key, $data);
				Response::output('success', '设置保存成功');
			}else{
				Response::output('error', '异常的数据格式');
			}
		}else{
			Response::output('error', '无数据被提交');
		}
	}
}


text:
namespace Google.Cloud.OsConfig.V1Alpha.Snippets
{
    // [START osconfig_v1alpha_generated_OsConfigZonalService_GetInventory_async_flattened_resourceNames]
    using Google.Cloud.OsConfig.V1Alpha;
    using System.Threading.Tasks;

    public sealed partial class GeneratedOsConfigZonalServiceClientSnippets
    {
        /// <summary>Snippet for GetInventoryAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetInventoryResourceNamesAsync()
        {
            // Create client
            OsConfigZonalServiceClient osConfigZonalServiceClient = await OsConfigZonalServiceClient.CreateAsync();
            // Initialize request argument(s)
            InventoryName name = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]");
            // Make the request
            Inventory response = await osConfigZonalServiceClient.GetInventoryAsync(name);
        }
    }
    // [END osconfig_v1alpha_generated_OsConfigZonalService_GetInventory_async_flattened_resourceNames]
}


text:
module Sorcery
  module Adapters
    class BaseAdapter
      def initialize(model)
        @model = model
      end

      def self.from(klass)
        @klass = klass
        self
      end

      def self.delete_all
        @klass.delete_all
      end

      def self.find(id)
        find_by_id(id)
      end

      def increment(field)
        @model.increment(field)
      end

      def update_attribute(name, value)
        update_attributes(name => value)
      end
    end
  end
end


text:
layout: acgRedirect
acgRedirectUrl: https://github.com/tianocore/tianocore.github.io/wiki/UDK2015
title: UDK2015
---

{% include site-links.md %}

UDK2015 is a stable release of portions of the [EDK II] project.

Link for  UDK2014 previous releases UDK2014 releases -Archive

If you have questions please email the  edk2-devel email list.

  <MTMarkdownOptions output='html4'>

       UDK2015 Releases

       </MTMarkdownOptions>

     What is it?
     What's in the package?

      w/ WorkSpace Expanded .zip

      Release Sept 29, 2015

      Release Notes

UEFI development Kit (UDK) 2015 (UDK2015) Release (Complete zip of all packages and documentation where packages are expanded to MyWorkSpace Directory)

Based on svn version:

https://svn.code.sf.net/p/edk2/code/branches/UDK2015 : r18552

      https://svn.code.sf.net/p/edk2-fatdriver2/code/trunk/FatPkg: r96

How to Build

      How to Build UDK2014 Release

Features Summary:

      See Release Notes Features

Supported OS and Build Environments

Using newer versions of Linux with Native GCC 4.x

Windows systems

Xcode Mac OS X

Unix-like systems (For older Linux distributions, or using Cygwin or Mac OS X)

(UDK2015)

File List
      Of Entire Release .zip

Notes UDK2015

      Feature details :

      Download All

Documents

      Download All

      <MTMarkdownOptions output='html4'>
      EDK II Specifications
      </MTMarkdownOptions>

    What is it?

Version 1.24 and 1.25

UDK2015 EDK II v1.24-1.25 specifications

      Link to EDK II Specifications page

      These documents describe the EDK II build information for the following (Build, DEC, DSC, FDF and INF) file formats and it contains the Errata updates (version 1.24 and 1.25) that are available with the UDK2015 release.  See details in the Revision History in each of the individual documents for more details.

Update July-Aug, 2015 V 1.24 & 1.25

    <MTMarkdownOptions output='html4'>
      Documents
      </MTMarkdownOptions>

     What is it?
     What's in the Download?

   BRANCH

Download All CHM/HTMLs

This download contains all .chm and .html documents for UDK2015.  Each package includes details on the definitions (including PPIs/PROTOCOLs/GUIDs and library classes) and libraries instances associated with each package.

Contains both .chm file and .html files in this .zip for all UDK2015  documents

CryptoPkg .chm

CryptoPkg .zip

The CryptoPkg Document Package Helper file. This Package provides cryptographic-related libraries for UEFI security modules.

.chm file

      .html file

IntelFrameworkModulePkg .chm

IntelFrameworkModulePkg .zip

The IntelFrameworkModulePkg Document Package Helper file. This Package contains the definitions and module implementation
which follows Intel EFI Framework Specification.

.chm file
 .html file

IntelFrameworkPkg .chm

IntelFrameworkPkg .zip

      The IntelFrameworkPkg Document Package Helper file.  This package provides definitions and libraries that comply to Intel Framework Specifications.

.chm file
 .html file

MdeModulePkg .chm

MdeModulePkg .zip

The MdeModulePkg Document Package Helper file. This package provides the modules that conform to UEFI/PI Industry standards.
      It also provides the defintions(including PPIs/PROTOCOLs/GUIDs and library classes)
      and libraries instances, which are used for those modules

.chm file
 .html file

MdePkg w/ Libraries .chm

MdePkg w/ Libraries .zip

MdePkg .chm

MdePkg  .zip

The MdePkg Document Package Helper file. This Package provides all definitions(including functions, MACROs, structures and library classes)
      and libraries instances, which are defined in MdePkg's .chm files.
      It also provides the definitions(including PPIs/PROTOCOLs/GUIDs) of
      EFI1.10/UEFI2.4/PI1.3 and some Industry Standards.

.chm file
 .html file

 .chm file
 .html file

NetworkPkg.chm

NetworkPkg.zip

The NetworkPkg Document Package Helper file. This package provides network modules that conform to UEFI 2.2 specification.

.chm file
 .html file

SecurityPkg.chm

SecurityPkg.zip

The SecurityPkg Document Package Helper file. This package includes the security drivers, defintions(including PPIs/PROTOCOLs/GUIDs
      and library classes) and libraries instances

.chm file
 .html file

      <MTMarkdownOptions output='html4'>
       Previous UDK Releases
      </MTMarkdownOptions>

UDK2014 Archive

Menu for downloading Previous UDK2014 releases

N/A

UDK2010 Archive

Menu for downloading Previous UDK2010 releases

        <MTMarkdownOptions output='html4'>
       Other Releated UDK Releases
      </MTMarkdownOptions>

     Download
     What is it?
     What's in the package?

Go to Driver Dev Page

UEFI Driver Writer's Wizard and the
UEFI Driver Writer's Guide supports UEFI 3.2.1 version of the Specification. See the
Driver Developer page for more resources for UEFI Driver Writers Resources

 UEFI Packaging Tool.zip

 Quick Start Guide

Intel® UEFI Packaging Tool is used to create, install or remove a UEFI Distribution Package.
The .Zip includes bin UPT.exe from http://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2/BaseTools/Bin/Win32
and Manual Documentation from http://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2/BaseTools/UserManuals plus the Quick Start Guide

.zip

User PDF Guide only

EADK Release 1.02.zip

Release Notes

EDK II Application Development Kit EADK
 Release 1.02 Package incorporates the Standard C Library, BSD Sockets Library, and other standards-based components. Include these into standard "C" applications. See the AppPkg for examples using the Standard Library components.  Further information is available in the ReadMe.txt files.

* Based on  SVN  https://svn.code.sf.net/p/edk2/code/trunk/edk2/  -r 14804

Packages Included in zip

 AppPkg

 StdLib

 StdLibPrivateInternalFiles

UEFI Shell 2.0 .zip

 Shell 2.0 Documentation

EDK II Sources for the UEFI Shell 2.0 Spec. Package Release 1.0 - Verified and tested SVN Rersion:
https://svn.code.sf.net/p/edk2/code/trunk/edk2/ShellPkg r11566

This release is the implmentation sources for the UEFI Shell Specification 2.0. Please see http://www.uefi.org to download this specification

See
 Shell_FAQ How to include UEFI Shell 2.0 into .DSC file

 ShellPkg .zip Package

<MTMarkdownOptions output='html4'>

More Info

</MTMarkdownOptions>

EDK II More info:
Getting Started for Developers,
EDK II Overview, EDKII Packages

UEFI Developers Kit 2015 (UDK2015).  The UDK2015 is the EDKII support for all currently published UEFI specifications UDK2015 currently supports UEFI 2.5 and PI 1.4 level of specifications.

The Intel(R) UDK Debugger Tool and its detailed user manual may be obtained from http://firmware.intel.com


text:
import extractForm from './extractForm'
import exampleGroupMarkup from '../../mocks/wordSet-entry1-sense5-exampleGroup'
import exampleGroupMarkupWithLinkword from '../../mocks/wordSet-entry1-sense6-exampleGroup2'

describe('extractForm', () => {
    it('extracts correct form', () => {
        expect(extractForm(exampleGroupMarkup)).toEqual(
            'set the pattern/tone/trend etc (for something)'
        )
    })

    it('extracts correct form if there is linkword', () => {
        expect(extractForm(exampleGroupMarkupWithLinkword)).toEqual(
            'set something on fire/alight/ablaze (also set fire to something)'
        )
    })
})


text:
package eap.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import eap.base.BaseController;
import eap.comps.token.TokenExpiredException;
import eap.comps.webevent.WebEventsHelper;
import eap.exception.BizException;
import eap.util.ExceptionUtil;
import eap.util.HttpUtil;
import eap.util.StringUtil;

/**
 * <p> Title: </p>
 * <p> Description: </p>
 * @作者 chiknin@gmail.com
 * @创建时间
 * @版本 1.00
 * @修改记录
 * <pre>
 * 版本       修改人         修改时间         修改内容描述
 * ----------------------------------------
 *
 * ----------------------------------------
 * </pre>
 */
public class HandlerExceptionResolver implements org.springframework.web.servlet.HandlerExceptionResolver { // not bizException;   all RuntimEexception

	private static final Logger logger = LoggerFactory.getLogger(HandlerExceptionResolver.class);

	private String errorViewPrefix = "";

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e)
	{
	    Throwable cause = ExceptionUtil.getRootCause(e);

		if (e.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) { // Tomcat Server // ClientAbortException:  java.net.SocketException: Software caused connection abort: socket write error
			logger.debug(e.getMessage(), cause);
			return null;
		}

		if (e instanceof TokenExpiredException) {
			logger.error(e.getMessage(), cause);

			if (HttpUtil.isAjaxRequest(request)) {
//				BaseController bc = (BaseController) handler;
//				String formId = bc.getParameter(env.getFormIdField());
//				if (StringUtils.isNotBlank(formId)) {
//					WebFormVO webFormVO = new WebFormVO();
//					this.setForm(formId, WebEventsHelper.toWebFormVO(request, e));
//				}
//
//				String formId = r.getParameter(env.getFormIdField());
////				String viewName = bc.getParameter(env.getInputViewNameField());
////				String viewName = (String) this.getSession().getAttribute(env.getInputViewNameField() + formId);
//				String viewName = requestMapping.inputView();
//
//				if (StringUtils.isNotBlank(formId)) {
//					this.setForm(formId, WebEventsHelper.toWebFormVO(request, e));
//				}

				WebEventsHelper.getWebEvents(request).alert("error", e.getMessage());
				return new ModelAndView(errorViewPrefix + "errorAjax");
			} else {
				String referer = request.getHeader("referer");
				if (StringUtil.isNotBlank(referer) && !referer.equals(request.getRequestURL().toString())) {
					try {
						response.sendRedirect(referer);
						return new ModelAndView();
					} catch (IOException sre) {
						logger.error(sre.getMessage(), cause);
					}
				}
			}

			return this.getErrorModelAndView(request, HttpServletResponse.SC_NOT_ACCEPTABLE);
		}

		ModelAndView mnv = null;
		if (handler instanceof BaseController) {
			BaseController bc = (BaseController) handler;

			if (e instanceof BindException) {
				bc.logger.error(e.getMessage(), cause);
				mnv = bc.validateError(request, response, (BindException) e);
			} else if (e instanceof BizException) {
				String viewName = bc.setException(e); // in setException ->  log error
				mnv = new ModelAndView(viewName, ((BizException) e).getModel());
			}
//			else if (e instanceof HttpRequestMethodNotSupportedException) {
//				String referer = request.getHeader("referer");
//				if (StringUtil.isNotBlank(referer) && !referer.equals(request.getRequestURL().toString())) {
//					try {
//						response.sendRedirect(referer);
//						return new ModelAndView();
//					} catch (IOException sre) {
//						logger.error(e.getMessage(), e);
//					}
//				}
//			}
			else {
				bc.logger.error(e.getMessage(), cause);
				WebEventsHelper.getWebEvents(request).alert("error", "服务器繁忙");
			}

			if (HttpUtil.isAjaxRequest(request)) {
//				WebAjaxResponse responseObject = new WebAjaxResponse();
//				responseObject.setSystemTime(DateUtil.currDate());
//				responseObject.setEvents(WebEventsHelper.getWebEvents(request).getEvents());
				mnv =  new ModelAndView(errorViewPrefix + "errorAjax");
			}

			if (mnv == null) {
				mnv = this.getErrorModelAndView(request, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			}
		}
		else {
			logger.error(e.getMessage(), cause);
			mnv = this.getErrorModelAndView(request, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}

		return mnv;
	}

	private ModelAndView getErrorModelAndView(HttpServletRequest request, int statucCode) {
		boolean isAjaxRequest = HttpUtil.isAjaxRequest(request);
		return new ModelAndView(errorViewPrefix + String.format("error%d%s", statucCode, isAjaxRequest ? "Ajax" : ""));
	}

	public void setErrorViewPrefix(String errorViewPrefix) {
		this.errorViewPrefix = errorViewPrefix;
	}
}


text:
import math
import uuid
from datetime import datetime
from urllib.parse import urlparse

import requests
from requests.adapters import HTTPAdapter
from requests.exceptions import RequestException, Timeout
from requests_toolbelt import MultipartEncoder

from ingenico.connect.sdk.communication_exception import CommunicationException
from ingenico.connect.sdk.endpoint_configuration import EndpointConfiguration
from ingenico.connect.sdk.log.body_obfuscator import BodyObfuscator
from ingenico.connect.sdk.log.header_obfuscator import HeaderObfuscator
from ingenico.connect.sdk.log.obfuscation_capable import ObfuscationCapable
from ingenico.connect.sdk.log.request_log_message import RequestLogMessage
from ingenico.connect.sdk.log.response_log_message import ResponseLogMessage
from ingenico.connect.sdk.pooled_connection import PooledConnection
from ingenico.connect.sdk.multipart_form_data_object import MultipartFormDataObject
from ingenico.connect.sdk.response_header import get_header_value

CHARSET = "UTF-8"

class DefaultConnection(PooledConnection, ObfuscationCapable):
    """
    Provides an HTTP request interface, thread-safe

    :param connect_timeout: timeout in seconds before a pending connection is
     dropped
    :param socket_timeout: timeout in seconds before dropping an established
     connection. This is the time the server is allowed for a response
    :param max_connections: the maximum number of connections in the connection
     pool
    :param proxy_configuration: ProxyConfiguration object that contains data
     about proxy settings if present.
     It should be writeable as string and have a scheme attribute.

    Use the methods get, delete, post and put to perform the corresponding HTTP
    request.
    Alternatively you can use request with the request method as the first
    parameter.

    URI, headers and body should be given on a per-request basis.
    """

    def __init__(self, connect_timeout,
                 socket_timeout,
                 max_connections=EndpointConfiguration.DEFAULT_MAX_CONNECTIONS,
                 proxy_configuration=None):
        self.logger = None
        self.__requests_session = requests.session()
        self.__requests_session.mount("http://", HTTPAdapter(
            pool_maxsize=max_connections, pool_connections=1))
        self.__requests_session.mount("https://", HTTPAdapter(
            pool_maxsize=max_connections, pool_connections=1))
        # request timeouts are in seconds
        self.__connect_timeout = connect_timeout if connect_timeout >= 0 else None
        self.__socket_timeout = socket_timeout if socket_timeout >= 0 else None
        if proxy_configuration:
            proxy = {"http": str(proxy_configuration),
                     "https": str(proxy_configuration)}
            self.__requests_session.proxies = proxy

        self.__body_obfuscator = BodyObfuscator.default_body_obfuscator()
        self.__header_obfuscator = HeaderObfuscator.default_header_obfuscator()

    @property
    def connect_timeout(self):
        """Connection timeout in seconds"""
        return self.__connect_timeout

    @property
    def socket_timeout(self):
        """Socket timeout in seconds"""
        return self.__socket_timeout

    def get(self, url, request_headers):
        """Perform a request to the server given by url

        :param url: the url to the server, given as a parsed url
        :param request_headers: a list containing RequestHeader objects
         representing the request headers
        """
        return self._request('get', url, request_headers)

    def delete(self, url, request_headers):
        """Perform a request to the server given by url

        :param url: the url to the server, given as a parsed url
        :param request_headers: a list containing RequestHeader objects
         representing the request headers
        """
        return self._request('delete', url, request_headers)

    def post(self, url, request_headers, body):
        """Perform a request to the server given by url

        :param url: the url to the server, given as a parsed url
        :param request_headers: a list containing RequestHeader objects
         representing the request headers
        :param body: the request body
        """
        if isinstance(body, MultipartFormDataObject):
            body = self.__to_multipart_encoder(body)
        return self._request('post', url, request_headers, body)

    def put(self, url, request_headers, body):
        """Perform a request to the server given by url

        :param url: the url to the server, given as a parsed url
        :param request_headers: a list containing RequestHeader objects
         representing the request headers
        :param body: the request body
        """
        if isinstance(body, MultipartFormDataObject):
            body = self.__to_multipart_encoder(body)
        return self._request('put', url, request_headers, body)

    def __to_multipart_encoder(self, multipart):
        fields = {}
        for name, value in multipart.values.items():
            fields[name] = value
        for name, uploadable_file in multipart.files.items():
            fields[name] = (uploadable_file.file_name, uploadable_file.content, uploadable_file.content_type)
        encoder = MultipartEncoder(fields=fields, boundary=multipart.boundary)
        if encoder.content_type != multipart.content_type:
            raise ValueError("MultipartEncoder did not create the expected content type")
        return encoder

    class _ToResult(object):
        def __call__(self, func):
            def _wrapper(*args, **kwargs):
                result = func(*args, **kwargs)
                header = next(result)
                return header + (result,)
            return _wrapper

    @_ToResult()
    def _request(self, method, url, headers, body=None):
        """
        Perform a request to the server given by url

        :param url: the url to the server, given as a parsed url
        :param headers: a list containing RequestHeader objects representing
         the request headers
        :param body: the request body
        """
        headers = {} if not headers else headers
        if not isinstance(url, str):
            url = url.geturl()

        # convert the list of RequestParam objects to a dictionary of key:value
        # pairs if necessary
        if headers and not isinstance(headers, dict):
            headers = {param.name: param.value for param in headers}

        # send request with all parameters not declared in session and with
        # callback for logging response
        request = requests.Request(method, url, headers=headers, data=body,
                                   hooks={'response': self._cb_log_response})
        prepped_request = self.__requests_session.prepare_request(request)
        # add timestamp to request for later reference
        prepped_request.timestamp = datetime.now()
        _id = str(uuid.uuid4())
        # store random id in request so it can be matched with its response
        # in logging
        prepped_request.id = _id
        self._log_request(prepped_request)
        try:
            timeout_ = (self.__connect_timeout, self.__socket_timeout)
            requests_response = self.__requests_session.send(prepped_request,
                                                             timeout=timeout_,
                                                             stream=True)
            try:
                iterable = requests_response.iter_content(chunk_size=1024)
                yield requests_response.status_code, requests_response.headers
                for chunk in iterable:
                    yield chunk
            finally:
                requests_response.close()

        except Timeout as timeout:
            self._log_error(prepped_request.id, timeout,
                            prepped_request.timestamp)
            raise CommunicationException(timeout)
        except RequestException as exception:
            self._log_error(prepped_request.id, exception,
                            prepped_request.timestamp)
            raise CommunicationException(exception)
        except RuntimeError as exception:
            self._log_error(prepped_request.id, exception,
                            prepped_request.timestamp)
            raise

    def _log_request(self, request):
        """
        Log parameter request if logging is enabled at the moment of logging.
        Also adds a timestamp to the request for response logging
        """
        logger = self.logger
        if logger is None:
            return
        method = request.method
        url = urlparse(request.url)
        if url.query:
            local_path = url.path + "?" + url.query
        else:
            local_path = url.path
        try:
            message = RequestLogMessage(request_id=request.id, method=method, uri=local_path,
                                        body_obfuscator=self.__body_obfuscator,
                                        header_obfuscator=self.__header_obfuscator)
            for name in request.headers:
                message.add_header(name, request.headers[name])
            body = request.body
            if body:
                content = request.headers['Content-Type']
                if content != "application/json":
                    message.set_body(body, content, CHARSET)
                else:
                    message.set_body(body, content)
            logger.log_request(message)
        except Exception as exception:
            logger.log("An error occurred trying to log request '{}'".format(
                request.id), exception)

    def _cb_log_response(self, response, **kwargs):
        """Log parameter response if logging is enabled at the moment of logging"""
        logger = self.logger
        if logger is None:
            return
        request = response.request
        _id = request.id
        duration = math.ceil((datetime.now() - request.timestamp).total_seconds() * 1000)
        status_code = response.status_code
        try:
            message = ResponseLogMessage(request_id=_id,
                                         status_code=status_code,
                                         duration=duration,
                                         body_obfuscator=self.__body_obfuscator,
                                         header_obfuscator=self.__header_obfuscator)
            for name in response.headers:
                message.add_header(name, response.headers[name])
            if self.__is_binary(response.headers):
                body = "<binary content>"
            else:
                # The response is always encoded UTF8
                # When this is not specified anywhere, the response body will be encoded in the wrong way
                response.encoding = 'utf8'
                body = response.text
            if body:
                content = response.headers['Content-Type']
                message.set_body(body, content)
            logger.log_response(message)
        except Exception as exception:
            message = "An error occurred trying to log response '{}'".format(_id)
            logger.log(message, exception)

    def _log_error(self, request_id, error, start_time):
        """Log communication errors when logging is enabled"""
        logger = self.logger
        if logger:
            duration = math.ceil((datetime.now() - start_time).total_seconds() * 1000)
            logger.log(
                "Error occurred for outgoing request (requestId='{}', {} s)".format(
                    request_id, duration), error)

    def __is_binary(self, headers):
        content_type = get_header_value(headers, "Content-Type")
        if content_type is None:
            return False
        content_type = content_type.lower()
        return not (content_type.startswith("text/") or "json" in content_type or "xml" in content_type)

    def set_body_obfuscator(self, body_obfuscator):
        self.__body_obfuscator = body_obfuscator

    def set_header_obfuscator(self, header_obfuscator):
        self.__header_obfuscator = header_obfuscator

    def enable_logging(self, communicator_logger):
        self.logger = communicator_logger

    def disable_logging(self):
        self.logger = None

    def close_idle_connections(self, idle_time):
        """
        :param idle_time: a datetime.timedelta object indicating the idle time
        """
        pass

    def close_expired_connections(self):
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    def close(self):
        """
        Explicitly closes the connection
        """
        self.__requests_session.close()