text:
// 1.0.4 Hawk.js | Copyright (c) 2013 Matthew Parke | (MIT LICENSE) hawkjs.org/#license
var Hawk = (function(){

	// An exception class to be instantiated when a requested Hawk class name does not exist
	function DoesNotExistException(className){
		this.value = className;
		this.message = 'definition does not exist.';
		this.toString = function(){
			return this.value + ' ' + this.message;
		};
	}

	// An exception class to be instantiated when a value is Not of type number
	function NumberTypeError(value){
		this.value = value;
		this.message = 'must be a number.';
		this.toString = function(){
			return this.value + ' ' + this.message;
		};
	}

	// An exception class to be instantiated when a value is Not of type object
	function ObjectTypeError(value){
		this.value = value;
		this.message = 'must be an object.';
		this.toString = function(){
			return this.value + ' ' + this.message;
		};
	}

	// An exception class to be instantiated when a provided index is out of bounds
	function IndexOutOfBoundsException(index){
		this.value = index;
		this.message = 'is out of bounds.';
		this.toString = function(){
			return this.value + ' ' + this.message;
		};
	}

	// Internal Hawk Object
  var cKm = {
  	DoesNotExistException: DoesNotExistException,
  	NumberTypeError: NumberTypeError,
  	ObjectTypeError: ObjectTypeError,
  	IndexOutOfBoundsException: IndexOutOfBoundsException,

  	classMap: {},
  	mixinMap: {},

  	proxy: function(fn, scope){
  		return function(){
  			args = Array.prototype.slice.call(arguments);
  			fn.apply(scope, args);
  		};
  	},

  	extend: function(destination, source){
  		for(var index in source){
  			if(source.hasOwnProperty(index)){
  				destination[index] = source[index];
  			}
  		}
  	},

    // Get a class definition object by name, @param {string}
  	getDef: function(className){
  		var def = this.classMap[className];

  		if(typeof def === 'object'){
				return def;
			}else{
				throw new DoesNotExistException(className);
			}
  	},

  	// Get multiple class definitions by name, @param {string[]}
  	getDefs: function(classNames){
  		var classDefs = [],
			len = classNames.length,
			className;

			for(var i = 0; i < len; i++){
				className = classNames[i];
				def = this.getDef(className);

				classDefs.push(def);
			}

			return classDefs;
  	},

  	// Get a mixin class definition
		getMixinDef: function(className){
			return this.mixinMap[className];
		},

		// Mix a class definition with the specified classes, @param {object}, @param {string[]}
		mix: function(classMixinDef, mixinNames){
			var constructor = function(){},
				mixinName,
				mixinDef,
				len;

			classMixinDef.sprout.call(constructor.prototype, classMixinDef.config);

			if(mixinNames){
				len = mixinNames.length;

				for(var i = 0; i < len; i++){
					mixinName = mixinNames[i];
					mixinDef = this.getMixinDef(mixinName);

					mixinDef.sprout.call(constructor.prototype, mixinDef.config);
				}
			}

			return constructor;
		},

		// Create a constructor that will apply an object of properties to this
		createMixinConstructor: function(){
			var me = this;
			return function(config){
				me.extend(this, config);
				return this;
			};
		},

		// Create a mixin definition and add it to the mixin map
		createMixin: function(className, config, initFn){
			var Sprout = this.createMixinConstructor();

			this.mixinMap[className] = {
				sprout: Sprout,
				initFn: initFn,
				config: config
			};

			return this.mixinMap[className];
		},

		// Get a queue of init functions from the provided mixin names
		getInitQueue: function(mixinNames){
			var initQueue = [],
				mixinDef,
				initFn,
				len;

			if(mixinNames){
				len = mixinNames.length;

				for(var i = 0; i < len; i++){
					mixinDef = this.getMixinDef(mixinNames[i]);
					initFn = mixinDef.initFn;

					if(initFn){
						initQueue.unshift(initFn);
					}
				}
			}

			return initQueue;
		},

		// Add a class definition to the class map
		addClassDef: function(className, sprout, initQueue){
			this.classMap[className] = {
				sprout: sprout,
				initQueue: initQueue
			};
		},

		// Execute an initialization queue
		executeInitQueue: function(inBloom, initQueue){
			var len = initQueue.length,
				i = len - 1;

			while(i >= 0){
				initFn = initQueue[i]; //we unshifted into the front of the queue, so we want to pop to get mixin's in the right order
				initFn.call(inBloom);

				--i;
			}
		},

		// Define a new class, providing a configuration object
		def: function(className, config){
			var initFn = config['init'],
				mixinNames = config['mixins'],
				classMixinDef,
				mixedConstructor,
				initQueue;

			delete config['init'];

			initQueue = this.getInitQueue(mixinNames); //build init queue based on mixins

			if(initFn){
				initQueue.unshift(initFn);
			}

			classMixinDef = this.createMixin(className, config, initFn); //create this class as a mixin definition
			mixedConstructor = this.mix(classMixinDef, mixinNames); //apply specified mixins to this class  mixin
			this.addClassDef(className, mixedConstructor, initQueue); //define the mixed constructor as a class definition
		},

		// Generate a class instance
		gen: function(className, overrideConfig){
			var classDef = this.getDef(className),
				sprout = classDef.sprout,
				initQueue = classDef.initQueue,
				inBloom; //result of Object.create, a mid level class instance, before initializations have been applied

			overrideConfig = overrideConfig || {};

			inBloom = new sprout();
			this.extend(inBloom, overrideConfig);
			this.executeInitQueue(inBloom, initQueue);

			return inBloom; //in bloom is now full bloom!
		}
  };

  return cKm;
})();
/**
*   Record class
*   Simple wrapper for data objects, intended to be the base objects for Cache
*/
Hawk.def('Record', {

  dirty: false,
  id: null,
  data: null,
  dataIndex: null,

  // Initialize the data
  init: function(){
    if(this.data === null){
      this.data = {};
    }
  },

  // Set the record id
  setId: function(id){
    if(typeof id === 'number'){
      this.id = id;
    }else{
      throw new Hawk.NumberTypeError(id);
    }
  },

  // Get the record id
  getId: function () {
    return this.id;
  },

  // Set the data
  setData: function(data){
    if(typeof data === 'object'){
      this.data = data; // allow null and array
    }else{
      throw new Hawk.ObjectTypeError(data);
    }
  },

  // Get the data
  getData: function () {
    return this.data;
  },

  // Set the data index
  setDataIndex: function (dataIndex) {
    if(typeof dataIndex === 'number'){
      this.dataIndex = dataIndex;
    }else{
      throw new Hawk.NumberTypeError(dataIndex);
    }
  },

  // Get the data index
  getDataIndex: function () {
    return this.dataIndex;
  },

  // Get a value at the given key
  get: function (key) {
    return this.data[key];
  },

  // Set the value at a given key
  set: function (key, value) {
    this.data[key] = value;
    this.dirty = true;
  },

  // Get the dirty boolean
  isDirty: function () {
    return this.dirty;
  }
});
/**
*   Data management layer, uses Record objects and an Array
*   Provides convenience methods for managing data sets
*
*   Recommended Use: Backing DOM lists and tables
*/
Hawk.def('Cache', {

  store: null,
  recCounter: 0,
  idCounter: 0,

  // initialize the store
	init: function(){
		this.store = [];
	},

  // Load an array of data objects into the cache
  load: function (dataArr) {
    var len = dataArr.length;

    for (var i = 0; i < len; i++) {
      this.add(dataArr[i]);
    }
  },

  // Get the size of the cache
  size: function(){
    return this.recCounter;
  },

  // Add an object of data to the cache
  add: function (data) {
    var record = Hawk.gen('Record', {
      id:this.idCounter,
      data:data
    });

    this.store.push(record);

    ++this.idCounter;
    ++this.recCounter;
  },

  // Remove a record from the cache
  remove: function (record) {
    var index = this.indexOf(record);

    if (index !== -1) {
      return this.removeAt(index);
    }else{
      return null;
    }
  },

  // Remove a record at a given index
  removeAt: function (index) {
    var record = this.getAt(index);

    if(record !== null){
      this.store.splice(index, 1);
      --this.recCounter;
    }

    return record;
  },

  // Remove all records from the cache
  removeAll: function () {
    this.recCounter = 0;
    this.idCounter = 0;

    return this.store.splice(0, this.store.length);
  },

  // Get the index of a given record
  indexOf: function (record) {
    var len = this.store.length,
      i = 0,
      found = false,
      comparison,
      index = -1;

    while (i < len && !found) {
      comparison = this.store[i];

      if (comparison.getId() === record.getId()) {
        index = i;
        found = true;
      }

      ++i;
    }

    return index;
  },

  // Get a record at a given index
  getAt: function (index) {
    if (index >= 0 && index < this.recCounter) {
      return this.store[index];
    } else {
      return null;
    }
  },

  // Get all records from the cache
  getRecords: function () {
    return this.store;
  },

  // Find and retrun a record by searching for the given key and value
  find: function (key, value) {
    var len = this.store.length,
      i = 0,
      found = false,
      rec = null;

    while (i < len && !found) {
      rec = this.store[i];

      if (rec.get(key) === value) {
        found = true;
      }

      ++i;
    }

    return rec;
  },

  // Get and return records which have changed and have been marked dirty
  getDirty: function () {
    var dirtyRecords = [],
      len = this.store.length,
      rec;

    for (var i = 0; i < len; i++) {
      rec = this.store[i];

      if (rec.isDirty()) {
        dirtyRecords.push(rec);
      }
    }

    return dirtyRecords;
  }
});
/**
*   Node object class used by LinkedList
*/
Hawk.def('Node', {

  id: null,
  data: null,
  next: null,
  prev: null,

  // Set the id
  setId: function (id) {
    if(typeof id === 'number'){
      this.id = id;
    }else{
      throw new Hawk.NumberTypeError(id);
    }
  },

  // Get the id
  getId: function () {
    return this.id;
  },

  // Set data
  setData: function (data) {
    this.data = data;
  },

  // Get data
  getData: function () {
    return this.data;
  }
});
/**
*   Linked List
*   [Doubly Linked](http://en.wikipedia.org/wiki/Doubly_linked_list)
*/
Hawk.def('LinkedList', {

  // Initialze the doubly linked list
  init: function () {
    this.start = Hawk.gen('Node',{
    	id:null,
    	data:null
    });

    this.end = Hawk.gen('Node',{
    	id:null,
    	data:null
    });

    this.start.next = this.end;
    this.start.prev = null;
    this.end.prev = this.start;
    this.end.next = null;

    this.idCounter = 0;
    this.numNodes = 0;
  },

  // Add to the end of the list
  add: function (data) {
    this.addLast(data);
  },

  // Add to the end of the list
  addLast: function (data) {
    var node = Hawk.gen('Node',{
      id: this.idCounter,
      data: data
    });

    last = this.end;

    this.insertBefore(last, node);

    ++this.idCounter;
    ++this.numNodes;
  },

  // Insert before a given node in the list
  insertBefore: function (toInsertBefore, node) {
    node.next = toInsertBefore;
    node.prev = toInsertBefore.prev;

    toInsertBefore.prev.next = node;
    toInsertBefore.prev = node;
  },

  // Get the first node in the list
  getFirst: function () {
    if (this.numNodes === 0) {
      return null;
    } else {
      return this.start.next;
    }
  },

  // Get the last node in the list
  getLast: function () {
    if (this.numNodes === 0) {
      return null;
    } else {
      return this.end.prev;
    }
  },

  // Finds and returns the node at the specified index, starting at the beginning of the list
  getFromFirst: function (index) {
    var count = 0,
      temp = this.start.next;

    if(index >= 0){
      while (count < index && temp !== null) {
        temp = temp.next;
        ++count;
      }
    }else{
      temp = null;
    }

    if(temp === null){
      throw new Hawk.IndexOutOfBoundsException(index);
    }

    return temp;
  },

  // Gets a node at the specific index
  getAt: function (index) {
    var count = 0,
      temp = null;

    if (index === 0) {
      temp = this.getFirst();
    } else if (index === this.numNodes - 1) {
      temp = this.getLast();
    } else {
      temp = this.getFromFirst(index);
    }

    return temp;
  },

  // Gets the size of the list
  size: function () {
    return this.numNodes;
  },

  // Remove and return a node from the list
  remove: function (node) {
    node.prev.next = node.next;
    node.next.prev = node.prev;

    --this.numNodes;

    return node;
  },

  // Remove the first node in the list
  removeFirst: function () {
    var temp = null;

    if (this.numNodes > 0) {
      temp = this.remove(this.start.next);
    }

    return temp;
  },

  // Remove the last node from the list
  removeLast: function () {
    var temp = null;

    if (this.numNodes > 0) {
      temp = this.remove(this.end.prev);
    }

    return temp;
  },

  // Remove all nodes from the list
  removeAll: function(){
    this.start.next = this.end;
    this.end.prev = this.start;
    this.numNodes = 0;
  }
});
/**
*   Observable event mixin
*/
Hawk.def('Observable', {

    // Initialize events and aliases
	init: function(){
		this.events = {};

    // Add an event listener
    this.on = this.addListener;
    // Remove an event listener
    this.off = this.removeListener;
    // Fires an event by name, with variable arguments
    this.fire = this.fireEvent;
	},

  // Add an event name
  addEvent: function (eventName) {
    this.events[eventName] = null;
  },

  // Add multiple event names
  addEvents: function (eventNames) {
    var len = eventNames.length;

    for (var i = 0; i < len; i++) {
      this.addEvent(eventNames[i]);
    }
  },

  // Add an event listener
  addListener: function (eventName, callback, scope) {
    var eventMapping = this.events[eventName],
	    proxy;

    if (eventMapping === null) {
      //this event mapping has been initialized
      proxy = Hawk.proxy(callback, scope);

      this.events[eventName] = proxy;
    }
  },

  // Remove an event listener
  removeListener: function (eventName) {
    var eventMapping = this.events[eventName];

    if (eventMapping !== null && eventMapping !== undefined) {
      this.events[eventName] = null;
    }
  },

  // Fire an event by name, with an arbitrary number of additional arguments to be passed
  // expects the first argument to be the event name.
  fireEvent: function () {
    var args = Array.prototype.slice.call(arguments),
    	eventName = args.shift(),
    	eventMapping = this.events[eventName];

    if (typeof eventMapping === 'function') {
      eventMapping.apply(this, args); //INVARIANT: the event mapping is a callback
    }
  }
});
/**
*   Publish and Subscribe Module
*   Allows for subscribing to and publishing global events
*   Will publish events in the order they are added as subscriptions
*
*/
Hawk.def('PubSub', {

  // Initialize subscriptions and aliases
  init: function(){
    this.subscriptions = {};

    // Subscribes to an event by name
    this.sub = this.registerSubscription;
    // Subscribes multiple event definitions
    this.subs = this.registerSubscriptions;
    // Publishes an event by name
    this.pub = this.publishEvent;
    // Registers an event mapping
    this.mapping = this.registerEventMappings;
  },

  // Registers an event subscription
  registerSubscription: function(eventName, callback, scope){
    var proxy = Hawk.proxy(callback, scope);

    if (!Array.isArray(this.subscriptions[eventName])) {
      this.subscriptions[eventName] = []; //INVARIANT: the event does not exist, create room it before pushing
    }

    this.subscriptions[eventName].push(proxy);
  },

  /**
  *   Parameter structure:
  *   events: [
  *       {
  *           eventName: '',
  *           callback: function(){}
  *       }
  *   ],
  *   scope: this
  */
  // Registers multiple event subscriptions
  registerSubscriptions: function (events, scope) {
    var len = events.length,
      evt, eventName, callback;

    for (var i = 0; i < len; i++) {
      evt = events[i];
      eventName = evt.eventName;
      callback = evt.callback;

      this.registerSubscription(eventName, callback, scope);
    }
  },

  // Publish an event with a variable number of arguments
  publishEvent: function () {
    var args = Array.prototype.slice.call(arguments),
      eventName = args.shift(),
      subArr = this.subscriptions[eventName],
      subCallback,
      len;

    if (Array.isArray(subArr)) {
      len = subArr.length;

      for (var i = 0; i < len; i++) {
        subCallback = subArr[i];
        subCallback.apply(this, args); //args must be an array, but may or may not be empty!
      }
    }
  },

  // Generate a callback to be used in publishing an event from an event mapping
  genPublishCallback: function (reactions) {
    return function () {
      var len = reactions.length,
        reaction,
        args;

      for (var j = 0; j < len; j++) {
        reaction = reactions[j];
        args = reaction.useArgs ? Array.prototype.slice.call(arguments) : [];
        //push the event name as the first param
        args.unshift(reaction.eventName);

        this.publishEvent.apply(this, args);
      }
    };
  },

  /*
  *   RegisterEventMappings takes a configuration object in the following form:
  *   [
  *       {
  *           eventName:"datachange",
  *           reactions:[
  *               { eventName:"validateRecord", useArgs:true },
  *               { eventName:"postRecord",   useArgs:true }
  *           ]
  *       }
  *   ]
  */
  // Register an event mapping, typically specified as a .json config file
  registerEventMappings: function (maps) {
    var len = maps.length,
      events = [],
      eventName,
      reactions,
      reactionLen;

    for (var i = 0; i < len; i++) {
      eventName = maps[i].eventName;
      reactions = maps[i].reactions;

      events.push({
        eventName: eventName,
        callback: this.genPublishCallback(reactions)
      });
    }

    this.registerSubscriptions(events, this);
  }
});


text:
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Microsoft.Extensions.DependencyModel
{
    public class DependencyContext
    {
#if !NETSTANDARD1_3
        private static readonly Lazy<DependencyContext> _defaultContext = new Lazy<DependencyContext>(LoadDefault);
#endif

        public DependencyContext(TargetInfo target,
            CompilationOptions compilationOptions,
            IEnumerable<CompilationLibrary> compileLibraries,
            IEnumerable<RuntimeLibrary> runtimeLibraries,
            IEnumerable<RuntimeFallbacks> runtimeGraph)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (compilationOptions == null)
            {
                throw new ArgumentNullException(nameof(compilationOptions));
            }
            if (compileLibraries == null)
            {
                throw new ArgumentNullException(nameof(compileLibraries));
            }
            if (runtimeLibraries == null)
            {
                throw new ArgumentNullException(nameof(runtimeLibraries));
            }
            if (runtimeGraph == null)
            {
                throw new ArgumentNullException(nameof(runtimeGraph));
            }

            Target = target;
            CompilationOptions = compilationOptions;
            CompileLibraries = compileLibraries.ToArray();
            RuntimeLibraries = runtimeLibraries.ToArray();
            RuntimeGraph = runtimeGraph.ToArray();
        }

#if !NETSTANDARD1_3
        public static DependencyContext Default => _defaultContext.Value;
#endif

        public TargetInfo Target { get; }

        public CompilationOptions CompilationOptions { get; }

        public IReadOnlyList<CompilationLibrary> CompileLibraries { get; }

        public IReadOnlyList<RuntimeLibrary> RuntimeLibraries { get; }

        public IReadOnlyList<RuntimeFallbacks> RuntimeGraph { get; }

        public DependencyContext Merge(DependencyContext other)
        {
            if (other == null)
            {
                throw new ArgumentNullException(nameof(other));
            }

            return new DependencyContext(
                Target,
                CompilationOptions,
                CompileLibraries.Union(other.CompileLibraries, new LibraryMergeEqualityComparer<CompilationLibrary>()),
                RuntimeLibraries.Union(other.RuntimeLibraries, new LibraryMergeEqualityComparer<RuntimeLibrary>()),
                RuntimeGraph.Union(other.RuntimeGraph)
                );
        }

#if !NETSTANDARD1_3
        private static DependencyContext LoadDefault()
        {
            return DependencyContextLoader.Default.Load(Assembly.GetEntryAssembly());
        }

        public static DependencyContext Load(Assembly assembly)
        {
            return DependencyContextLoader.Default.Load(assembly);
        }
#endif

        private class LibraryMergeEqualityComparer<T> : IEqualityComparer<T> where T : Library
        {
            public bool Equals(T x, T y)
            {
                return StringComparer.OrdinalIgnoreCase.Equals(x.Name, y.Name);
            }

            public int GetHashCode(T obj)
            {
                return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Name);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.motechproject.couch.mrs.model;

import org.joda.time.DateTime;

public class Initializer {

    public CouchPerson initializePerson1() {
        CouchPerson person1 = new CouchPerson();
        person1.setDateOfBirth(new DateTime(2011, 12, 12, 0, 0));
        person1.setGender("female");
        person1.setPersonId("12345");
        person1.setFirstName("FirstName");
        person1.setLastName("LastName");
        person1.addAttribute(new CouchAttribute("phone number", "1234567890"));
        person1.setAddress("SomeAddress");
        return person1;
    }

    public CouchPerson initializeSecondPerson() {
        CouchPerson person2 = new CouchPerson();
        person2.setAddress("AnAddress");
        person2.setDateOfBirth(new DateTime(2011, 12, 12, 0, 0));
        person2.setGender("female");
        person2.setPersonId("externalId");
        person2.setFirstName("AName");
        person2.setLastName("ALastName");
        return person2;
    }

    public CouchPerson initializeThirdPerson() {
        CouchPerson person2 = new CouchPerson();
        person2.setAddress("New address");
        person2.setDateOfBirth(new DateTime(2011, 12, 12, 0, 0));
        person2.setGender("female");
        person2.setPersonId("54322");
        person2.setFirstName("FirstName");
        person2.setLastName("LastName");
        person2.addAttribute(new CouchAttribute("parity", "G4P3"));
        return person2;
    }

    public CouchPerson initializePerson3WithOnlyExternalIdAndPhone() {
        CouchPerson person3 = new CouchPerson();
        person3.addAttribute(new CouchAttribute("phone number", "1234567890"));
        person3.setPersonId("00000");
        return person3;
    }
}


text:
//
//  SBPhotoViewController.m
//  ImageSlider
//
//  Created by Soumalya Banerjee on 16/12/15.
//  Copyright © 2015 Soumalya Banerjee. All rights reserved.
//

#import "SBPhotoViewController.h"

static const CGFloat kMinBlackMaskAlpha = 0.1f;

@interface SBPhotoViewController () {
    UIImageView *mainImageView;
    CGRect _finalRect;
}

@end

@implementation SBPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [self setupBackGround];
    [self setUpImageViewer];
}

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

- (void)setupBackGround {

    _backGroundImageView.image = _backGroundImage;
    _backGroundImageView.contentMode = UIViewContentModeScaleAspectFill;
    _backGroundImageView.clipsToBounds = YES;
}

- (void)setUpImageViewer {

    mainImageView = [[UIImageView alloc] initWithFrame:_initialRect];
    mainImageView.contentMode = UIViewContentModeScaleAspectFill;
    mainImageView.image = _targetImage;
    mainImageView.clipsToBounds = YES;
    [self.view addSubview:mainImageView];

    __block CGRect mainImageViewFrame = [self getFullSizeFrameWithView:mainImageView];
    __block CGFloat targetY = ((mainImageView.superview.frame.size.height - mainImageViewFrame.size.height) / 2.0f);

    [UIView animateWithDuration:0.5f animations:^(void){

        _maskView.alpha = 1.0f;
        mainImageViewFrame.origin.x = 0.0f;
        mainImageViewFrame.origin.y = targetY;
        mainImageView.frame = mainImageViewFrame;

    } completion:^(BOOL finished){
        [self setupGesture];
        _finalRect = mainImageViewFrame;
    }];
}

- (CGRect)getFullSizeFrameWithView:(UIImageView *)targetImageView {

    UIImage *tempImage = targetImageView.image;
    CGSize imageFrame = tempImage.size;

    CGRect finalFullFrame = targetImageView.frame;

    if (imageFrame.width > imageFrame.height) {

        finalFullFrame.size.width = [UIScreen mainScreen].bounds.size.width;
        CGFloat multiplier = imageFrame.width / imageFrame.height;
        finalFullFrame.size.height = finalFullFrame.size.width / multiplier;

    } else if (imageFrame.height > imageFrame.width) {

        finalFullFrame.size.height = [UIScreen mainScreen].bounds.size.width;
        CGFloat multiplier = imageFrame.width / imageFrame.height;
        finalFullFrame.size.height = finalFullFrame.size.width / multiplier;

    } else {

        finalFullFrame.size.height = [UIScreen mainScreen].bounds.size.width;
        finalFullFrame.size.height = [UIScreen mainScreen].bounds.size.width;
    }

    return finalFullFrame;
}

- (void)setupGesture {

    mainImageView.userInteractionEnabled = YES;
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewDidPan:)];
    panGesture.minimumNumberOfTouches = 1;
    panGesture.maximumNumberOfTouches = 1;

    [mainImageView addGestureRecognizer:panGesture];
}

- (void)imageViewDidPan:(UIPanGestureRecognizer *)recognizer {

    CGPoint translation = [recognizer translationInView:self.view];
    CGRect recognizerFrame = recognizer.view.frame;
    recognizerFrame.origin.x += translation.x;
    recognizerFrame.origin.y += translation.y;

    CGFloat displacement = fabs((recognizerFrame.origin.y + mainImageView.frame.size.height/2) - [UIScreen mainScreen].bounds.size.height/2);

    _maskView.alpha = MAX(1 - displacement/([UIScreen mainScreen].bounds.size.height/0.9),kMinBlackMaskAlpha);

    recognizer.view.frame = recognizerFrame;

    if ([recognizer state] == UIGestureRecognizerStateEnded) {
        [self animationDidFinish:recognizerFrame.origin];
    }

    // Reset translation so that on next pan recognition
    // we get correct translation value
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}

- (void)animationDidFinish:(CGPoint)endRect {

    CGFloat displacement = _finalRect.origin.y - endRect.y;

    if (displacement < 0) {
        displacement = -(displacement);
    }

    if (displacement <= 60.0f) {

        [UIView animateWithDuration:0.3f animations:^(void){

            mainImageView.frame = _finalRect;
            _maskView.alpha = 1.0f;

        } completion:nil];

    } else {
        [UIView animateWithDuration:0.3f animations:^(void){

            mainImageView.frame = _initialRect;

        } completion:^(BOOL finished){
            [self.navigationController popViewControllerAnimated:NO];
        }];
    }

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
'use strict';

angular.module('rhmf-admin',['ngRoute','ngResource'])
  .config(['$routeProvider', function($routeProvider) {
    $routeProvider
      .when('/',{templateUrl:'views/landing.html',controller:'LandingPageController'})
      .when('/Devices',{templateUrl:'views/Device/search.html',controller:'SearchDeviceController'})
      .when('/Devices/new',{templateUrl:'views/Device/detail.html',controller:'NewDeviceController'})
      .when('/Devices/edit/:DeviceId',{templateUrl:'views/Device/detail.html',controller:'EditDeviceController'})
      .when('/Polls',{templateUrl:'views/Poll/search.html',controller:'SearchPollController'})
      .when('/Polls/new',{templateUrl:'views/Poll/detail.html',controller:'NewPollController'})
      .when('/Polls/edit/:PollId',{templateUrl:'views/Poll/detail.html',controller:'EditPollController'})
      .when('/Votes',{templateUrl:'views/Vote/search.html',controller:'SearchVoteController'})
      .when('/Votes/new',{templateUrl:'views/Vote/detail.html',controller:'NewVoteController'})
      .when('/Votes/edit/:VoteId',{templateUrl:'views/Vote/detail.html',controller:'EditVoteController'})
      .otherwise({
        redirectTo: '/'
      });
  }])
  .controller('LandingPageController', function LandingPageController() {
  })
  .controller('NavController', function NavController($scope, $location) {
    $scope.matchesRoute = function(route) {
        var path = $location.path();
        return (path === ("/" + route) || path.indexOf("/" + route + "/") == 0);
    };
  });


text:
(function () {
  'use strict';

  angular
    .module('queues')
    .factory('QueuesService', QueuesService);

  QueuesService.$inject = ['$resource'];

  function QueuesService($resource) {
    return $resource('api/queues/:queueId', {
      queueId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
})();


text:
html,body {
  background-color: white;
  overflow:hidden;
  padding:0;
  margin:0;
}
div {
  border: solid 2px #eee;
  padding: 20px;
  text-align:center;
  background-color: black;
  color: #88F;
}
div.button {
  float: left;
  background-color: red;
  color: yellow;
}
.left,.right {
  -webkit-transition:all ease-in-out 0.3s;
}
.ng-click-active {
  background-color: #0E0;
}


text:
using Neo.Network.P2P.Payloads;
using Neo.Network.RPC.Models;
using Neo.SmartContract;
using Neo.VM;
using Neo.Wallets;
using System.Linq;
using System.Numerics;

namespace Neo.Network.RPC
{
    /// <summary>
    /// Call NEP5 methods with RPC API
    /// </summary>
    public class Nep5API : ContractClient
    {
        /// <summary>
        /// Nep5API Constructor
        /// </summary>
        /// <param name="rpcClient">the RPC client to call NEO RPC methods</param>
        public Nep5API(RpcClient rpcClient) : base(rpcClient) { }

        /// <summary>
        /// Get balance of NEP5 token
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <param name="account">account script hash</param>
        /// <returns></returns>
        public BigInteger BalanceOf(UInt160 scriptHash, UInt160 account)
        {
            BigInteger balance = TestInvoke(scriptHash, "balanceOf", account).Stack.Single().ToStackItem().GetBigInteger();
            return balance;
        }

        /// <summary>
        /// Get name of NEP5 token
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <returns></returns>
        public string Name(UInt160 scriptHash)
        {
            return TestInvoke(scriptHash, "name").Stack.Single().ToStackItem().GetString();
        }

        /// <summary>
        /// Get symbol of NEP5 token
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <returns></returns>
        public string Symbol(UInt160 scriptHash)
        {
            return TestInvoke(scriptHash, "symbol").Stack.Single().ToStackItem().GetString();
        }

        /// <summary>
        /// Get decimals of NEP5 token
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <returns></returns>
        public uint Decimals(UInt160 scriptHash)
        {
            return (uint)TestInvoke(scriptHash, "decimals").Stack.Single().ToStackItem().GetBigInteger();
        }

        /// <summary>
        /// Get total supply of NEP5 token
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <returns></returns>
        public BigInteger TotalSupply(UInt160 scriptHash)
        {
            return TestInvoke(scriptHash, "totalSupply").Stack.Single().ToStackItem().GetBigInteger();
        }

        /// <summary>
        /// Get token information in one rpc call
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <returns></returns>
        public RpcNep5TokenInfo GetTokenInfo(UInt160 scriptHash)
        {
            byte[] script = scriptHash.MakeScript("name")
                .Concat(scriptHash.MakeScript("symbol"))
                .Concat(scriptHash.MakeScript("decimals"))
                .Concat(scriptHash.MakeScript("totalSupply"))
                .ToArray();

            var result = rpcClient.InvokeScript(script).Stack;

            return new RpcNep5TokenInfo
            {
                Name = result[0].ToStackItem().GetString(),
                Symbol = result[1].ToStackItem().GetString(),
                Decimals = (uint)result[2].ToStackItem().GetBigInteger(),
                TotalSupply = result[3].ToStackItem().GetBigInteger()
            };
        }

        /// <summary>
        /// Create NEP5 token transfer transaction
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <param name="fromKey">from KeyPair</param>
        /// <param name="to">to account script hash</param>
        /// <param name="amount">transfer amount</param>
        /// <param name="networkFee">netwotk fee, set to be 0 will auto calculate the least fee</param>
        /// <returns></returns>
        public Transaction CreateTransferTx(UInt160 scriptHash, KeyPair fromKey, UInt160 to, BigInteger amount, long networkFee = 0)
        {
            var sender = Contract.CreateSignatureRedeemScript(fromKey.PublicKey).ToScriptHash();
            Cosigner[] cosigners = new[] { new Cosigner { Scopes = WitnessScope.CalledByEntry, Account = sender } };

            byte[] script = scriptHash.MakeScript("transfer", sender, to, amount);
            Transaction tx = new TransactionManager(rpcClient, sender)
                .MakeTransaction(script, null, cosigners, networkFee)
                .AddSignature(fromKey)
                .Sign()
                .Tx;

            return tx;
        }
    }
}


text:
	<form class="columns" ng-submit="save(true)">

			<switch name="torEnabled" ng-model="torEnabled" class="green right"></switch>

TOR enabled

		Host
		<input type="text" id="host" name="host" ng-model="socksHost" placeholder="127.0.0.1">
		Port

{{errorPortInput}}

		<input type="text" id="port" name="port" ng-model="socksPort" placeholder="9150">
		<input type="submit" class="button expand black round" value="{{'Save'|translate}}"
			   ng-style="{'background-color':index.backgroundColor}">
	</form>

		WARNINGS:

You need to have Tor service or Tor Browser running to use this feature!


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Menu</title>
  <link rel="stylesheet" href="css/base.css">
  <link rel="stylesheet" href="css/menu.css">

    Toggle Menu

Link 1

Link 2

Link 3

Link 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt voluptate dolor ipsam, earum. Asperiores qui consequatur possimus in perferendis, accusamus necessitatibus repellendus vero quos, officiis, ut. Dolorum omnis fuga perspiciatis possimus, ex vero, non voluptatum, dolorem enim debitis minus est.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est doloremque aut reprehenderit accusantium ipsam! Odit pariatur rerum eaque velit laborum saepe molestiae odio sunt alias, nesciunt porro sed culpa earum dolor laudantium quae repellat provident assumenda doloribus dolores veniam facere!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt eveniet magnam dolor, omnis at, voluptatum, facere fuga sit minus quaerat fugiat! Mollitia consequatur accusantium debitis dolor. Fuga repudiandae impedit quibusdam maxime harum tempora, officiis error non recusandae nesciunt earum ipsam.


text:
import os
import unittest

from goose import core
from goose import models

dbFile = ":memory:"
dbUrl = "sqlite:///%s"%(dbFile,)

class TestMigration(unittest.TestCase):
    def setUp(self):
        self.indexFilepath = os.path.join(core.ROOT, "testmigrations",
                                          "index.yaml")
        self.migrator = core.DatabaseMigrator(self.indexFilepath)
        self.migrator.connect(dbUrl)
        models.init()

    def tearDown(self):
        pass

    def test_connectCreateDbIfNecessary(self):
        self.migrator.connect(dbUrl)

    def test_getVersionWithoutVersionInfo(self):
        self.migrator.connect(dbUrl)
        self.assertRaises(ValueError, self.migrator.getVersion)

    def test_installMigrationInfoVersionNumberWithNoMigrations(self):
        self.assertEquals(self.migrator.getVersion(), None)

    def test_createAndMigrate(self):
        # we migrate only to version 2 because the test migrations
        # after that are supposed to fail.
        migrationsApplied = self.migrator.migrate(toVersion=2)
        self.assertEqual(migrationsApplied, ["create.sql",
                                             "track.sql"])
        self.assertEqual(self.migrator.getVersion(), 2)
        cursor = self.migrator.session
        cursor.execute("SELECT * FROM test1;")
        cursor.execute("SELECT * FROM Track;")
        migrationsApplied = self.migrator.migrate(toVersion=2)
        self.assertEqual(migrationsApplied, [])
        self.assertEqual(self.migrator.getVersion(), 2)

    def test_migrationFailure(self):
        # here we attempt to migration all the way but our 3rd test
        # migration contains and error so we'll only get to the first 2.
        self.assertRaises(models.OperationalError, self.migrator.migrate)
        self.assertEqual(self.migrator.getVersion(), 2)
        migrations = self.migrator.migrationsApplied()
        for migration in migrations:
            print migration

        migrationsApplied = self.migrator.migrate(toVersion=2)
        self.assertEqual(migrationsApplied, [])
        self.assertEqual(self.migrator.getVersion(), 2)

class TestMigrateSubcommandFunction(unittest.TestCase):
    def setUp(self):
        migrationDir = os.path.join(core.ROOT, "testmigrations")
        self.migrator = core.migrate(migrationDir, dbUrl, toVersion=2, init=True)

    def test_migrations(self):
        self.assertEquals(self.migrator.migrations,
                          ["create.sql",
                           "track.sql",
                           "bad.sql",
                           "good.sql"])

class TestListSubcommandFunction(unittest.TestCase):
    def test_listMigrations(self):
        migrationDir = os.path.join(core.ROOT, "testmigrations")
        core.listMigrations(migrationDir, dbUrl, init=True)

class TestInitializeSubcommandFunction(unittest.TestCase):
    def test(self):
        models.connect(dbUrl)
        models.init()

class TestMain(unittest.TestCase):
    def setUp(self):
        self.migrationDir = os.path.join(core.ROOT, "testmigrations")

    def test_init(self):
        args = ["-m", self.migrationDir, "-d", dbUrl, "init"]
        options = core.main(args)
        self.assertEquals(options.subCommand, "init")

    def test_list(self):
        args = ["-m", self.migrationDir, "-d", dbUrl, "list"]
        options = core.main(args, init=True)
        self.assertEquals(options.subCommand, "list")

    def test_migrate(self):
        args = ["-m", self.migrationDir, "-d", dbUrl, "migrate",
                "-t", "2"]
        options = core.main(args, init=True)
        self.assertEquals(options.subCommand, "migrate")


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

namespace FluentBootstrap.MediaObjects
{
    public class Media : Tag,
        ICanCreate<MediaObject>,
        ICanCreate<MediaBody>
    {
        internal Media(BootstrapHelper helper)
            : base(helper, "div", Css.Media)
        {
        }

        protected override void OnStart(TextWriter writer)
        {
            // Change to a list item if inside a MediaList
            if(GetComponent<MediaList>(true) != null)
            {
                TagName = "li";
            }

            base.OnStart(writer);
        }
    }
}


text:
package com.alipay.api.response;

import com.alipay.api.internal.mapping.ApiField;

import com.alipay.api.AlipayResponse;

/**
 * ALIPAY API: alipay.ecapiprod.drawndn.contract.get response.
 *
 * @author auto create
 * @since 1.0, 2016-03-29 11:34:32
 */
public class AlipayEcapiprodDrawndnContractGetResponse extends AlipayResponse {

	private static final long serialVersionUID = 3194165267827478614L;

	/**
	 * 合同的内容文本	String	合同的内容文本,为HTML格式
	 */
	@ApiField("contract_content")
	private String contractContent;

	/**
	 * 合同编号
	 */
	@ApiField("contract_no")
	private String contractNo;

	/**
	 * 唯一标识这次请求
	 */
	@ApiField("request_id")
	private String requestId;

	public void setContractContent(String contractContent) {
		this.contractContent = contractContent;
	}
	public String getContractContent( ) {
		return this.contractContent;
	}

	public void setContractNo(String contractNo) {
		this.contractNo = contractNo;
	}
	public String getContractNo( ) {
		return this.contractNo;
	}

	public void setRequestId(String requestId) {
		this.requestId = requestId;
	}
	public String getRequestId( ) {
		return this.requestId;
	}

}


text:
The Generators
==============

These are just generator functions to be used to find files.

Find
----

The find-generator finds all file names that match a file glob and yields them one at a time.

Concatenate
-----------

The Concatenate Generator finds all the files that match a glob and yields all their lines.


text:
package com.cadyyan.lockAndKey.api.item;

public interface ILock
{
}


text:
package aima.core.search.local;

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

import aima.core.agent.Action;
import aima.core.search.framework.HeuristicFunction;
import aima.core.search.framework.Node;
import aima.core.search.framework.NodeExpander;
import aima.core.search.framework.Problem;
import aima.core.search.framework.Search;
import aima.core.search.framework.SearchUtils;
import aima.core.util.CancelableThread;

/**
 * Artificial Intelligence A Modern Approach (3rd Edition): Figure 4.2, page
 * 122.

 *

 *
 *

 * function HILL-CLIMBING(problem) returns a state that is a local maximum
 *
 *   current <- MAKE-NODE(problem.INITIAL-STATE)
 *   loop do
 *     neighbor <- a highest-valued successor of current
 *     if neighbor.VALUE <= current.VALUE then return current.STATE
 *     current <- neighbor
 *

 *
 * Figure 4.2 The hill-climbing search algorithm, which is the most basic local
 * search technique. At each step the current node is replaced by the best
 * neighbor; in this version, that means the neighbor with the highest VALUE,
 * but if a heuristic cost estimate h is used, we would find the neighbor with
 * the lowest h.
 *
 * @author Ravi Mohan
 * @author Mike Stampone
 */
public class HillClimbingSearch extends NodeExpander implements Search {

	public enum SearchOutcome {
		FAILURE, SOLUTION_FOUND
	};

	private HeuristicFunction hf = null;

	private SearchOutcome outcome = SearchOutcome.FAILURE;

	private Object lastState = null;

	/**
	 * Constructs a hill-climbing search from the specified heuristic function.
	 *
	 * @param hf
	 *            a heuristic function
	 */
	public HillClimbingSearch(HeuristicFunction hf) {
		this.hf = hf;
	}

	/**
	 * Returns a list of actions to the local maximum if the local maximum was
	 * found, a list containing a single NoOp Action if already at the local
	 * maximum, or an empty list if the search was canceled by the user.
	 *
	 * @param p
	 *            the search problem
	 *
	 * @return a list of actions to the local maximum if the local maximum was
	 *         found, a list containing a single NoOp Action if already at the
	 *         local maximum, or an empty list if the search was canceled by the
	 *         user.
	 */
	// function HILL-CLIMBING(problem) returns a state that is a local maximum
	public List<Action> search(Problem p) throws Exception {
		clearInstrumentation();
		outcome = SearchOutcome.FAILURE;
		lastState = null;
		// current <- MAKE-NODE(problem.INITIAL-STATE)
		Node current = new Node(p.getInitialState());
		Node neighbor = null;
		// loop do
		while (!CancelableThread.currIsCanceled()) {
			List<Node> children = expandNode(current, p);
			// neighbor <- a highest-valued successor of current
			neighbor = getHighestValuedNodeFrom(children, p);

			// if neighbor.VALUE <= current.VALUE then return current.STATE
			if ((neighbor == null) || (getValue(neighbor) <= getValue(current))) {
				if (SearchUtils.isGoalState(p, current)) {
					outcome = SearchOutcome.SOLUTION_FOUND;
				}
				lastState = current.getState();
				return SearchUtils.actionsFromNodes(current.getPathFromRoot());
			}
			// current <- neighbor
			current = neighbor;
		}
		return new ArrayList<Action>();
	}

	/**
	 * Returns SOLUTION_FOUND if the local maximum is a goal state, or FAILURE
	 * if the local maximum is not a goal state.
	 *
	 * @return SOLUTION_FOUND if the local maximum is a goal state, or FAILURE
	 *         if the local maximum is not a goal state.
	 */
	public SearchOutcome getOutcome() {
		return outcome;
	}

	/**
	 * Returns the last state from which the hill climbing search found the
	 * local maximum.
	 *
	 * @return the last state from which the hill climbing search found the
	 *         local maximum.
	 */
	public Object getLastSearchState() {
		return lastState;
	}

	//
	// PRIVATE METHODS
	//

	private Node getHighestValuedNodeFrom(List<Node> children, Problem p) {
		double highestValue = Double.NEGATIVE_INFINITY;
		Node nodeWithHighestValue = null;
		for (int i = 0; i < children.size(); i++) {
			Node child = (Node) children.get(i);
			double value = getValue(child);
			if (value > highestValue) {
				highestValue = value;
				nodeWithHighestValue = child;
			}
		}
		return nodeWithHighestValue;
	}

	private double getValue(Node n) {
		// assumption greater heuristic value =>
		// HIGHER on hill; 0 == goal state;
		return -1 * hf.h(n.getState());
	}
}


text:
@interface LocationViewController (UtilityMethods) <UIScrollViewDelegate>
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center;

@end

@implementation LocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.scrollView.bouncesZoom = YES;
    self.scrollView.delegate = self;
    self.scrollView.clipsToBounds = YES;
    self.image = [UIImage imageNamed:@"terrein.jpg"];
    if(self.image)
    {
        [self.imageView setImage:self.image];
    }
    self.imageView.userInteractionEnabled = YES;
    [self.imageView setContentMode:UIViewContentModeScaleAspectFit];
    self.imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth );
    [self.scrollView addSubview:self.imageView];

    self.scrollView.contentSize = [self.imageView frame].size;

    // add gesture recognizers to the image view
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    UITapGestureRecognizer *twoFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerTap:)];

    [doubleTap setNumberOfTapsRequired:2];
    [twoFingerTap setNumberOfTouchesRequired:2];

    [self.imageView addGestureRecognizer:singleTap];
    [self.imageView addGestureRecognizer:doubleTap];
    [self.imageView addGestureRecognizer:twoFingerTap];

    // calculate minimum scale to perfectly fit image width, and begin at that scale
    float minimumScale = [self.scrollView frame].size.width  / [self.imageView frame].size.width;
    self.scrollView.maximumZoomScale = 8.0;
    self.scrollView.minimumZoomScale = minimumScale;
    self.scrollView.zoomScale = minimumScale;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return YES;
}

- (void)didReceiveMemoryWarning {
  	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

  	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [self setScrollView:nil];
    self.self.scrollView = nil;
    self.imageView = nil;
}

#pragma mark UIScrollViewDelegate methods

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}

#pragma mark TapDetectingImageViewDelegate methods

- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer {
    // single tap does nothing for now
}

- (void)handleDoubleTap:(UIGestureRecognizer *)gestureRecognizer {
    // zoom in
    float newScale = [self.scrollView zoomScale] * ZOOM_STEP;
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
    [self.scrollView zoomToRect:zoomRect animated:YES];
}

- (void)handleTwoFingerTap:(UIGestureRecognizer *)gestureRecognizer {
    // two-finger tap zooms out
    float newScale = [self.scrollView zoomScale] / ZOOM_STEP;
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
    [self.scrollView zoomToRect:zoomRect animated:YES];
}

#pragma mark Utility methods

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center {

    CGRect zoomRect;

    // the zoom rect is in the content view's coordinates.
    //    At a zoom scale of 1.0, it would be the size of the self.scrollView's bounds.
    //    As the zoom scale decreases, so more content is visible, the size of the rect grows.
    zoomRect.size.height = [self.scrollView frame].size.height / scale;
    zoomRect.size.width  = [self.scrollView frame].size.width  / scale;

    // choose an origin so as to get the right center.
    zoomRect.origin.x    = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y    = center.y - (zoomRect.size.height / 2.0);

    return zoomRect;
}

@end


text:
SYNONYM

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

#### Published in
Bull. trimest. Soc. mycol. Fr. 41: 108 (1925)

#### Original name
Polyporus coronatus Rostk., 1848

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example.twirl</groupId>
  <artifactId>test</artifactId>
  <version>1.0.0-SNAPSHOT</version>

  <build>
    <plugins>
      <plugin>
        <groupId>com.jakewharton.twirl</groupId>
        <artifactId>twirl-maven-plugin</artifactId>
        <configuration>
          <includes>
            <include>bar/**</include>
          </includes>
          <excludes>
            <exclude>bar/foo/**</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
'use strict'

const assert = require('assert')
const path = require('path')
const {closeWindow} = require('./window-helpers')

const {remote} = require('electron')
const {BrowserWindow, webContents} = remote

const isCi = remote.getGlobal('isCi')

describe('webContents module', function () {
  const fixtures = path.resolve(__dirname, 'fixtures')
  let w

  beforeEach(function () {
    w = new BrowserWindow({
      show: false,
      width: 400,
      height: 400,
      webPreferences: {
        backgroundThrottling: false
      }
    })
  })

  afterEach(function () {
    return closeWindow(w).then(function () { w = null })
  })

  describe('getAllWebContents() API', function () {
    it('returns an array of web contents', function (done) {
      w.webContents.on('devtools-opened', function () {
        const all = webContents.getAllWebContents().sort(function (a, b) {
          return a.getId() - b.getId()
        })

        assert.equal(all.length, 4)
        assert.equal(all[0].getType(), 'window')
        assert.equal(all[1].getType(), 'window')
        assert.equal(all[2].getType(), 'remote')
        assert.equal(all[3].getType(), 'webview')

        done()
      })

      w.loadURL('file://' + path.join(fixtures, 'pages', 'webview-zoom-factor.html'))
      w.webContents.openDevTools()
    })
  })

  describe('getFocusedWebContents() API', function () {
    if (isCi) {
      return
    }

    it('returns the focused web contents', function (done) {
      const specWebContents = remote.getCurrentWebContents()
      assert.equal(specWebContents.getId(), webContents.getFocusedWebContents().getId())

      specWebContents.once('devtools-opened', function () {
        assert.equal(specWebContents.devToolsWebContents.getId(), webContents.getFocusedWebContents().getId())
        specWebContents.closeDevTools()
      })

      specWebContents.once('devtools-closed', function () {
        assert.equal(specWebContents.getId(), webContents.getFocusedWebContents().getId())
        done()
      })

      specWebContents.openDevTools()
    })
  })
})


text:
require 'spec_helper'

describe file('/home/re-ops/.vimrc') do
    it { should contain 'pathogen' }
    it { should be_file }
    it { should be_linked_to '/home/re-ops/.vim/.vimrc' }
end


text:
<?php

namespace Fungku\HubSpot\Api;

class Email extends Api
{
    /**
     * Get email subscription types for a portal.
     *
     * @param int $portal_id
     * @return \Fungku\HubSpot\Http\Response
     */
    public function subscriptions($portal_id)
    {
        $endpoint = "/email/public/v1/subscriptions";

        $queryString = $this->buildQueryString(['portalId' => $portal_id]);

        return $this->request('get', $endpoint, [], $queryString);
    }

    /**
     * View subscriptions timeline for a portal.
     *
     * @param array $params Optional parameters
     * @return \Fungku\HubSpot\Http\Response
     */
    public function subscriptionsTimeline($params = [])
    {
        $endpoint = "/email/public/v1/subscriptions/timeline";

        $queryString = $this->buildQueryString($params);

        return $this->request('get', $endpoint, [], $queryString);
    }

    /**
     * Get email subscription status for an email address.
     *
     * @param int    $portal_id
     * @param string $email
     * @return \Fungku\HubSpot\Http\Response
     */
    public function subscriptionStatus($portal_id, $email)
    {
        $endpoint = "/email/public/v1/subscriptions/{$email}";

        $queryString = $this->buildQueryString(['portalId' => $portal_id]);

        return $this->request('get', $endpoint, [], $queryString);
    }

    /**
     * Update email subscription status for an email address.
     *
     * @param int    $portal_id
     * @param string $email
     * @param array  $params
     * @return \Fungku\HubSpot\Http\Response
     */
    public function updateSubscription($portal_id, $email, $params = [])
    {
        $endpoint = "/email/public/v1/subscriptions/{$email}";

        $queryString = $this->buildQueryString(['portalId' => $portal_id]);
        $options['json'] = $params;

        return $this->request('put', $endpoint, $options, $queryString);
    }

}


text:
package com.siteworx.cq5.ooyala.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;

import com.siteworx.cq5.ooyala.service.OoyalaService;

@Component(immediate = true, metatype = false, description = "Ooyala Uploader Proxy Servlet")
@Service
@Properties({ @Property(name = "sling.servlet.paths", value = "/bin/ooyala/upload/assets") })
public class UploadProxyServlet extends SlingAllMethodsServlet {

	private static final long serialVersionUID = -3738183473154158783L;

	private final Pattern assetIdPattern = Pattern.compile("^(.*?assets/)(.*?)/(.*)$");

	private static final String UPLOAD_STATUS_ACTION = "upload_status";

	@Reference
	private OoyalaService ooyalaService;

	protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
		final String requestURI = request.getRequestURI();
		final String requestAction = getActionFromPath(requestURI);

		try {
			JSONObject requestJson;
			final StringBuilder stringBuilder = new StringBuilder();
			final InputStream inputStream = request.getInputStream();
			if (inputStream != null) {
				final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				final char[] charBuffer = new char[128];
				int bytesRead = -1;
				while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
					stringBuilder.append(charBuffer, 0, bytesRead);
				}
			} else {
				stringBuilder.append("");
			}
			requestJson = new JSONObject(stringBuilder.toString());

			if (requestAction != null && UPLOAD_STATUS_ACTION.equals(requestAction)) {
				final String assetId = getAssetIdFromPath(requestURI);
				final String uploadStatusResponse = ooyalaService.setUploadStatus(requestJson, assetId, requestAction);
				if (uploadStatusResponse != null && !"".equals(uploadStatusResponse)) {
					response.setStatus(200);
					response.getWriter().write(uploadStatusResponse);
				} else response.setStatus(500);
				return;
			} else {
				final String initUploadResponse = ooyalaService.initUpload(requestJson);
				if (initUploadResponse != null && !"".equals(initUploadResponse)) {
					response.setStatus(200);
					response.getWriter().write(initUploadResponse);
				} else response.setStatus(500);
			}
		} catch (JSONException je) {
			je.printStackTrace();
			response.sendError(500);
		}
		return;
	}

	private String getActionFromPath(String path) {
		final Matcher matcher = assetIdPattern.matcher(path);
		if (matcher.matches()) {
			return matcher.group(3);
		} else {
			return null;
		}
	}

	private String getAssetIdFromPath(String path) {
		final Matcher matcher = assetIdPattern.matcher(path);
		if (matcher.matches()) {
			return matcher.group(2);
		} else {
			return null;
		}
	}
}


text:
require 'interactive_grep/version'
require 'interactive_grep/grepper'
module InteractiveGrep; end


text:
@interface CommentViewController : BaseViewController

@property (nonatomic, copy)NSString *ID;//传入的漫画id

@end


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_RESOLVER_STATE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_RESOLVER_STATE_H_

#include "third_party/blink/renderer/core/animation/css/css_animation_update.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/css_property_name.h"
#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_to_length_conversion_data.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_mode.h"
#include "third_party/blink/renderer/core/css/resolver/css_to_style_map.h"
#include "third_party/blink/renderer/core/css/resolver/element_resolve_context.h"
#include "third_party/blink/renderer/core/css/resolver/element_style_resources.h"
#include "third_party/blink/renderer/core/css/resolver/font_builder.h"
#include "third_party/blink/renderer/core/css/style_recalc_context.h"
#include "third_party/blink/renderer/core/css/style_request.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"

namespace blink {

class ComputedStyle;
class FontDescription;
class PseudoElement;

// A per-element object which wraps an ElementResolveContext. It collects state
// throughout the process of computing the style. It also gives convenient
// access to other element-related information.
class CORE_EXPORT StyleResolverState {
  STACK_ALLOCATED();

  enum class ElementType { kElement, kPseudoElement };

 public:
  StyleResolverState(Document&,
                     Element&,
                     const StyleRecalcContext& = StyleRecalcContext(),
                     const StyleRequest& = StyleRequest());
  StyleResolverState(const StyleResolverState&) = delete;
  StyleResolverState& operator=(const StyleResolverState&) = delete;
  ~StyleResolverState();

  bool IsForPseudoElement() const {
    return element_type_ == ElementType::kPseudoElement;
  }
  bool IsInheritedForUnset(const CSSProperty& property) const;

  // In FontFaceSet and CanvasRenderingContext2D, we don't have an element to
  // grab the document from.  This is why we have to store the document
  // separately.
  Document& GetDocument() const { return *document_; }
  // These are all just pass-through methods to ElementResolveContext.
  Element& GetElement() const { return element_context_.GetElement(); }
  const ContainerNode* ParentNode() const {
    return element_context_.ParentNode();
  }
  const ComputedStyle* RootElementStyle() const {
    if (const auto* root_element_style = element_context_.RootElementStyle())
      return root_element_style;
    return Style();
  }
  EInsideLink ElementLinkState() const {
    return element_context_.ElementLinkState();
  }

  const ElementResolveContext& ElementContext() const {
    return element_context_;
  }

  void SetStyle(scoped_refptr<ComputedStyle>);
  const ComputedStyle* Style() const { return style_.get(); }
  ComputedStyle* Style() { return style_.get(); }
  ComputedStyle& StyleRef() {
    DCHECK(style_);
    return *style_;
  }
  scoped_refptr<ComputedStyle> TakeStyle();

  const CSSToLengthConversionData& CssToLengthConversionData() const {
    return css_to_length_conversion_data_;
  }
  CSSToLengthConversionData FontSizeConversionData() const;
  CSSToLengthConversionData UnzoomedLengthConversionData() const;

  void SetConversionFontSizes(
      const CSSToLengthConversionData::FontSizes& font_sizes) {
    css_to_length_conversion_data_.SetFontSizes(font_sizes);
  }
  void SetConversionZoom(float zoom) {
    css_to_length_conversion_data_.SetZoom(zoom);
  }

  CSSAnimationUpdate& AnimationUpdate() { return animation_update_; }
  const CSSAnimationUpdate& AnimationUpdate() const {
    return animation_update_;
  }

  Element* GetAnimatingElement() const;

  void SetParentStyle(scoped_refptr<const ComputedStyle>);
  const ComputedStyle* ParentStyle() const { return parent_style_.get(); }

  void SetLayoutParentStyle(scoped_refptr<const ComputedStyle>);
  const ComputedStyle* LayoutParentStyle() const {
    return layout_parent_style_.get();
  }

  ElementStyleResources& GetElementStyleResources() {
    return element_style_resources_;
  }

  void LoadPendingResources();

  // FIXME: Once styleImage can be made to not take a StyleResolverState
  // this convenience function should be removed. As-is, without this, call
  // sites are extremely verbose.
  StyleImage* GetStyleImage(CSSPropertyID property_id, const CSSValue& value) {
    return element_style_resources_.GetStyleImage(property_id, value);
  }

  FontBuilder& GetFontBuilder() { return font_builder_; }
  const FontBuilder& GetFontBuilder() const { return font_builder_; }
  // FIXME: These exist as a primitive way to track mutations to font-related
  // properties on a ComputedStyle. As designed, these are very error-prone, as
  // some callers set these directly on the ComputedStyle w/o telling us.
  // Presumably we'll want to design a better wrapper around ComputedStyle for
  // tracking these mutations and separate it from StyleResolverState.
  const FontDescription& ParentFontDescription() const;

  void SetZoom(float);
  void SetEffectiveZoom(float);
  void SetWritingMode(WritingMode);
  void SetTextOrientation(ETextOrientation);

  CSSParserMode GetParserMode() const;

  // If the input CSSValue is a CSSLightDarkValuePair, return the light or dark
  // CSSValue based on the UsedColorScheme. For all other values, just return a
  // reference to the passed value.
  const CSSValue& ResolveLightDarkPair(const CSSValue&);

  bool IsForHighlight() const { return is_for_highlight_; }

  bool CanCacheBaseStyle() const { return can_cache_base_style_; }

  bool HadNoMatchedProperties() const { return had_no_matched_properties_; }
  void SetHadNoMatchedProperties() { had_no_matched_properties_ = true; }

  // True if the cascade observed any  "animation" or "transition" properties,
  // or when such properties were found within non-matching container queries.
  //
  // The flag is supposed to represent whether or not animations can be
  // affected by at least one of the style variations produced by evaluating
  // @container rules differently.
  bool CanAffectAnimations() const { return can_affect_animations_; }
  void SetCanAffectAnimations() { can_affect_animations_ = true; }

  bool AffectsCompositorSnapshots() const {
    return affects_compositor_snapshots_;
  }
  void SetAffectsCompositorSnapshots() { affects_compositor_snapshots_ = true; }

 private:
  void UpdateLengthConversionData();
  CSSToLengthConversionData UnzoomedLengthConversionData(
      const ComputedStyle* font_style) const;

  ElementResolveContext element_context_;
  Document* document_;

  // style_ is the primary output for each element's style resolve.
  scoped_refptr<ComputedStyle> style_;

  CSSToLengthConversionData css_to_length_conversion_data_;

  // parent_style_ is not always just ElementResolveContext::ParentStyle(),
  // so we keep it separate.
  scoped_refptr<const ComputedStyle> parent_style_;
  // This will almost-always be the same that parent_style_, except in the
  // presence of display: contents. This is the style against which we have to
  // do adjustment.
  scoped_refptr<const ComputedStyle> layout_parent_style_;

  CSSAnimationUpdate animation_update_;
  StyleRequest::RequestType pseudo_request_type_;

  FontBuilder font_builder_;

  PseudoElement* pseudo_element_;
  ElementStyleResources element_style_resources_;
  ElementType element_type_;
  Element* nearest_container_;

  // True if we are resolving styles for a highlight pseudo-element.
  const bool is_for_highlight_;

  // True if the base style can be cached to optimize style recalculations for
  // animation updates or transition retargeting.
  bool can_cache_base_style_ = false;

  // Set to true if a given style resolve produced an empty MatchResult.
  // This is used to return a nullptr style for pseudo-element style resolves.
  bool had_no_matched_properties_ = false;

  // True whenever a matching rule in a non-matching container query contains
  // any properties that can affect animations or transitions.
  bool can_affect_animations_ = false;

  // True if snapshots of composited keyframes require re-validation.
  bool affects_compositor_snapshots_ = false;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_RESOLVER_STATE_H_


text:
"""
VerseBot for Slack
By Matt Arnold
Adapted from VerseBot for Reddit by Matthieu Grieger
Copyright (c) 2016 Matt Arnold (MIT License)

"""
import asyncio
import websockets
import json
import signal
import logging
import time
import re
from slacker import Slacker

import sys
import threading

import books
import webparser
from regex import find_verses
from response import Response
from verse import Verse
from webparser import WebParser

# Time (seconds) to wait between receiving message before sending a ping
TIMEOUT = 3

class VerseBot(threading.Thread):
    def __init__(self, token):
        super(VerseBot, self).__init__()

        logging.getLogger('requests').setLevel(logging.WARNING)

        self.log = logging.getLogger('versebot')
        self.log.addHandler(logging.FileHandler('versebot_log.txt'))
        self.parser = WebParser()
        self.slack = Slacker(token)
        self.next_id = 1
        self.unacked_messages = set()
        self.user_id = self._get_user_id()

    def _get_user_id(self):
        data = self.slack.auth.test()

        if data.successful:
            return data.body['user_id']
        else:
            raise Exception

    async def connect(self):
        rtm_response = self.slack.rtm.start()

        if rtm_response.successful:
            url = rtm_response.body['url']

            while True:
                try:
                    await self.listen(url)
                except websockets.ConnectionClosed:
                    pass
                except Exception as e:
                    self.log.error('caught ' + str(type(e)) + ':' + str(e))
                    pass

        else:
            self.log.error('Failed to connect to rtm')

    def run(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        asyncio.ensure_future(self.connect())
        loop.run_forever()

    async def listen(self, url):
        async with websockets.connect(url) as websocket:
            while True:
                try:
                    msg = await asyncio.wait_for(websocket.recv(), TIMEOUT)
                    msg = json.loads(msg)

                    if msg.get('type', '') == 'message' and \
                                    msg.get('subtype', '') != 'bot_message':
                        if msg.get('text', '').find('@' + self.user_id) != -1:
                            await self.send_verses_response(msg, websocket)
                            time.sleep(1)
                    elif msg.get('type', '') == 'error':
                        self.log.error(
                            'error message received: %s' % (json.dumps(msg)))
                        return

                    # TODO handle rtm response. check if ok
                    else:
                        pass
                except asyncio.TimeoutError:
                    await self.ping(websocket)

    async def send_verses_response(self, msg, websocket):
        user = msg['user']
        channel = msg['channel']
        body = msg['text']

        match = re.search(r'[""].*"', body)

        if match is not None:
            reference = self.search(match.group(0))
            if reference is None:
                pass
            else:
                body = '[' + reference + ']'

        verses = find_verses(body)
        await self.send_verses(body, verses, user, channel, websocket)

    async def ping(self, websocket):
        ping_message = json.dumps({"id": self.next_id, "type": "ping",
                                   "time": time.time()})
        self.next_id += 1
        await websocket.send(ping_message)
        pong = await websocket.recv()
        # eventually validate or something here

    async def send_message(self, text, channel, websocket):
        data = {'id': self.next_id, 'type': 'message', 'channel': channel,
                'text': text}

        self.next_id += 1
        self.unacked_messages.add(self.next_id)

        await websocket.send(json.dumps(data))

    async def send_verses(self, body, verses, user, channel, websocket):
        if verses is not None:
            response = Response(body, self.parser)
            for verse in verses:
                book_name = books.get_book(verse[0])
                if book_name is not None:
                    v = Verse(book_name,
                              verse[1],
                              verse[3],
                              user,
                              channel,
                              verse[2])
                    if not response.is_duplicate_verse(v):
                        response.add_verse(v)
            if len(response.verse_list) != 0:
                message_response = response.construct_message()
                if message_response is not None:
                    await self.send_message(message_response, channel,
                                            websocket)
        else:
            pass

    def search(self, search_terms):
        return webparser.search_bible_gateway(search_terms)

def handle_sigint(sig, frame):
    for thread in threads:
        signal.pthread_kill(thread.ident, signal.SIGINT)

    sys.exit(0)

threads = []
if __name__ == '__main__':
    signal.signal(signal.SIGINT, handle_sigint)

    with open('tokens.dat') as tokens:
        for token in tokens.readlines():
            token = token.strip()
            vb = VerseBot(token)
            vb.start()
            threads.append(vb)

    for t in threads:
        t.join()


text:
require 'spec_helper'

describe 'cloudera::cdh5::oozie::mysql', :type => 'class' do

#  context 'on a non-supported operatingsystem' do
#    let :facts do {
#      :osfamily        => 'foo',
#      :operatingsystem => 'bar'
#    }
#    end
#    it 'should fail' do
#      expect {
#        should raise_error(Puppet::Error, /Module cloudera is not supported on bar/)
#      }
#    end
#  end

  context 'on a supported operatingsystem, default parameters' do
    let(:params) {{ }}
    let :facts do {
      :osfamily        => 'RedHat',
      :operatingsystem => 'CentOS'
    }
    end
    it { should contain_class('mysql::bindings') }
    it { should contain_class('mysql::bindings::java') }
    it { should contain_file('/usr/lib/oozie/libext/mysql-connector-java.jar').with(
      :ensure => 'link',
      :target => '/usr/share/java/mysql-connector-java.jar'
    )}
  end
end


text:
package server

import (
	"context"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"github.com/envoyproxy/go-control-plane/pkg/server/delta/v3"
	"github.com/envoyproxy/go-control-plane/pkg/server/rest/v3"
	"github.com/envoyproxy/go-control-plane/pkg/server/sotw/v3"
	"github.com/envoyproxy/go-control-plane/pkg/server/stream/v3"

	clusterservice "github.com/envoyproxy/go-control-plane/envoy/service/cluster/v3"
	discovery "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
	discoverygrpc "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
	endpointservice "github.com/envoyproxy/go-control-plane/envoy/service/endpoint/v3"
	listenerservice "github.com/envoyproxy/go-control-plane/envoy/service/listener/v3"
	routeservice "github.com/envoyproxy/go-control-plane/envoy/service/route/v3"
	runtimeservice "github.com/envoyproxy/go-control-plane/envoy/service/runtime/v3"
	secretservice "github.com/envoyproxy/go-control-plane/envoy/service/secret/v3"
	"github.com/envoyproxy/go-control-plane/pkg/cache/v3"
	"github.com/envoyproxy/go-control-plane/pkg/resource/v3"
)

// Server is a collection of handlers for streaming discovery requests.
type Server interface {
	endpointservice.EndpointDiscoveryServiceServer
	clusterservice.ClusterDiscoveryServiceServer
	routeservice.RouteDiscoveryServiceServer
	listenerservice.ListenerDiscoveryServiceServer
	discoverygrpc.AggregatedDiscoveryServiceServer
	secretservice.SecretDiscoveryServiceServer
	runtimeservice.RuntimeDiscoveryServiceServer

	rest.Server
	sotw.Server
	delta.Server
}

// Callbacks is a collection of callbacks inserted into the server operation.
// The callbacks are invoked synchronously.
type Callbacks interface {
	rest.Callbacks
	sotw.Callbacks
	delta.Callbacks
}

// CallbackFuncs is a convenience type for implementing the Callbacks interface.
type CallbackFuncs struct {
	StreamOpenFunc          func(context.Context, int64, string) error
	StreamClosedFunc        func(int64)
	DeltaStreamOpenFunc     func(context.Context, int64, string) error
	DeltaStreamClosedFunc   func(int64)
	StreamRequestFunc       func(int64, *discovery.DiscoveryRequest) error
	StreamResponseFunc      func(int64, *discovery.DiscoveryRequest, *discovery.DiscoveryResponse)
	StreamDeltaRequestFunc  func(int64, *discovery.DeltaDiscoveryRequest) error
	StreamDeltaResponseFunc func(int64, *discovery.DeltaDiscoveryRequest, *discovery.DeltaDiscoveryResponse)
	FetchRequestFunc        func(context.Context, *discovery.DiscoveryRequest) error
	FetchResponseFunc       func(*discovery.DiscoveryRequest, *discovery.DiscoveryResponse)
}

var _ Callbacks = CallbackFuncs{}

// OnStreamOpen invokes StreamOpenFunc.
func (c CallbackFuncs) OnStreamOpen(ctx context.Context, streamID int64, typeURL string) error {
	if c.StreamOpenFunc != nil {
		return c.StreamOpenFunc(ctx, streamID, typeURL)
	}

	return nil
}

// OnStreamClosed invokes StreamClosedFunc.
func (c CallbackFuncs) OnStreamClosed(streamID int64) {
	if c.StreamClosedFunc != nil {
		c.StreamClosedFunc(streamID)
	}
}

// OnDeltaStreamOpen invokes DeltaStreamOpenFunc.
func (c CallbackFuncs) OnDeltaStreamOpen(ctx context.Context, streamID int64, typeURL string) error {
	if c.StreamOpenFunc != nil {
		return c.DeltaStreamOpenFunc(ctx, streamID, typeURL)
	}

	return nil
}

// OnDeltaStreamClosed invokes DeltaStreamClosedFunc.
func (c CallbackFuncs) OnDeltaStreamClosed(streamID int64) {
	if c.StreamClosedFunc != nil {
		c.DeltaStreamClosedFunc(streamID)
	}
}

// OnStreamRequest invokes StreamRequestFunc.
func (c CallbackFuncs) OnStreamRequest(streamID int64, req *discovery.DiscoveryRequest) error {
	if c.StreamRequestFunc != nil {
		return c.StreamRequestFunc(streamID, req)
	}

	return nil
}

// OnStreamResponse invokes StreamResponseFunc.
func (c CallbackFuncs) OnStreamResponse(streamID int64, req *discovery.DiscoveryRequest, resp *discovery.DiscoveryResponse) {
	if c.StreamResponseFunc != nil {
		c.StreamResponseFunc(streamID, req, resp)
	}
}

// OnStreamDeltaRequest invokes StreamDeltaResponseFunc
func (c CallbackFuncs) OnStreamDeltaRequest(streamID int64, req *discovery.DeltaDiscoveryRequest) error {
	if c.StreamDeltaRequestFunc != nil {
		return c.StreamDeltaRequestFunc(streamID, req)
	}

	return nil
}

// OnStreamDeltaResponse invokes StreamDeltaResponseFunc.
func (c CallbackFuncs) OnStreamDeltaResponse(streamID int64, req *discovery.DeltaDiscoveryRequest, resp *discovery.DeltaDiscoveryResponse) {
	if c.StreamDeltaResponseFunc != nil {
		c.StreamDeltaResponseFunc(streamID, req, resp)
	}
}

// OnFetchRequest invokes FetchRequestFunc.
func (c CallbackFuncs) OnFetchRequest(ctx context.Context, req *discovery.DiscoveryRequest) error {
	if c.FetchRequestFunc != nil {
		return c.FetchRequestFunc(ctx, req)
	}

	return nil
}

// OnFetchResponse invoked FetchResponseFunc.
func (c CallbackFuncs) OnFetchResponse(req *discovery.DiscoveryRequest, resp *discovery.DiscoveryResponse) {
	if c.FetchResponseFunc != nil {
		c.FetchResponseFunc(req, resp)
	}
}

// NewServer creates handlers from a config watcher and callbacks.
func NewServer(ctx context.Context, config cache.Cache, callbacks Callbacks) Server {
	return NewServerAdvanced(rest.NewServer(config, callbacks),
		sotw.NewServer(ctx, config, callbacks),
		delta.NewServer(ctx, config, callbacks),
	)
}

func NewServerAdvanced(restServer rest.Server, sotwServer sotw.Server, deltaServer delta.Server) Server {
	return &server{rest: restServer, sotw: sotwServer, delta: deltaServer}
}

type server struct {
	rest  rest.Server
	sotw  sotw.Server
	delta delta.Server
}

func (s *server) StreamHandler(stream sotw.Stream, typeURL string) error {
	return s.sotw.StreamHandler(stream, typeURL)
}

func (s *server) StreamAggregatedResources(stream discoverygrpc.AggregatedDiscoveryService_StreamAggregatedResourcesServer) error {
	return s.StreamHandler(stream, resource.AnyType)
}

func (s *server) StreamEndpoints(stream endpointservice.EndpointDiscoveryService_StreamEndpointsServer) error {
	return s.StreamHandler(stream, resource.EndpointType)
}

func (s *server) StreamClusters(stream clusterservice.ClusterDiscoveryService_StreamClustersServer) error {
	return s.StreamHandler(stream, resource.ClusterType)
}

func (s *server) StreamRoutes(stream routeservice.RouteDiscoveryService_StreamRoutesServer) error {
	return s.StreamHandler(stream, resource.RouteType)
}

func (s *server) StreamListeners(stream listenerservice.ListenerDiscoveryService_StreamListenersServer) error {
	return s.StreamHandler(stream, resource.ListenerType)
}

func (s *server) StreamSecrets(stream secretservice.SecretDiscoveryService_StreamSecretsServer) error {
	return s.StreamHandler(stream, resource.SecretType)
}

func (s *server) StreamRuntime(stream runtimeservice.RuntimeDiscoveryService_StreamRuntimeServer) error {
	return s.StreamHandler(stream, resource.RuntimeType)
}

// Fetch is the universal fetch method.
func (s *server) Fetch(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
	return s.rest.Fetch(ctx, req)
}

func (s *server) FetchEndpoints(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
	if req == nil {
		return nil, status.Errorf(codes.Unavailable, "empty request")
	}
	req.TypeUrl = resource.EndpointType
	return s.Fetch(ctx, req)
}

func (s *server) FetchClusters(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
	if req == nil {
		return nil, status.Errorf(codes.Unavailable, "empty request")
	}
	req.TypeUrl = resource.ClusterType
	return s.Fetch(ctx, req)
}

func (s *server) FetchRoutes(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
	if req == nil {
		return nil, status.Errorf(codes.Unavailable, "empty request")
	}
	req.TypeUrl = resource.RouteType
	return s.Fetch(ctx, req)
}

func (s *server) FetchListeners(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
	if req == nil {
		return nil, status.Errorf(codes.Unavailable, "empty request")
	}
	req.TypeUrl = resource.ListenerType
	return s.Fetch(ctx, req)
}

func (s *server) FetchSecrets(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
	if req == nil {
		return nil, status.Errorf(codes.Unavailable, "empty request")
	}
	req.TypeUrl = resource.SecretType
	return s.Fetch(ctx, req)
}

func (s *server) FetchRuntime(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
	if req == nil {
		return nil, status.Errorf(codes.Unavailable, "empty request")
	}
	req.TypeUrl = resource.RuntimeType
	return s.Fetch(ctx, req)
}

func (s *server) DeltaStreamHandler(stream stream.DeltaStream, typeURL string) error {
	return s.delta.DeltaStreamHandler(stream, typeURL)
}

func (s *server) DeltaAggregatedResources(stream discoverygrpc.AggregatedDiscoveryService_DeltaAggregatedResourcesServer) error {
	return s.DeltaStreamHandler(stream, resource.AnyType)
}

func (s *server) DeltaEndpoints(stream endpointservice.EndpointDiscoveryService_DeltaEndpointsServer) error {
	return s.DeltaStreamHandler(stream, resource.EndpointType)
}

func (s *server) DeltaClusters(stream clusterservice.ClusterDiscoveryService_DeltaClustersServer) error {
	return s.DeltaStreamHandler(stream, resource.ClusterType)
}

func (s *server) DeltaRoutes(stream routeservice.RouteDiscoveryService_DeltaRoutesServer) error {
	return s.DeltaStreamHandler(stream, resource.RouteType)
}

func (s *server) DeltaListeners(stream listenerservice.ListenerDiscoveryService_DeltaListenersServer) error {
	return s.DeltaStreamHandler(stream, resource.ListenerType)
}

func (s *server) DeltaSecrets(stream secretservice.SecretDiscoveryService_DeltaSecretsServer) error {
	return s.DeltaStreamHandler(stream, resource.SecretType)
}

func (s *server) DeltaRuntime(stream runtimeservice.RuntimeDiscoveryService_DeltaRuntimeServer) error {
	return s.DeltaStreamHandler(stream, resource.RuntimeType)
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<link href="{Saivi::RES}/css/Estate/lp/css/review.css" rel="stylesheet" type="text/css" media="all" />
<link href="{Saivi::RES}/css/Estate/css/reset_ny.css" rel="stylesheet" type="text/css" />
<title>客户点评</title>
<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
<meta content="no-cache,must-revalidate" http-equiv="Cache-Control">
<meta content="no-cache" http-equiv="pragma">
<meta content="0" http-equiv="expires">
<meta content="telephone=no, address=no" name="format-detection">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="shortcut icon" href="{Saivi::RES}/css/Estate/img/favicon.ico" />

返回

前进

$_GET['token'],'id'=>$estate['id']))}">首页

刷新

客户点评

    <volist name="zjdp" id="info">

{Saivi:$info.name}    点评酒吧:{Saivi:$info.subestatename}

            {Saivi:$info.zw}

            <php>echo htmlspecialchars_decode($info['content'])</php>

{Saivi:$info.title}

            <php>echo htmlspecialchars_decode($info['dpcontent'])</php>

    </volist>

<if condition="$kefu['jiuba'] eq '1'"></if>


text:
/*
 * aria2 - The high speed download utility
 *
 * Copyright (C) 2006 Tatsuhiro Tsujikawa
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 */
/* copyright --> */
#include "InitiateConnectionCommandFactory.h"
#include "HttpInitiateConnectionCommand.h"
#include "FtpInitiateConnectionCommand.h"
#include "Request.h"
#include "RequestGroup.h"
#include "DownloadEngine.h"
#include "DlAbortEx.h"
#include "fmt.h"
#include "Option.h"
#include "prefs.h"
#include "SocketCore.h"
#include "SocketRecvBuffer.h"

namespace aria2 {

std::unique_ptr<Command>
InitiateConnectionCommandFactory::createInitiateConnectionCommand
(cuid_t cuid,
 const std::shared_ptr<Request>& req,
 const std::shared_ptr<FileEntry>& fileEntry,
 RequestGroup* requestGroup,
 DownloadEngine* e)
{
  if(req->getProtocol() == "http"
#ifdef ENABLE_SSL
     // for SSL
     || req->getProtocol() == "https"
#endif // ENABLE_SSL
     ) {

    if(requestGroup->getOption()->getAsBool(PREF_ENABLE_HTTP_KEEP_ALIVE)) {
      req->setKeepAliveHint(true);
    }
    if(requestGroup->getOption()->getAsBool(PREF_ENABLE_HTTP_PIPELINING)) {
      req->setPipeliningHint(true);
    }

    return make_unique<HttpInitiateConnectionCommand>(cuid, req, fileEntry,
                                                      requestGroup, e);
  } else if(req->getProtocol() == "ftp") {
    if(req->getFile().empty()) {
      throw DL_ABORT_EX
        (fmt("FTP URI %s doesn't contain file path.",
             req->getUri().c_str()));
    }
    return make_unique<FtpInitiateConnectionCommand>(cuid, req, fileEntry,
                                                     requestGroup, e);
  } else {
    // these protocols are not supported yet
    throw DL_ABORT_EX
      (fmt("%s is not supported yet.",
           req->getProtocol().c_str()));
  }
}

} // namespace aria2


text:
<?php

$fecha = strip_tags($_POST['fecha-ingreso']);
$cuenta = strip_tags($_POST['cuenta-ingreso']);
$categoria = strip_tags($_POST['categoria-ingreso']);
$subcategoria = strip_tags($_POST['subcategoria-ingreso']);
$beneficiario = strip_tags($_POST['beneficiario-ingreso']);
$m = strip_tags($_POST['monto-ingreso']);
$monto = preg_replace("/[^0-9.]/", "", $m);
$descripcion = utf8_decode(strip_tags($_POST['descripcion-ingreso']));

if ($subcategoria == "") {
    $subcategoria = "NULL";
}

require "../db/abrirBD.php";

$consulta = "insert into " . $dbname . ".transaccion
            (Cuenta,Beneficiario,Categoria,SubCategoria,Descripcion,Fecha,Ingreso)
            VALUES (" . $cuenta . "," . $beneficiario . "," . $categoria . "," . $subcategoria . ",'" . $descripcion . "','" . $fecha . "'," . $monto . ");";

if (mysqli_query($conn, $consulta)) {
    $m = "Guardado correctamente";
} else {
    $m = "Ocurrio un error " ;
}

require "../db/cerrarBD.php";

echo $m;


text:
<?php

namespace Doctrine\Tests\ORM\Functional;

require_once __DIR__ . '/../../TestInit.php';

/**
 * Functional Query tests.
 *
 * @group DDC-692
 */
class ReadOnlyTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
    protected function setUp()
    {
        parent::setUp();

        $this->_schemaTool->createSchema(array(
            $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\ReadOnlyEntity'),
        ));
    }

    public function testReadOnlyEntityNeverChangeTracked()
    {
        $readOnly = new ReadOnlyEntity("Test1", 1234);
        $this->_em->persist($readOnly);
        $this->_em->flush();

        $readOnly->name = "Test2";
        $readOnly->numericValue = 4321;

        $this->_em->flush();
        $this->_em->clear();

        $dbReadOnly = $this->_em->find('Doctrine\Tests\ORM\Functional\ReadOnlyEntity', $readOnly->id);
        $this->assertEquals("Test1", $dbReadOnly->name);
        $this->assertEquals(1234, $dbReadOnly->numericValue);
    }
}

/**
 * @Entity(readOnly=true)
 */
class ReadOnlyEntity
{
    /**
     * @Id @GeneratedValue @Column(type="integer")
     * @var int
     */
    public $id;
    /** @column(type="string") */
    public $name;
    /** @Column(type="integer") */
    public $numericValue;

    public function __construct($name, $number)
    {
        $this->name = $name;
        $this->numericValue = $number;
    }
}


text:
const _ = require('lodash');

console.log(typeof _.each);
debugger


text:
using System;
using RtmpSharp.IO;
using System.Collections.Generic;

namespace LegendaryClient.Logic.Riot.Platform
{
    [Serializable]
    [SerializedName("com.riotgames.platform.summoner.TalentGroup")]
    public class TalentGroup
    {
        [SerializedName("index")]
        public Int32 Index { get; set; }

        [SerializedName("talentRows")]
        public List<TalentRow> TalentRows { get; set; }

        [SerializedName("name")]
        public String Name { get; set; }

        [SerializedName("tltGroupId")]
        public Int32 TltGroupId { get; set; }
    }
}


text:
package com.mobilesolutionworks.android.imagepaging;

public interface Scrollable {

    boolean isHittingEdge(int direction);

    boolean isScrollable();
}


text:
from __future__ import division
import cv2
import numpy as np

tolerance = 40
visited = []

def rough_scan(image):
    width, height = image_size(image)
    for j in range(0, height, 100):
        for i in range(0, width, 100):
            if i > 50 and i < width-50:
                if check_difference(image[j,i]) == True:
                    if check_down(image, i, j) == True:
                        if (j == 0):
                            return 0
                        else:
                            return(j-100)

def scan_img(image):
    img_r = False
    width, height = image_size(image)
    min_height = rough_scan(image)
    get_tolerance(image, width, height)
    if min_height == 0:
        # print("ROTATE!")
        img_r = True
        image = rotate_image(image)
        min_height = rough_scan(image)
    for j in range(min_height, height):
        for i in range(width):
            if i > 50 and i < width-50:
                if check_difference(image[j,i]) == True:
                    if check_down(image, i, j, True) == True:
                        return(i, j, img_r)

def rotate_image(image):
    rotated = np.rot90(image)
    rotated = np.rot90(rotated)
    return rotated

def check_down(image, i ,j, check = False):
    good = True
    if (j < 2770):
        for x in range(200):
            if good == True:
                visited.append([j+x,i])
                if check_difference(image[j+x,i]) == False:
                    good = False
    else:
        good = False
    return good

def check_difference(pixel):
    b, g, r = pixel
    if r < b + tolerance:
        return False
    return True

#image_size returns the dimensions of the image in width, height format
def image_size(image):
    return tuple(image.shape[1::-1])

def get_tolerance(image, width, height):
    global tolerance
    total = 0
    num = 0
    for j in range(50, height, 100):
        for i in range(0, width, 100):
            if i > 50 and i < width - 50:
                b,g,r = image[j,i]
                total += (int(r) - int(b))
                num += 1

    average = total / num
    tolerance = average + 10

def get_length(image):
    result = scan_img(image)
    x, y, img_r = result
    if img_r == True:
        image = rotate_image(image)
    for i in range(len(visited)):
        image[visited[i][0], visited[i][1]] = [255,0,0]
    image[y, :] = [0, 0, 255]
    cv2.imwrite("lines.png", image)
    raw = 2969 - y
    foot_length = raw/10
    return foot_length


text:
package org.apache.jena.graph.impl;

import org.apache.jena.graph.Capabilities ;

/**
    A default implementation of capabilities, in which everything is allowed,
    size is accurate, and graphs may be completely empty.
 */

public class AllCapabilities implements Capabilities
    {
    @Override
    public boolean sizeAccurate() { return true; }
    @Override
    public boolean addAllowed() { return addAllowed( false ); }
    @Override
    public boolean addAllowed( boolean every ) { return true; }
    @Override
    public boolean deleteAllowed() { return deleteAllowed( false ); }
    @Override
    public boolean deleteAllowed( boolean every ) { return true; }
    @Override
    public boolean canBeEmpty() { return true; }
    @Override
    public boolean iteratorRemoveAllowed() { return true; }
    @Override
    public boolean findContractSafe() { return true; }
    @Override
    public boolean handlesLiteralTyping() { return true; }
    }


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

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

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.
-->
<html>
    <head>
        <script src="./timesince.js" type="text/javascript"></script>
    </head>
    <body>
        <script>
        /**
         * This will place the text right here.
         * Ensure you have included before the lib 'timesince.js'
         *
         * It accepts a JS Date object.
         * As weird as it sounds, the month is a number between 0 and 11.
         * Example: 17th Feb 2011 is 'new Date(2001, 01, 17)'.
         *
         * If you want to variate the format, pass a string as second parameter.
         * Acceptable values are:
         * - "%%D%%" for days
         * - "%%H%%" for hours
         * - "%%M%%" for minutes
         * - "%%S%%" for seconds
         *
         * Default format is: "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds."
         */
        timeSince(new Date(2011,01,17));
        </script>
    </body>
</html>