text:
'use strict';
/**
 * Created by gbecan on 6/23/15.
 */

angular
  .module('openCompareEditor')
  .config(function ($translateProvider) {
    $translateProvider.translations('embedded', {

        'view.button.edit':'Edit',
        'edit.title':'Title',
        'edit.title.placeholder':'Title',
        'edit.title.createNewFeature':'Create a new feature',
        'edit.title.featureName':'Feature Name',
        'edit.title.featureType':'Feature type',
        'edit.title.renameFeature':'Rename',
        'edit.title.changeType':'Change type',
        'edit.title.selectRange':'Select a range to filter',
        'edit.title.from':'From',
        'edit.title.to':'To',
        'edit.title.selectProducts':'Select products to filter',
        'edit.title.embed':'Embed',
        'edit.title.showTitle':'Show title',
        'edit.title.allowEdition':'Allow edition',
        'edit.title.allowExportation':'Allow exportation',
        'edit.title.allowSharing':'Allow sharing',
        'edit.title.confirm':'Confirm',

        'edit.source.placeholder': 'Source',
        'edit.license.placeholder': 'License',

        'edit.button.edit':'Edit',
        'edit.button.export':'Export',
        'edit.button.save':'Save',
        'edit.button.validate':'Validate',
        'edit.button.embed':'Embed',
        'edit.button.remove':'Remove',
        'edit.button.addfeature':'Feature',
        'edit.button.addproduct':'Product',
        'edit.button.addfeaturegroup':'Feature group',
        'edit.button.cancel':'Cancel',
        'edit.button.apply':'Apply',
        'edit.button.confirm':'Are you sure?',
        'edit.button.no':'No',
        'edit.button.yes':'Yes',
        'edit.button.share':'Share',
        'edit.button.height':'Row height',

        'edit.type.string':'String',
        'edit.type.boolean':'Boolean',
        'edit.type.number':'Number',

        'edit.warning.removeIsDefinitive':'Removing the comparison matrix is definitive and cannot be undone. Please, confirm.',
        'edit.warning.cancelWillLoseChanges':'Cancel will lose all unsaved changes are you sure?',
        'edit.validation.warning':'This value doesn\'t seem to match the feature type, validate if you want to keep it.',

        'importer.select':'Select a file to import',
        'importer.select.url':'Give a wikipedia matrix title',
        'importer.type':'Select a file extention',
        'importer.csv.separator':'Separator',
        'importer.csv.quote':'Quote',
        'importer.csv.header':'Has header ?',
        'importer.pcm.title':'Title',
        'importer.pcm.productAsLines':'Product as lines ?',
        'importer.button.getfile':'Select a file',
        'importer.button.cancel':'Cancel',
        'importer.button.confirm':'Confirm',
        'importer.button.confirm.message':'Are you sure to import?',
        'importer.button.confirm.desc':'Please, give a name to this new PCM and confirm.'

    });
    $translateProvider.useSanitizeValueStrategy('escaped');
    $translateProvider.useLoader('i18nLoader');
    $translateProvider.preferredLanguage('oc');
})
  .factory('i18nLoader', function($q, $translate, openCompareServer) {

    return function() {
        var deferred = $q.defer();

      openCompareServer.get("/api/i18n").then(
        function (response) {
          $translate.use('oc');
          return deferred.resolve(response.data);
        },
        function() {
          $translate.use('embedded');
        }
      );

      return deferred.promise;
    };
})
  .controller("I18nCtrl", function($scope, openCompareServer) {

    $scope.changeLanguage = function(langKey) {
      openCompareServer.get("/api/i18n/" + langKey).then(function () {
            window.location.reload();
        });
    };

});


text:
import React, { PureComponent } from 'react'
import config from '../config'

import '../../css/authoring.less'

function camelCaseToWords (name) {
  return name.replace(/([A-Z])/g, ` $1`).toLowerCase()
}

const HIDDEN_OPTIONS = [ 'authoring' ]
const SEPARATOR_AFTER = [ 'pins', 'logging', 'endTime' ]

const OPTIONS_WITH_SEPARATORS = (function () {
  const result = []
  Object.keys(config).forEach(name => {
    if (HIDDEN_OPTIONS.indexOf(name) !== -1) {
      return
    }
    result.push(name)
    if (SEPARATOR_AFTER.indexOf(name) !== -1) {
      result.push('___separator___')
    }
  })
  return result
}())

export default class Authoring extends PureComponent {
  constructor (props) {
    super(props)
    this.state = {
      iframeSrc: ''
    }
    Object.keys(config).forEach(name => {
      let value = config[name]
      if (name === 'startTime' || name === 'endTime') {
        value = (new Date(value)).toISOString()
      }
      this.state[name] = value
    })
  }

  componentDidMount () {
    this.setState({
      iframeSrc: this.finalUrl()
    })
  }

  componentDidUpdate () {
    window.clearTimeout(this._iframeUpdate)
    this._iframeUpdate = setTimeout(() => {
      this.setState({
        iframeSrc: this.finalUrl()
      })
    }, 2000)
  }

  renderCheckbox (name) {
    const toggleOption = () => {
      this.setState({ [name]: !this.state[name] })
    }
    return (

<input type='checkbox' checked={this.state[name]} onChange={toggleOption} /> { camelCaseToWords(name) }

    )
  }

  renderTextInput (name) {
    const setOption = (event) => {
      this.setState({ [name]: event.target.value })
    }
    return (

{ camelCaseToWords(name) } <input type='text' value={this.state[name]} onChange={setOption} />

    )
  }

  renderPinsAuthoring () {
    const addPin = () => {
      const { pins } = this.state
      this.setState({ pins: pins.concat([[0, 0, 'label']]) })
    }
    const removePin = idx => {
      const { pins } = this.state
      const newPins = pins.concat()
      newPins.splice(idx, 1)
      this.setState({ pins: newPins })
    }
    const setProp = (idx, prop, event) => {
      const { pins } = this.state
      const newPins = pins.concat()
      newPins[idx][prop] = event.target.value
      this.setState({ pins: newPins })
    }
    const { pins } = this.state
    return (

        map pins
        { pins.map((pin, idx) =>

            lat <input type='text' className='coords' value={pins[idx][0]} onChange={setProp.bind(null, idx, 0)} />
            lng <input type='text' className='coords' value={pins[idx][1]} onChange={setProp.bind(null, idx, 1)} />
            label <input type='text' value={pins[idx][2]} onChange={setProp.bind(null, idx, 2)} />

        )}

    )
  }

  renderConfig () {
    return OPTIONS_WITH_SEPARATORS.map((name, idx) => {
      const value = this.state[name]
      if (name === '___separator___') {
        return

      }
      if (name === 'pins') {
        return this.renderPinsAuthoring()
      }
      if (typeof value === 'boolean') {
        return this.renderCheckbox(name)
      }
      if (typeof value === 'string' || typeof value === 'number') {
        return this.renderTextInput(name)
      }
    })
  }

  finalUrl () {
    let url = window.location.href.slice()
    url = url.replace('?authoring', '')

    OPTIONS_WITH_SEPARATORS.forEach(name => {
      let value = this.state[name]
      let configValue = config[name]
      if (name === 'startTime' || name === 'endTime') {
        configValue = (new Date(configValue)).toISOString()
      }
      if (name === 'pins') {
        configValue = JSON.stringify(configValue)
        // Make sure that coordinates have numeric format.
        value = JSON.stringify(value.map(a => [parseFloat(a[0]), parseFloat(a[1]), a[2]]))
      }
      if (value !== configValue) {
        if (value === true) {
          url += `&${name}`
        } else {
          url += `&${name}=${value}`
        }
      }
    })
    // Remove first &, as it's unnecessary and make sure there's ?
    url = url.replace('&', '?')
    return url
  }

  render () {
    const { iframeSrc } = this.state
    return (

Authoring

        { this.renderConfig() }

Final URL

        <textarea value={this.finalUrl()} readOnly />

Preview

    )
  }
}

redpajama_set_name: RedPajamaGithub


text:
<html>

<head>
    <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>

<body ng-app = "myApp">

<div ng-controller = "myCtrl">
    <input type = "file" file-model = "myFile"/>
    <button ng-click = "uploadFile()">upload me</button>
</div>

<script>
    var myApp = angular.module('myApp', []);

    myApp.directive('fileModel', ['$parse', function ($parse) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                var model = $parse(attrs.fileModel);
                var modelSetter = model.assign;

                element.bind('change', function(){
                    scope.$apply(function(){
                        modelSetter(scope, element[0].files[0]);
                    });
                });
            }
        };
    }]);

    myApp.service('fileUpload', ['$http', function ($http) {
        this.uploadFileToUrl = function(file, uploadUrl){
            var fd = new FormData();
            fd.append('file', file);

            $http.post(uploadUrl, fd, {
                        transformRequest: angular.identity,
                        headers: {'Content-Type': undefined}
                    })

                    .success(function(){
                    })

                    .error(function(){
                    });
        }
    }]);

    myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
        $scope.uploadFile = function(){
            var file = $scope.myFile;

            console.log('file is ' );
            console.dir(file);

            var uploadUrl = "/fileUpload";
            fileUpload.uploadFileToUrl(file, uploadUrl);
        };
    }]);

</script>

</body>
</html>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../style.css" type="text/css" media="screen">
<link rel="stylesheet" href="../../../print.css" type="text/css" media="print">
<meta content="LatLng,com.google.maps.LatLng,EARTH_RADIUS,angleFrom,clone,distanceFrom,equals,fromRadians,fromUrlValue,lat,latRadians,lng,lngRadians,toString,toUrlValue,wrapLatLng" name="keywords">
<title>com.google.maps.LatLng</title>

Google Maps API for Flash Documentation, Version 1.20	All Packages | All Classes | Index | FramesNo Frames

Class LatLng	Methods | Constants

Package	com.google.maps

Class	public class LatLng

 LatLng is a point in geographical coordinates with longitude and latitude.

Notice that although usual map projections associate longitude with the
 x-coordinate of the map, and latitude with the y-coordinate, the latitude
 coordinate is always written first, followed by the longitude, as is
 customary in cartography.

Notice also that you cannot modify the coordinates of a LatLng. If you
 want to compute another point, you have to create a new one.

Public Methods

 	Method	Defined by

LatLng(lat:Number, lng:Number, opt_noCorrect:Boolean = false)

   Constructs a LatLng.

	LatLng

angleFrom(other:LatLng):Number

   Returns the angle (radians) between this point and the given point.

	LatLng

clone():LatLng

   Returns a new LatLng object that is a copy of this.

	LatLng

distanceFrom(other:LatLng, opt_radius:Number):Number

   Returns the distance, in meters, from this point to the given point.

	LatLng

equals(other:LatLng):Boolean

   Tests whether this LatLng is coincident with another specified
   LatLng, allowing for numerical rounding errors.

	LatLng

fromRadians(lat:Number, lng:Number, opt_noCorrect:Boolean = false):LatLng

[static]
   Creates a latlng from radian values.

	LatLng

fromUrlValue(value:String):LatLng

[static]
   Parses a string of the form "lat,lng" and returns a point with
   those values, or null if the string could not be successfully
   parsed.

	LatLng

lat():Number

   Returns the latitude in degrees.

	LatLng

latRadians():Number

   Returns the latitude in radians.

	LatLng

lng():Number

   Returns the longitude in degrees.

	LatLng

lngRadians():Number

   Returns the longitude in radians.

	LatLng

toString():String

   Returns a  string representation of this LatLng, for example
   "48.8584, 2.2944" for Paris.

	LatLng

toUrlValue(opt_precision:Number = 6):String

   Returns a string of the form "lat,lng" for this
   LatLng.

	LatLng

wrapLatLng(latLng:LatLng):LatLng

[static]
   Returns a LatLng that is a copy of the given LatLng, but with latitude
   clamped to the range [-90, 90] and longitude wrapped to the range
   [-180, 180].

	LatLng

Public Constants

 	Constant	Defined by

 	 	EARTH_RADIUS : Number = 6378137
[static]
   The equatorial radius of the earth in meters.

	LatLng

Constructor detail

LatLng	()	constructor

public function LatLng(lat:Number, lng:Number, opt_noCorrect:Boolean = false)

   Constructs a LatLng. If opt_noCorrect is false,
   we make sure the latitude and longitude are valid, wrapping the longitude
   appropriately around the dateline and clamping the latitude at the poles.

Valid values for longitude lie in the range [-180,180]. Valid values for
   latitude lie in the range [-90,90].

      Parameters

	lat:Number —  Latitude.

	lng:Number —  Longitude.

	opt_noCorrect:Boolean (default = false) —  Flag: do not correct to valid range.

Example

Construct three LatLng instances.

   var sydney:LatLng = new LatLng(-33.8581, 151.2149);
   var bound:LatLng = new LatLng(10, 190);  // longitude set to -170
   var unbound:LatLng = new LatLng(10, 190, true);  // longitude set to 190

Method detail

angleFrom	()	method

public function angleFrom(other:LatLng):Number

   Returns the angle (radians) between this point and the given point.
   This is also the distance between those points on a unit sphere.

Parameters

	other:LatLng —  Other LatLng

Returns

	Number —  Distance in radians between this and other.

Example

Calculate angle in radians between London and Paris.

   var london:LatLng = new LatLng(51.53, -0.08);
   var paris:LatLng = new LatLng(48.8, 2.33);
   trace("angle: " + paris.angleFrom(london));

clone	()	method

public function clone():LatLng

   Returns a new LatLng object that is a copy of this.

Returns

	LatLng —
                         The new copy.

distanceFrom	()	method

public function distanceFrom(other:LatLng, opt_radius:Number):Number

   Returns the distance, in meters, from this point to the given point. Since
   we approximate the earth as a sphere, the distance could be off by as much
   as 0.3%.

Parameters

	other:LatLng —  Other LatLng

	opt_radius:Number — The radius of the planet (default EARTH_RADIUS).

Returns

	Number —  Distance in meters between this and other.

Example

Calculate distance in km between London and Sydney.

   var london:LatLng = new LatLng(51.53, -0.08);
   var sydney:LatLng = new LatLng(-34.0, 151.0);
   trace("km: " + sydney.distanceFrom(london) / 1000);

equals	()	method

public function equals(other:LatLng):Boolean

   Tests whether this LatLng is coincident with another specified
   LatLng, allowing for numerical rounding errors.

Parameters

	other:LatLng —  LatLng against which to compare.

Returns

	Boolean —  true if this LatLng is coincident with the other.

fromRadians	()	method

public static function fromRadians(lat:Number, lng:Number, opt_noCorrect:Boolean = false):LatLng

   Creates a latlng from radian values.

Parameters

	lat:Number —  Latitude in radians.

	lng:Number —  Longitude in radians.

	opt_noCorrect:Boolean (default = false) —  Flag to prevent correction to valid range.

Returns

	LatLng —
                         Resulting LatLng object.

fromUrlValue	()	method

public static function fromUrlValue(value:String):LatLng

   Parses a string of the form "lat,lng" and returns a point with
   those values, or null if the string could not be successfully
   parsed.

Parameters

	value:String —  "lat,lng" string to parse.

Returns

	LatLng —
                         Resulting LatLng.

Example

Create a LatLng from a text string.

   var location:LatLng = LatLng.fromUrlValue("-34,151");

lat	()	method

public function lat():Number

   Returns the latitude in degrees.

Returns

	Number —  Latitude in degrees.

latRadians	()	method

public function latRadians():Number

   Returns the latitude in radians.

Returns

	Number —  Latitude in radians.

lng	()	method

public function lng():Number

   Returns the longitude in degrees.

Returns

	Number —  Longitude in degrees.

lngRadians	()	method

public function lngRadians():Number

   Returns the longitude in radians.

Returns

	Number —  Longitude in radians.

toString	()	method

public function toString():String

   Returns a  string representation of this LatLng, for example
   "48.8584, 2.2944" for Paris.

Returns

	String — String representation of this LatLng.

toUrlValue	()	method

public function toUrlValue(opt_precision:Number = 6):String

   Returns a string of the form "lat,lng" for this
   LatLng.
   We round the lat/lng values to 6 decimal places by default.

precision	approximate error

-1	1000 kilometers / 700 miles

0	100 kilometers / 70 miles

1	10 kilometers / 7 miles

2	1 kilometer / 0.7 miles

3	100 meters / 300 feet

4	10 meters / 30 feet

5	1 meter / 3 feet

6	10 centimeters / 4 inches

7	1 centimeter (a nickel)

Parameters

	opt_precision:Number (default = 6) —  Number of digits following decimal point.

Returns

	String — String representation suitable for use as a URL parameter,
       for example '48.858405,2.294362' for Paris.

wrapLatLng	()	method

public static function wrapLatLng(latLng:LatLng):LatLng

   Returns a LatLng that is a copy of the given LatLng, but with latitude
   clamped to the range [-90, 90] and longitude wrapped to the range
   [-180, 180].

Parameters

	latLng:LatLng —  Unbound LatLng object.

Returns

	LatLng —
                         Bound LatLng object.

Constant detail

EARTH_RADIUS	constant

public static const EARTH_RADIUS:Number = 6378137

   The equatorial radius of the earth in meters. Assumes a perfectly spherical
   earth, and hence is approximate. The earth's radius in fact varies between
   6357 km at the pole to 6378 KM at the equator - a difference of 0.3%.


text:
using BlackBox.Service;
using IFC2X3;
using EbInstanceModel;
using System;
using System.Collections.Generic;

namespace BlackBox.Predefined
{

    public class BbPiece : BbElement
    {

        //[EarlyBindingInstance]
        //public IfcRelAggregates IfcRelAggregates { get; protected set; }

        private IfcElement _ifcElement;

        [EarlyBindingInstance]
        public override IfcObject IfcObject
        {
            get { return _ifcElement; }
            protected set
            {
                base.IfcObject = _ifcElement = value as IfcElement;
            }
        }

        public BbProfile Profile { get; protected set; }

        protected BbPiece()
            : this(Guid.NewGuid())
        {
        }

        protected BbPiece(Guid guid)
            : base(guid)
        {
        }

        protected BbPiece(
            string id, string name, string objectType, BbProfile profile,
            double length, BbCoordinate3D position, BbDirection3D zAxis,
            BbDirection3D xAxis, BbDirection3D extrudeDirection,
            BbElement hostElement, Type ifcEntityType)
            :this( name,  objectType,  profile,
             length,  position,  zAxis,
             xAxis,  extrudeDirection,
             hostElement.ObjectBbLocalPlacement,  ifcEntityType)
        {
            //AddToHostObject(hostElement);
        }

        private BbPiece(string name, string objectType, BbProfile profile,
            double length, BbCoordinate3D position, BbDirection3D zAxis,
            BbDirection3D xAxis, BbDirection3D extrudeDirection,
            BbLocalPlacement3D hostPlacement, Type ifcEntityType)
        {
            Length = length;
            Profile = profile;
            var pos = BbPosition3D.Create(position, zAxis, xAxis);

            ObjectBbLocalPlacement = BbLocalPlacement3D.Create(
                hostPlacement, pos);

            var semExtrudedGeometry = BbExtrudedGeometry.Create(
                profile,
                BbHeaderSetting.Setting3D.DefaultBbPosition3D,
                extrudeDirection,
                Length);

            _ifcElement = Activator.CreateInstance(ifcEntityType) as IfcElement;
            if (_ifcElement == null)
                return;

            _ifcElement.GlobalId = IfcGloballyUniqueId.ConvertToIfcGuid(Guid);
            _ifcElement.OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory;
            _ifcElement.Name = name;
            _ifcElement.ObjectType = objectType;
            _ifcElement.ObjectPlacement = ObjectBbLocalPlacement.IfcLocalPlacement;
            _ifcElement.Representation = semExtrudedGeometry.IfcProductDefinitionShape;
            //_ifcElement.Tag = id;
        }

        //protected BbPiece(
        //    string id, string name, string objectType, BbProfile profile,
        //    double length, BbCoordinate3D position, BbDirection3D zAxis,
        //    BbDirection3D xAxis, BbDirection3D extrudeDirection,
        //    BbSpatialElement element, Type ifcEntityType)
        //{
        //    //Profile = profile;
        //    Length = length;

        //    var pos = BbPosition3D.Create(position, zAxis, xAxis);

        //    ObjectBbLocalPlacement = BbLocalPlacement3D.Create(
        //        element.ObjectBbLocalPlacement, pos);

        //    var semExtrudedGeometry = BbExtrudedGeometry.Create(
        //        profile,
        //        BbPosition3D.DefaultPosition,
        //        extrudeDirection,
        //        Length);

        //    _ifcElement = Activator.CreateInstance(ifcEntityType) as IfcElement;
        //    if (_ifcElement == null)
        //        return;

        //    _ifcElement.GlobalId = IfcGloballyUniqueId.NewGuid();
        //    _ifcElement.OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory;
        //    _ifcElement.Name = name;
        //    _ifcElement.ObjectType = objectType;
        //    _ifcElement.ObjectPlacement = ObjectBbLocalPlacement.IfcLocalPlacement;
        //    _ifcElement.Representation = semExtrudedGeometry.IfcProductDefinitionShape;
        //    _ifcElement.Tag = id;

        //    var a = element.IfcRelAggregates;
        //    if (a == null)
        //    {
        //        element.IfcRelAggregates = new IfcRelAggregates()
        //        {
        //            GlobalId = IfcGloballyUniqueId.NewGuid(),
        //            OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory,
        //            RelatingObject = element.IfcSpatialStructureElement,
        //            RelatedObjects = new List<IfcObjectDefinition>() { _ifcElement },
        //        };
        //    }
        //    element.IfcRelAggregates.RelatedObjects.Add(_ifcElement);

        //}

        //public static BbPiece Create(
        //    string id, string pieceName, string objectType, BbProfile profile,
        //    double depth, BbCoordinate3D position, BbDirection3D zAxis,
        //    BbDirection3D xAxis, BbAssembly container, Type ifcEntityType
        //)
        //{
        //    var mainPart = new BbPiece(
        //        id, pieceName, objectType, profile, depth, position, zAxis, xAxis,
        //        BbDirection3D.ZAxis, container, ifcEntityType);
        //    //container.AddElement (mainPart);

        //    BbInstanceDB.AddToExport(mainPart);
        //    return mainPart;
        //}

    }
}


text:
(function() {
  function Emitter(obj) {
    if (obj) return mixin(obj);
  }
    /**
   * Mixin the emitter properties.
   *
   * @param {Object} obj
   * @return {Object}
   * @api private
   */

  function mixin(obj) {
    for (var key in Emitter.prototype) {
      obj[key] = Emitter.prototype[key];
    }
    return obj;
  }

  /**
   * Listen on the given `event` with `fn`.
   *
   * @param {String} event
   * @param {Function} fn
   * @return {Emitter}
   * @api public
   */

  Emitter.prototype.on =
  Emitter.prototype.addEventListener = function(event, fn){
    this._callbacks = this._callbacks || {};
    (this._callbacks[event] = this._callbacks[event] || [])
      .push(fn);
    return this;
  };

  /**
   * Adds an `event` listener that will be invoked a single
   * time then automatically removed.
   *
   * @param {String} event
   * @param {Function} fn
   * @return {Emitter}
   * @api public
   */

  Emitter.prototype.once = function(event, fn){
    var self = this;
    this._callbacks = this._callbacks || {};

    function on() {
      self.off(event, on);
      fn.apply(this, arguments);
    }

    on.fn = fn;
    this.on(event, on);
    return this;
  };

  /**
   * Remove the given callback for `event` or all
   * registered callbacks.
   *
   * @param {String} event
   * @param {Function} fn
   * @return {Emitter}
   * @api public
   */

  Emitter.prototype.off =
  Emitter.prototype.removeListener =
  Emitter.prototype.removeAllListeners =
  Emitter.prototype.removeEventListener = function(event, fn){
    this._callbacks = this._callbacks || {};

    // all
    if (0 == arguments.length) {
      this._callbacks = {};
      return this;
    }

    // specific event
    var callbacks = this._callbacks[event];
    if (!callbacks) return this;

    // remove all handlers
    if (1 == arguments.length) {
      delete this._callbacks[event];
      return this;
    }

    // remove specific handler
    var cb;
    for (var i = 0; i < callbacks.length; i++) {
      cb = callbacks[i];
      if (cb === fn || cb.fn === fn) {
        callbacks.splice(i, 1);
        break;
      }
    }
    return this;
  };

  /**
   * Emit `event` with the given args.
   *
   * @param {String} event
   * @param {Mixed} ...
   * @return {Emitter}
   */

  Emitter.prototype.emit = function(event){
    this._callbacks = this._callbacks || {};
    var args = [].slice.call(arguments, 1)
      , callbacks = this._callbacks[event];

    if (callbacks) {
      callbacks = callbacks.slice(0);
      for (var i = 0, len = callbacks.length; i < len; ++i) {
        callbacks[i].apply(this, args);
      }
    }

    return this;
  };

  /**
   * Return array of callbacks for `event`.
   *
   * @param {String} event
   * @return {Array}
   * @api public
   */

  Emitter.prototype.listeners = function(event){
    this._callbacks = this._callbacks || {};
    return this._callbacks[event] || [];
  };

  /**
   * Check if this emitter has `event` handlers.
   *
   * @param {String} event
   * @return {Boolean}
   * @api public
   */

  Emitter.prototype.hasListeners = function(event){
    return !! this.listeners(event).length;
  };
  var JS_WS_CLIENT_TYPE = 'js-websocket';
  var JS_WS_CLIENT_VERSION = '0.0.1';

  var Protocol = window.Protocol;
  var decodeIO_encoder = null;
  var decodeIO_decoder = null;
  var Package = Protocol.Package;
  var Message = Protocol.Message;
  var EventEmitter = Emitter;
  var rsa = window.rsa;

  if(typeof(window) != "undefined" && typeof(sys) != 'undefined' && sys.localStorage) {
    window.localStorage = sys.localStorage;
  }

  var RES_OK = 200;
  var RES_FAIL = 500;
  var RES_OLD_CLIENT = 501;

  if (typeof Object.create !== 'function') {
    Object.create = function (o) {
      function F() {}
      F.prototype = o;
      return new F();
    };
  }

  var root = window;
  var starx = Object.create(EventEmitter.prototype); // object extend from object
  root.starx = starx;
  var socket = null;
  var reqId = 0;
  var callbacks = {};
  var handlers = {};
  //Map from request id to route
  var routeMap = {};
  var dict = {};    // route string to code
  var abbrs = {};   // code to route string

  var heartbeatInterval = 0;
  var heartbeatTimeout = 0;
  var nextHeartbeatTimeout = 0;
  var gapThreshold = 100;   // heartbeat gap threashold
  var heartbeatId = null;
  var heartbeatTimeoutId = null;
  var handshakeCallback = null;

  var decode = null;
  var encode = null;

  var reconnect = false;
  var reconncetTimer = null;
  var reconnectUrl = null;
  var reconnectAttempts = 0;
  var reconnectionDelay = 5000;
  var DEFAULT_MAX_RECONNECT_ATTEMPTS = 10;

  var useCrypto;

  var handshakeBuffer = {
    'sys': {
      type: JS_WS_CLIENT_TYPE,
      version: JS_WS_CLIENT_VERSION,
      rsa: {}
    },
    'user': {
    }
  };

  var initCallback = null;

  starx.init = function(params, cb) {
    initCallback = cb;
    var host = params.host;
    var port = params.port;
    var path = params.path;

    encode = params.encode || defaultEncode;
    decode = params.decode || defaultDecode;

    var url = 'ws://' + host;
    if(port) {
      url +=  ':' + port;
    }

    if(path) {
      url += path;
    }

    handshakeBuffer.user = params.user;
    if(params.encrypt) {
      useCrypto = true;
      rsa.generate(1024, "10001");
      var data = {
        rsa_n: rsa.n.toString(16),
        rsa_e: rsa.e
      };
      handshakeBuffer.sys.rsa = data;
    }
    handshakeCallback = params.handshakeCallback;
    connect(params, url, cb);
  };

  var defaultDecode = starx.decode = function(data) {
    var msg = Message.decode(data);

    if(msg.id > 0){
      msg.route = routeMap[msg.id];
      delete routeMap[msg.id];
      if(!msg.route){
        return;
      }
    }

    msg.body = deCompose(msg);
    return msg;
  };

  var defaultEncode = starx.encode = function(reqId, route, msg) {
    var type = reqId ? Message.TYPE_REQUEST : Message.TYPE_NOTIFY;

    if(decodeIO_encoder && decodeIO_encoder.lookup(route)) {
      var Builder = decodeIO_encoder.build(route);
      msg = new Builder(msg).encodeNB();
    } else {
      msg = Protocol.strencode(JSON.stringify(msg));
    }

    var compressRoute = 0;
    if(dict && dict[route]) {
      route = dict[route];
      compressRoute = 1;
    }

    return Message.encode(reqId, type, compressRoute, route, msg);
  };

  var connect = function(params, url, cb) {
    console.log('connect to ' + url);

    var params = params || {};
    var maxReconnectAttempts = params.maxReconnectAttempts || DEFAULT_MAX_RECONNECT_ATTEMPTS;
    reconnectUrl = url;

    var onopen = function(event) {
      if(!!reconnect) {
        starx.emit('reconnect');
      }
      reset();
      var obj = Package.encode(Package.TYPE_HANDSHAKE, Protocol.strencode(JSON.stringify(handshakeBuffer)));
      send(obj);
    };
    var onmessage = function(event) {
      processPackage(Package.decode(event.data), cb);
      // new package arrived, update the heartbeat timeout
      if(heartbeatTimeout) {
        nextHeartbeatTimeout = Date.now() + heartbeatTimeout;
      }
    };
    var onerror = function(event) {
      starx.emit('io-error', event);
      console.error('socket error: ', event);
    };
    var onclose = function(event) {
      starx.emit('close',event);
      starx.emit('disconnect', event);
      console.log('socket close: ', event);
      if(!!params.reconnect && reconnectAttempts < maxReconnectAttempts) {
        reconnect = true;
        reconnectAttempts++;
        reconncetTimer = setTimeout(function() {
          connect(params, reconnectUrl, cb);
        }, reconnectionDelay);
        reconnectionDelay *= 2;
      }
    };
    socket = new WebSocket(url);
    socket.binaryType = 'arraybuffer';
    socket.onopen = onopen;
    socket.onmessage = onmessage;
    socket.onerror = onerror;
    socket.onclose = onclose;
  };

  starx.disconnect = function() {
    if(socket) {
      if(socket.disconnect) socket.disconnect();
      if(socket.close) socket.close();
      console.log('disconnect');
      socket = null;
    }

    if(heartbeatId) {
      clearTimeout(heartbeatId);
      heartbeatId = null;
    }
    if(heartbeatTimeoutId) {
      clearTimeout(heartbeatTimeoutId);
      heartbeatTimeoutId = null;
    }
  };

  var reset = function() {
    reconnect = false;
    reconnectionDelay = 1000 * 5;
    reconnectAttempts = 0;
    clearTimeout(reconncetTimer);
  };

  starx.request = function(route, msg, cb) {
    if(arguments.length === 2 && typeof msg === 'function') {
      cb = msg;
      msg = {};
    } else {
      msg = msg || {};
    }
    route = route || msg.route;
    if(!route) {
      return;
    }

    reqId++;
    sendMessage(reqId, route, msg);

    callbacks[reqId] = cb;
    routeMap[reqId] = route;
  };

  starx.notify = function(route, msg) {
    msg = msg || {};
    sendMessage(0, route, msg);
  };

  var sendMessage = function(reqId, route, msg) {
    if(useCrypto) {
      msg = JSON.stringify(msg);
      var sig = rsa.signString(msg, "sha256");
      msg = JSON.parse(msg);
      msg['__crypto__'] = sig;
    }

    if(encode) {
      msg = encode(reqId, route, msg);
    }

    var packet = Package.encode(Package.TYPE_DATA, msg);
    send(packet);
  };

  var send = function(packet) {
    socket.send(packet.buffer);
  };

  var handler = {};

  var heartbeat = function(data) {
    if(!heartbeatInterval) {
      // no heartbeat
      return;
    }

    var obj = Package.encode(Package.TYPE_HEARTBEAT);
    if(heartbeatTimeoutId) {
      clearTimeout(heartbeatTimeoutId);
      heartbeatTimeoutId = null;
    }

    if(heartbeatId) {
      // already in a heartbeat interval
      return;
    }
    heartbeatId = setTimeout(function() {
      heartbeatId = null;
      send(obj);

      nextHeartbeatTimeout = Date.now() + heartbeatTimeout;
      heartbeatTimeoutId = setTimeout(heartbeatTimeoutCb, heartbeatTimeout);
    }, heartbeatInterval);
  };

  var heartbeatTimeoutCb = function() {
    var gap = nextHeartbeatTimeout - Date.now();
    if(gap > gapThreshold) {
      heartbeatTimeoutId = setTimeout(heartbeatTimeoutCb, gap);
    } else {
      console.error('server heartbeat timeout');
      starx.emit('heartbeat timeout');
      starx.disconnect();
    }
  };

  var handshake = function(data) {
    data = JSON.parse(Protocol.strdecode(data));
    if(data.code === RES_OLD_CLIENT) {
      starx.emit('error', 'client version not fullfill');
      return;
    }

    if(data.code !== RES_OK) {
      starx.emit('error', 'handshake fail');
      return;
    }

    handshakeInit(data);

    var obj = Package.encode(Package.TYPE_HANDSHAKE_ACK);
    send(obj);
    if(initCallback) {
      initCallback(socket);
    }
  };

  var onData = function(data) {
    var msg = data;
    if(decode) {
      msg = decode(msg);
    }
    processMessage(starx, msg);
  };

  var onKick = function(data) {
    data = JSON.parse(Protocol.strdecode(data));
    starx.emit('onKick', data);
  };

  handlers[Package.TYPE_HANDSHAKE] = handshake;
  handlers[Package.TYPE_HEARTBEAT] = heartbeat;
  handlers[Package.TYPE_DATA] = onData;
  handlers[Package.TYPE_KICK] = onKick;

  var processPackage = function(msgs) {
    if(Array.isArray(msgs)) {
      for(var i=0; i<msgs.length; i++) {
        var msg = msgs[i];
        handlers[msg.type](msg.body);
      }
    } else {
      handlers[msgs.type](msgs.body);
    }
  };

  var processMessage = function(starx, msg) {
    if(!msg.id) {
      // server push message
      starx.emit(msg.route, msg.body);
      return;
    }

    //if have a id then find the callback function with the request
    var cb = callbacks[msg.id];

    delete callbacks[msg.id];
    if(typeof cb !== 'function') {
      return;
    }

    cb(msg.body);

  };

  var processMessageBatch = function(starx, msgs) {
    for(var i=0, l=msgs.length; i<l; i++) {
      processMessage(starx, msgs[i]);
    }
  };

  var deCompose = function(msg) {
    var route = msg.route;

    //Decompose route from dict
    if(msg.compressRoute) {
      if(!abbrs[route]){
        return {};
      }

      route = msg.route = abbrs[route];
    }

    if(decodeIO_decoder && decodeIO_decoder.lookup(route)) {
      return decodeIO_decoder.build(route).decode(msg.body);
    } else {
      return JSON.parse(Protocol.strdecode(msg.body));
    }

    return msg;
  };

  var handshakeInit = function(data) {
    if(data.sys && data.sys.heartbeat) {
      heartbeatInterval = data.sys.heartbeat * 1000;   // heartbeat interval
      heartbeatTimeout = heartbeatInterval * 2;        // max heartbeat timeout
    } else {
      heartbeatInterval = 0;
      heartbeatTimeout = 0;
    }

    initData(data);

    if(typeof handshakeCallback === 'function') {
      handshakeCallback(data.user);
    }
  };

  //Initilize data used in starx client
  var initData = function(data) {
    if(!data || !data.sys) {
      return;
    }
    dict = data.sys.dict;

    //Init compress dict
    if(dict) {
      dict = dict;
      abbrs = {};

      for(var route in dict) {
        abbrs[dict[route]] = route;
      }
    }

    window.starx = starx;
  }})();


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Profile extends CI_Controller {

  /**
   * Index Page for this controller.
   *
   * Maps to the following URL
   *    http://example.com/index.php/welcome
   *  - or -
   *    http://example.com/index.php/welcome/index
   *  - or -
   * Since this controller is set as the default controller in
   * config/routes.php, it's displayed at http://example.com/
   *
   * So any other public methods not prefixed with an underscore will
   * map to /index.php/welcome/<method_name>
   * @see http://codeigniter.com/user_guide/general/urls.html
   */
  public function index($user_id)
  {
   $this->load->view('header');
   $this->load->view('navbar');

   $this->load->database();

   $this->load->model('User');
   $data=$this->User->dataWithSkills($user_id);

   if ($data !=null){
       $this->load->view('profile', $data);
   }

    $this->load->view('footer');
  }
}


text:
using System;
using System.Collections.Generic;
using UnityEngine;

namespace Game {
	public class PathPainter {
		private List<LightCheckpoint> Checkpoints { get; set; }

		TerrainData terrainData;
		Terrain terrain;
		float widthHeight;
		int pathSize = 20;

		public PathPainter (List<LightCheckpoint> checkpoints, Terrain terrain) {
			this.Checkpoints = checkpoints;

			terrainData = terrain.terrainData;
			widthHeight = terrainData.size.x;
			var leftTop = terrain.transform.position.x;
			pathSize = (int)(widthHeight / 10);

			if (widthHeight != terrainData.size.z || leftTop != terrain.transform.position.z || widthHeight + 2 * leftTop != 0.0)
				throw new Exception ("Invalid terrain configuration!");
		}

		private float[,,] CreateTerrainMap () {
			var map = new float[terrainData.alphamapWidth, terrainData.alphamapHeight, terrainData.alphamapLayers];
			//var map = terrainData.GetAlphamaps (0, 0, terrainData.alphamapWidth, terrainData.alphamapHeight);
			for (var x = 0; x < terrainData.alphamapWidth; ++x) {
				for (var y = 0; y < terrainData.alphamapHeight; ++y) {
					map [x, y, 0] = 1f;
					map [x, y, 1] = 0f;
					map [x, y, 2] = 0f;
				}
			}
			return map;
		}

		private void PaintCheckpoint (float[,,] map, Vector2 pos) {
			PaintPoint (map, pos, 1, pathSize / 2);
		}

		private void PaintPoint (float[,,] map, Vector2 pos, int index, int size) {
			var cx = (pos.x + widthHeight / 2) / widthHeight * map.GetLength (0);
			var cy = (pos.y + widthHeight / 2) / widthHeight * map.GetLength (1);

			DrawPoint (map, (int)cx, (int)cy, index, size);
		}

		private void DrawPoint (float[,,] map, int cx, int cy, int index, int size) {
			var h = size;
			float maxDist = (float) h * (float)Math.Sqrt (2);

			for (int x = cx - h; x < cx + h; ++x) {
				for (int y = cy - h; y < cy + h; ++y) {
					float dx = Math.Abs (x - cx);
					float dy = Math.Abs (y - cy);
					float distToCenter = (float)Math.Sqrt (dx * dx + dy * dy);
					float intensity = 1.0f - distToCenter / maxDist;

					if (index == 2) {
						map [y, x, 0] = 1f-intensity;
					} else {
						map [y, x, 0] = 1f;
					}
					map [y, x, index] = Math.Max (intensity, map [y, x, 1]);
				}
			}
		}

		public void PaintPath () {
			var map = CreateTerrainMap ();

			foreach (var checkpoint in Checkpoints) {
				PaintCheckpoint (map, new Vector2 (checkpoint.Position.x, checkpoint.Position.z));
			}

			var c1 = Checkpoints [0].Position;
			PaintPoint (map, new Vector2 (c1.x, c1.z), 2, pathSize);
			var c2 = Checkpoints [Checkpoints.Count - 1].Position;
			PaintPoint (map, new Vector2 (c2.x, c2.z), 2, pathSize);

			terrainData.SetAlphamaps (0, 0, map);
		}
	}
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <com.zekunyan.linktextview.LinkTextView
        android:id="@+id/linkTextView"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="#DDDDDD"
        android:gravity="center"
        android:textColor="#000000"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/textview_info"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:background="#DDDDDD"
        android:textColor="#000000"
        android:textSize="18sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:background="#03a9f4" />

    <Button
        android:id="@+id/button_change_normal_color"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="Change Link Normal Color" />

    <Button
        android:id="@+id/button_change_pressed_color"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="Change Link Pressed color" />

    <Button
        android:id="@+id/button_change_bg_color"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="Change Link Background color" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="4dp"
        android:background="#03a9f4" />

    <EditText
        android:id="@+id/edittext_attachment"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#FFDDDDDD"
        android:hint="Input something as attachment..."
        android:textSize="18sp" />

    <Button
        android:id="@+id/button_add"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="Add Link" />

    <Button
        android:id="@+id/button_remove"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="Remove Link" />

</LinearLayout>


text:
namespace NRepository.Core.Tests
{
    public enum Names
    {
        JohnKelly = 1,
        MarcBurgess,
        PaulCox,
        NigelBurgess,
        TomCox,
        SueCox,
        JeanetteBurgess,
        IsabelleOsborne,
        EllieOsborne,
        AimmeOsborne,
        ToBeDecided
    }
}


text:
{% extends 'base.html' %}

{% block base_content %}
    <div id="bd">
        {% block content %}{% endblock content %}
    </div>
{% endblock base_content %}


text:
package com.vectorprint.certificates;

import com.vectorprint.ArrayHelper;
import com.vectorprint.IOHelper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

/**
 * Methods to load certificates, keystores and private keys. Password arguments will be cleared after use, see {@link ArrayHelper#clear(char[]) }.
 * You need to configure a {@link Provider security provider} in the jvm or programmatically.
 *
 * @author Eduard Drenth at VectorPrint.nl
 */
public class CertificateHelper {

   private CertificateHelper() {}

   /**
    * calls {@link #loadCertificate(java.io.InputStream, java.lang.String) } with X.509
    * @param in
    * @return
    * @throws IOException
    * @throws CertificateException
    */
   public static Certificate loadCertificate(InputStream in) throws IOException, CertificateException {
      return loadCertificate(in, "X.509");
   }

   /**
    * loads a certificate from a stream
    * @param in
    * @param type
    * @return
    */
   public static Certificate loadCertificate(InputStream in, String type) throws IOException, CertificateException {
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         Certificate cert = CertificateFactory.getInstance(type)
             .generateCertificate(new ByteArrayInputStream(IOHelper.load(in, out).toByteArray()));
         return cert;
   }

   /**
    * loads a keystore from an inputstream
    * @param in
    * @param keystoretype
    * @param password
    * @return
    */
   public static KeyStore loadKeyStore(InputStream in, String keystoretype, char[] password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
         KeyStore ks = KeyStore.getInstance(keystoretype);
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         ks.load(new ByteArrayInputStream(IOHelper.load(in, out).toByteArray()), password);
         ArrayHelper.clear(password);
         return ks;
   }

   /**
    * returns a private key from a keystore
    * @param ks
    * @param alias
    * @param password
    * @return
    * @throws KeyStoreException
    * @throws NoSuchAlgorithmException
    * @throws UnrecoverableKeyException
    */
   public static PrivateKey getKey(KeyStore ks, String alias, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
      PrivateKey k = (PrivateKey) ks.getKey(alias, password);
      ArrayHelper.clear(password);
      return k;
   }

   /**
    * calls {@link #getKey(java.security.KeyStore, java.lang.String, char[]) } with "1" for alias.
    * @param ks
    * @param password
    * @return
    * @throws KeyStoreException
    * @throws NoSuchAlgorithmException
    * @throws UnrecoverableKeyException
    */
   public static PrivateKey getKey(KeyStore ks, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
      return getKey(ks, "1", password);
   }
   /*
Installing the Provider Statically

To install the provider statically you need to add it as an entry to the java.security file which can be found in $JAVA_HOME/jre/lib/security/java.security for the JRE/JDK you are using. Look for a list of lines with security.provider.X where X is some number. At the bottom of the list add the line:

security.provider.N=org.bouncycastle.jce.provider.BouncyCastleProvider

where N is one more than the last number in the list.

It is possible to add the provider higher up in the list. If you do this we recommend you don't add it earlier than position 2 as there are occasionally internal dependencies on the provider at position 1 which may cause some operations by your JVM to result in errors.   */
}


text:
<?php

namespace BalanceTest\View\Template\Postings;

use Balance\Form\Element\Currency as CurrencyElement;
use Balance\Form\Postings as PostingsForm;
use PHPUnit_Framework_TestCase as TestCase;
use Zend\Dom\Query;
use Zend\Form\FormElementManager;
use Zend\Form\View\HelperConfig;
use Zend\ServiceManager\ServiceManager;
use Zend\View\Model\ViewModel;
use Zend\View\Renderer\PhpRenderer;
use Zend\View\Resolver\TemplateMapResolver;
use Zend\View\View;
use Zend\View\ViewEvent;

class EditTest extends TestCase
{
    protected function setUp()
    {
        $serviceManager = new ServiceManager();

        $serviceLocator = new FormElementManager();
        $serviceLocator->setServiceLocator($serviceManager);

        $pAccounts = $this->getMock('Balance\Model\Persistence\ValueOptionsInterface');
        $pAccounts->method('getValueOptions')->will($this->returnValue([]));
        $serviceManager->setService('Balance\Model\Persistence\Accounts', $pAccounts);

        $serviceLocator->setService('Currency', new CurrencyElement());

        $view = new View();

        $view->getEventManager()->attach(ViewEvent::EVENT_RENDERER, function () {
            $renderer = (new PhpRenderer())->setResolver(new TemplateMapResolver([
                // Páginas Básicas
                'layout/page-header'    => './module/Balance/view/layout/page-header.phtml',
                'balance/postings/edit' => './module/Balance/view/balance/postings/edit.phtml',
                // Páginas Internas
                'tests/postings/before-entries-a'
                    => './module/Balance/test/BalanceTest/View/Scripts/postings-before-entries-a.phtml',
                'tests/postings/before-entries-b'
                    => './module/Balance/test/BalanceTest/View/Scripts/postings-before-entries-b.phtml',
            ]));

            $helpers = $renderer->getHelperPluginManager();
            $helpers->get('BasePath')->setBasePath('/');

            $match = $this->getMockBuilder('Zend\Mvc\Router\RouteMatch')
                ->disableOriginalConstructor()
                ->getMock();
            $match->method('getMatchedRouteName')->will($this->returnValue('default'));

            $helpers->get('Url')
                ->setRouter($this->getMock('Zend\Mvc\Router\RouteStackInterface'))
                ->setRouteMatch($match);

            $configs = new HelperConfig();
            $configs->configureServiceManager($helpers);

            return $renderer;
        });

        $form = new PostingsForm();
        $form->setServiceLocator($serviceLocator);

        $model = (new ViewModel())
            ->setTemplate('balance/postings/edit')
            ->setVariable('form', $form)
            ->setOption('has_parent', true);

        $form->init();

        $this->view  = $view;
        $this->model = $model;
    }

    protected function tearDown()
    {
        unset($this->view);
        unset($this->model);
    }

    public function testRenderBeforeEntries()
    {
        $this->model->setVariable('beforeEntries', '
foobar
');

        $content = $this->view->render($this->model);

        $result = (new Query($content))->execute('#before-entries-container');

        $this->assertCount(1, $result);

        $element = $result->current();

        $this->assertEquals('foobar', $element->textContent);
    }

    public function testRenderBeforeEntriesWithAppend()
    {
        $submodelA = (new ViewModel())
            ->setTemplate('tests/postings/before-entries-a')
            ->setAppend(true);

        $submodelB = (new ViewModel())
            ->setTemplate('tests/postings/before-entries-b')
            ->setAppend(true);

        $this->model
            ->addChild($submodelA, 'beforeEntries')
            ->addChild($submodelB, 'beforeEntries');

        $content = $this->view->render($this->model);

        $result = (new Query($content))->execute('.before-entries');
        $this->assertCount(2, $result);

        $element = $result->current();
        $this->assertEquals('foobar', $element->textContent);

        $result->next();

        $element = $result->current();
        $this->assertEquals('foobaz', $element->textContent);
    }
}


text:
import { createSelector, Selector as Reselector} from "reselect";
import {RootState} from "../reducers/index";

export const getDeviceAvailableCapacity = (state: RootState) => state.device.device ? state.device.device.attributes.available_device_capacity : null;
export const getDeviceCapacity = (state: RootState) => state.device.device ? state.device.device.attributes.device_capacity : null;

export const getPercentCapacityUsed: Reselector<RootState, number> = createSelector(
    [getDeviceCapacity, getDeviceAvailableCapacity],
    (deviceCapacity: number = 0, availableCapacity: number = 0) => (deviceCapacity - availableCapacity)
);


text:
#include "../../include/babcode.h"

#include <windows.h>
#include <stdio.h>

static uint32_t getComPortNumber(const char *portcom)
{
	uint32_t i,j;
	char buffer[4];
    int32_t port;

	i=0;
	while(portcom[i]!='M')
	{
		i++;
	}
	i++;

	j=0;
	while(portcom[i]!=0)
	{
		buffer[j] = portcom[i];
		j++;
		i++;
	}

	buffer[j] = 0;

	stringToInt(buffer,&port);

	return port;
}

uint32_t initUART(Uart * uart, const char * name, uint32_t baudrate)
{
    HANDLE hCom ;

	uint32_t comport;
	DCB dcb_structure;
	COMMTIMEOUTS commtimeouts;

	char port[24];

	comport = getComPortNumber(name);

	sprintf(port,"\\\\.\\COM%d",comport);

	hCom=CreateFileA(port,GENERIC_WRITE|GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);

	if(hCom == INVALID_HANDLE_VALUE)
	{
		return UART_OPEN_FAILED ;
	}

	GetCommState (hCom,&dcb_structure);

	//configuration du port
	dcb_structure.BaudRate=baudrate ; //115200;
	dcb_structure.ByteSize=8;
	dcb_structure.StopBits=ONESTOPBIT;
	dcb_structure.Parity=NOPARITY;
	dcb_structure.fDtrControl=DTR_CONTROL_DISABLE;
	dcb_structure.fRtsControl=RTS_CONTROL_DISABLE ;
	dcb_structure.fOutxCtsFlow =FALSE;
	dcb_structure.fOutxDsrFlow =FALSE;

	if( SetCommState (hCom,&dcb_structure) == 0 )
	{
		return UART_CONF_FAILED ;
	}

	commtimeouts.ReadIntervalTimeout         =MAXDWORD;
    commtimeouts.ReadTotalTimeoutMultiplier  =0;
    commtimeouts.ReadTotalTimeoutConstant    =1;
    commtimeouts.WriteTotalTimeoutMultiplier =0;
    commtimeouts.WriteTotalTimeoutConstant   =0;
    SetCommTimeouts(hCom, &commtimeouts);

	PurgeComm(hCom,PURGE_TXCLEAR | PURGE_RXCLEAR | PURGE_TXABORT  | PURGE_TXABORT );

    uart->handle = hCom;

	return UART_OK ;
}

uint32_t sendBufferToUART (Uart * uart, const uint8_t *Buffer, uint32_t Count)
{
	unsigned long buffer;
//	FlushFileBuffers(hCom);
	if (!WriteFile(uart->handle,Buffer,Count,&buffer,NULL))
	{
		return UART_WRITE_FAILED;
	}
	FlushFileBuffers(uart->handle);
	return UART_OK;
}

uint32_t sendByteToUART(Uart * uart, uint8_t byte)
{
	unsigned long buffer;
//	FlushFileBuffers(hCom);
	if (!WriteFile(uart->handle,&byte,1,&buffer,NULL))
	{
		return UART_WRITE_FAILED;
	}
	FlushFileBuffers(uart->handle);
	return UART_OK;
}

uint32_t getByteFromUART (Uart * uart, uint8_t *Val)
{
	unsigned long buffer;

	if(ReadFile(uart->handle,Val,1,&buffer,NULL)==0)
	{
		return UART_READ_FAILED;
	}
//	FlushFileBuffers(hCom);
	return UART_OK;
}

uint32_t getByteFromUARTNoWait(Uart * uart, uint8_t *mot)
{
	unsigned long len=0;
	unsigned long time=0;

	do
	{
		ReadFile (uart->handle,mot,1,&len,NULL);
		if (!len) time++;

		if (time>50) return UART_TIMEOUT_ERROR;

	}while(!len);

	return UART_OK;
}

uint32_t getBufferFromUART (Uart * uart, uint8_t *Buffer,uint32_t Count)
{
	unsigned long buffer;
	if(ReadFile(uart->handle,Buffer,Count,&buffer,NULL)==0)
	{
		return UART_READ_FAILED;
	}

//	FlushFileBuffers(hCom);

	return UART_OK;
}

void closeUART(Uart * uart)
{
	CloseHandle(uart->handle);
}


text:
require 'uri'
require './lib/utilities'

class PropertyValue
  # attr_accessor :content,:attributes
  attr_reader :content,:attributes

  def initialize(element)
    @attributes = Hash.new
    @content = element.content
    element.attributes.each do |attribute|
      @attributes[attribute.name] = attribute.value
    end
  end

  def get_attribute_value(attribute_name)
    return @attributes[attribute_name]
  end
end

class ValidationError
  attr_accessor :property_name, :error_type, :message, :severity

  def initialize(property_name, error_type, message,severity)
    @property_name = property_name
    @error_type = error_type
    @message = message
    @severity = severity
  end
end

class PropertyDataSet
  attr_reader :values,:errors

  def initialize
    @values = Array.new
    @errors = Array.new
  end

  def add_value(value)
    @values << value
  end

  def add_validation_error(error)
    @errors << error
  end

  def valid?
    return(@errors.count == 0)
  end

  def simple_values_as_array
    string_array = []
    @values.each do |value|
      string_array << value.content
    end
    return string_array
  end
end

class BaseProperty
  attr_reader :name,:min,:max,:data

  def initialize(args)
    @valid = false
    @min = args['min']
    @max = args['max']
    @name = args['name']
  end
end

class RioxxBaseProperty < BaseProperty
  RIOXX_NAMESPACES = ['rioxx:http://www.rioxx.net/schema/v2.0/rioxx/','dc:http://purl.org/dc/elements/1.1/','dcterms:http://purl.org/dc/terms/','rioxxterms:http://docs.rioxx.net/schema/v2.0/rioxxterms/','ali:http://ali.niso.org/2014/ali/1.0']

  def validate(xml)
    data = PropertyDataSet.new
    if @max == 1 then
      element = find_property_elements_in_xml("//record/metadata/rioxx:rioxx/#{@name}",RIOXX_NAMESPACES,xml,false)
      if element then
        data.add_value(PropertyValue.new(element))
      end
    else
      find_property_elements_in_xml("//record/metadata/rioxx:rioxx/#{@name}",RIOXX_NAMESPACES,xml,true).each do |element|
        if element then
          data.add_value(PropertyValue.new(element))
        end
      end
    end
    if(data.values.length < @min) then
      data.add_validation_error(ValidationError.new(@name, :TOO_FEW_VALUES, "Minimum of #{@min} value(s) required for #{@name} - found #{data.values.length} values",:ERROR))
    end
    if (@max != nil && data.values.length > @max) then
      data.add_validation_error(ValidationError.new(@name, :TOO_MANY_VALUES, "Maximum of #{@max} value(s) required for #{@name} - found #{data.values.length} values",:ERROR))
    end
    return data
  end
end

class RioxxStringProperty < RioxxBaseProperty
  def validate(xml)
    data = super(xml)
    if !(check_all_strings_exist(data.simple_values_as_array)) then
      data.add_validation_error(ValidationError.new(@name, :EMPTY_STRING_VALUES, "Empty string value(s) found in #{@name}",:ERROR))
    end
    return data
  end
end

class RioxxHttpUriStringProperty < RioxxStringProperty
  def validate(xml)
    data = super(xml)
    data.values.each do |value|
      if(!check_string_is_http_uri(value.content)) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_HTTP_URI, "'#{value.content}' is not a valid HTTP URI in #{@name}",:ERROR))
      end
    end
    return data
  end
end

class RioxxDateStringProperty < RioxxStringProperty
  def validate(xml)
    data = super(xml)
    data.values.each do |value|
      if(!check_string_is_iso8601_date(value.content)) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_ISO8601_DATE, "'#{value}' is not in valid ISO8601 ('yyyy-mm-dd') format in #{@name}",:ERROR))
      end
    end
    return data
  end
end

class RioxxMimeStringProperty < RioxxStringProperty
  def validate(xml)
    data = super(xml)
    data.values.each do |value|
      if(!check_string_is_mime_type(value.content)) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_MIME_TYPE, "This is not a recognised MIME Type in #{@name}",:WARN))
      end
    end
    return data
  end
end

class RioxxLanguageStringProperty < RioxxStringProperty
  def validate(xml)
    data = super(xml)
    data.values.each do |value|
      if(!check_string_is_iso639_3_language_code(value.content)) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_ISO639_3_LANGUAGE_CODE, "'#{value}' is not a recognised ISO639-3 language code in #{@name}",:WARN))
      end
    end
    return data
  end
end

class RioxxFreeToReadProperty < RioxxBaseProperty
  def initialize(args)
    super({'min' => args['min'],'max' => args['max'], 'name' => 'ali:free-to-read'})
  end

  def validate(xml)
    data = super(xml)
    data.values.each do |value|
      if value.get_attribute_value('start_date')!=nil && !check_string_is_iso8601_date(value.get_attribute_value('start_date')) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_ISO8601_DATE, "'#{value.get_attribute_value('start_date')}' in the 'start_date' attribute is not in valid ISO8601 ('yyyy-mm-dd') format in #{@name}",:ERROR))
      end
      if value.get_attribute_value('end_date')!=nil && !check_string_is_iso8601_date(value.get_attribute_value('end_date')) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_ISO8601_DATE, "'#{value.get_attribute_value('end_date')}' in the 'end_date' attribute is not in valid ISO8601 ('yyyy-mm-dd') format in #{@name}",:ERROR))
      end
    end
    return data
  end
end

class RioxxLicenseRefProperty < RioxxBaseProperty
  def initialize(args)
    super({'min' => args['min'],'max' => args['max'], 'name' => 'ali:license_ref'})
  end

  def validate(xml)
    data = super(xml)
    data.values.each do |value|
      if value.content==nil || !check_string_is_http_uri(value.content) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_HTTP_URI, "'#{value.content}' is not a valid HTTP URI in #{@name}",:ERROR))
      end
      if value.get_attribute_value('start_date')!=nil && !check_string_is_iso8601_date(value.get_attribute_value('start_date')) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_ISO8601_DATE, "'#{value.get_attribute_value('start_date')}' in the 'start_date' attribute is not in valid ISO8601 ('yyyy-mm-dd') format in #{@name}",:ERROR))
      end
    end
    return data
  end
end

class RioxxPartyProperty < RioxxBaseProperty
  def validate(xml)
    data = super(xml)
    data.values.each do |value|
      if value.get_attribute_value('id') != nil && !check_string_is_http_uri(value.get_attribute_value('id')) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_HTTP_URI, "'#{value.get_attribute_value('id')}' in the 'id' attribute is not a valid HTTP URI in #{@name}",:ERROR))
      end
      if !check_string_exists(value.content) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_NAME, "'#{value.content}' is not a valid name in #{@name}",:WARN))
      end
    end
    return data
  end
end

class RioxxProjectProperty < RioxxBaseProperty
  def initialize(args)
    super({'min' => args['min'],'max' => args['max'], 'name' => 'rioxxterms:project'})
  end

  def validate(xml)
    data = super(xml)
    data.values.each do |value|
      if value.get_attribute_value('funder_name') != nil && !check_string_exists(value.get_attribute_value('funder_name')) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_NAME, "'#{value.get_attribute_value('funder_name')}' is not a valid name in #{@name}",:WARN))
      end
      if value.get_attribute_value('funder_id') != nil && !check_string_is_http_uri(value.get_attribute_value('funder_id')) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_HTTP_URI, "'#{value.get_attribute_value('funder_id')}' in the 'funder_id' attributeis not a valid HTTP URI in #{@name}",:ERROR))
      end
      if (value.get_attribute_value('funder_name') == nil && value.get_attribute_value('funder_id') == nil) then
        data.add_validation_error(ValidationError.new(@name, :MISSING_VALUE, "One or both of the attributes 'funder_name' or 'funder_id' must be present in #{@name}",:ERROR))
      end
      if !check_string_exists(value.content) then
        data.add_validation_error(ValidationError.new(@name, :MISSING_VALUE, "'#{value.content}' is not a valid project_id in #{@name}",:ERROR))
      end
    end
    return data
  end
end

class RioxxApcProperty < RioxxBaseProperty
  APC_VOCAB = ['paid','partially waived','fully waived','not charged','not required','unknown'].map(&:downcase)
  def initialize(args)
    super({'min' => args['min'],'max' => args['max'], 'name' => 'rioxxterms:apc'})
  end

  def validate(xml)
    data = super(xml)
    data.values.each do |value|
      if(!APC_VOCAB.include?(value.content.downcase)) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_TERM, "'#{value.content}' is not a valid term from the RIOXX APC vocabulary in #{@name}",:WARN))
      end
    end
    return data
  end
end

class RioxxItemTypeProperty < RioxxBaseProperty
  ITEM_TYPE_VOCAB = ['Book','Book chapter','Book edited','Conference Paper/Proceeding/Abstract','Journal Article/Review','Manual/Guide','Monograph','Policy briefing report','Technical Report','Technical Standard','Thesis','Other','Consultancy Report','Working paper'].map(&:downcase)

  def initialize(args)
    super({'min' => args['min'],'max' => args['max'], 'name' => 'rioxxterms:type'})
  end

  def validate(xml)
    data = super(xml)
    data.values.each do |value|
      if(!ITEM_TYPE_VOCAB.include?(value.content.downcase)) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_TERM, "'#{value.content}' is not a valid term from the RIOXX Item-type vocabulary in #{@name}",:WARN))
      end
    end
    return data
  end
end

class RioxxVersionProperty < RioxxBaseProperty
  VERSION_VOCAB = ['AO','SMUR','AM','P','VoR','CVoR','EVoR','NA'].map(&:downcase)

  def initialize(args)
    super({'min' => args['min'],'max' => args['max'], 'name' => 'rioxxterms:version'})
  end

  def validate(xml)
    data = super(xml)
    data.values.each do |value|
      if(!VERSION_VOCAB.include?(value.content.downcase)) then
        data.add_validation_error(ValidationError.new(@name, :INVALID_TERM, "'#{value.content}' is not a valid term from the RIOXX Versions vocabulary in #{@name}",:WARN))
      end
    end
    return data
  end
end


text:
import sys
from m5.params import *
from m5.proxy import *
from Device import DmaDevice
from AbstractNVM import *

class UFSHostDevice(DmaDevice):
    type = 'UFSHostDevice'
    cxx_header = "dev/arm/ufs_device.hh"
    pio_addr = Param.Addr("Address for SCSI configuration slave interface")
    pio_latency = Param.Latency("10ns", "Time between action and write/read \
       result by AMBA DMA Device")
    gic = Param.BaseGic(Parent.any, "Gic to use for interrupting")
    int_num = Param.UInt32("Interrupt number that connects to GIC")
    img_blk_size = Param.UInt32(512, "Size of one image block in bytes")
    # Every image that is added to the vector will generate a new logic unit
    # in the UFS device; Theoretically (when using the driver from Linux
    # kernel 3.9 onwards), this can be as many as eigth. Up to two have been
    # tested.
    image = VectorParam.DiskImage("Disk images")
    # Every logic unit can have its own flash dimensions. So the number of
    # images that have been provided in the image vector, should be equal to
    # the number of flash objects that are created. Each logic unit can have
    # its own flash dimensions; to allow the system to define a hetrogeneous
    # storage system.
    internalflash = VectorParam.AbstractNVM("Describes the internal flash")
    ufs_slots = Param.UInt32(32, "Number of commands that can be queued in \
        the Host controller (min: 1, max: 32)")


text:
from django_google_charts.utils import OptionsDict

def test_dot_access():
    key, value = 'key', 'value'
    options = OptionsDict({key: value})

    assert options.key == value

    options2 = OptionsDict()
    options2.key = value

    assert options2.key == value

def test_options_equality():
    options = OptionsDict({'key1': 'value', 'key2': 3})
    test = {'key1': 'value', 'key2': 3}

    assert options == test

def test_adding_dict():
    value = 'value'
    options = OptionsDict()

    options.x = {}
    options.x.y = value

    assert options.x.y == value

def test_options_inherit():
    options = OptionsDict({'overridden': 1, 'kept': 1})
    suboptions = OptionsDict({'overridden': 2, 'new': 1})

    suboptions.inherit(options)

    assert suboptions == {
        'overridden': 2,
        'new': 1,
        'kept': 1,
    }

def test_options_recursive_inherit():
    options = OptionsDict({
        'key': {
            'subkey': {'subsubkey': 2},
        },
    })

    options.inherit(OptionsDict({
        'key': {
            'subkey': {'subsubkey': 1},
            'kept': 1,
        },
    }))

    assert options == {
        'key': {
            'subkey': {'subsubkey': 2},
            'kept': 1,
        },
    }


text:
package com.devicehive.websockets.util;

import com.devicehive.json.GsonFactory;
import com.devicehive.websockets.HiveWebsocketSessionState;
import com.google.gson.JsonElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;

@Component
public class AsyncMessageSupplier {
    private static final Logger logger = LoggerFactory.getLogger(AsyncMessageSupplier.class);

    public void deliverMessages(WebSocketSession session) {
        ConcurrentLinkedQueue<JsonElement> queue = HiveWebsocketSessionState.get(session).getQueue();
        boolean acquired = false;
        try {
            acquired = HiveWebsocketSessionState.get(session).getQueueLock().tryLock();
            if (acquired) {
                while (!queue.isEmpty()) {
                    JsonElement jsonElement = queue.peek();
                    if (jsonElement == null) {
                        queue.poll();
                        continue;
                    }
                    if (session.isOpen()) {
                        String data = GsonFactory.createGson().toJson(jsonElement);
                        session.sendMessage(new TextMessage(data));
                        queue.poll();
                    } else {
                        logger.error("Session is closed. Unable to deliver message");
                        queue.clear();
                        return;
                    }
                    logger.debug("Session {}: {} messages left", session.getId(), queue.size());
                }
            }
        } catch (IOException e) {
            logger.error("Unexpected exception", e);
            throw new RuntimeException(e);
        } finally {
            if (acquired) {
                HiveWebsocketSessionState.get(session).getQueueLock().unlock();
            }
        }
    }

}


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

namespace _02.ChangeList
{
    class ChangeList
    {
        static void Main()
        {
            List<int> numbers = Console.ReadLine()
                .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(int.Parse)
                .ToList();

            string command = Console.ReadLine().ToLower();

            while (command != "odd" && command != "even")
            {
                string[] tokens = command.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                int element = int.Parse(tokens[1]);

                switch (tokens[0])
                {
                    case "delete":
                        DeleteElements(numbers, element);
                        break;
                    case "insert":
                        int index = int.Parse(tokens[2]);
                        numbers.Insert(index, element);
                        break;
                }

                command = Console.ReadLine().ToLower();
            }

            if (command == "odd")
            {
                numbers =
                    numbers.Where(n => n % 2 != 0)
                    .ToList();
            }
            else if (command == "even")
            {
                numbers =
                    numbers.Where(n => n % 2 == 0)
                    .ToList();
            }

            Console.WriteLine(string.Join(" ", numbers));
        }

        private static void DeleteElements(List<int> numbers, int element)
        {
            for (int i = 0; i < numbers.Count; i++)
            {
                if (numbers[i] == element)
                {
                    numbers.RemoveAt(i);
                    i--;
                }
            }
        }
    }
}


text:
// Creates and injects the remove friend button
// @param playerID ID of the player to remove
// @param targetID ID of the page element target location
function createRemoveFriendForm(playerID, targetID) {

    // Ensure we have a target location to append to
    if (targetID == null) {
        console.log("Friend Forms must have a targetID");
        return;
    }

    var tID = document.getElementById(targetID);
    $(tID).empty();

    // Build the form
    var form = document.createElement("form");
    $(form).addClass("remove-friend-form").attr("action", "/Players/RemoveFriend").attr("method", "post").append(
        "<input type=\"hidden\" name=\"id\" value=\"" + playerID + "\" /><button type=\"submit\" class=\"expand flip-text remove-friend\">You are friendsRemove Friend</button>"
    );

    // Bind submission to submit with ajax
    $(form).submit(function (e) {
        e.preventDefault();

        $(form).ajaxSubmit({
            clearForm: false,
            success: function (responseObj) {
                createAddFriendForm(playerID, targetID);
            },
            error: function () {
                alert("Friend removal failed. Please try again later.");
            }
        });
    });

    // Add form to target
    $(tID).append(form);
}

// Creates and injects the add friend button
// @param playerID ID of the player to add
// @param targetID ID of the page element target location
function createAddFriendForm(playerID, targetID) {

    if (targetID == null) {
        console.log("Friend Forms must have a targetID");
        return;
    }

    var tID = document.getElementById(targetID);
    $(tID).empty();

    var form = document.createElement("form");
    $(form).addClass("add-friend-form").attr("action", "/Players/AddFriend").attr("method", "post").append(
        "<input type=\"hidden\" name=\"id\" value=\"" + playerID + "\" /><button type=\"submit\" class=\"expand add-friend\">Add Friend</button>"
    );

    $(form).submit(function (e) {
        e.preventDefault();

        $(form).ajaxSubmit({
            clearForm: false,
            success: function (responseObj) {
                createPendingFriendButton(targetID);
            },
            error: function () {
                alert("Friend addition failed. Please try again later.");
            }
        });
    });

    // Add form to target
    $(tID).append(form);
}

// Creates and injects the pending friend response forms
// @param playerID ID of the player to update
// @param targetID ID of the page element target location
// @param inline Bool to flip display mode to inline. Used for notification view.
function createPendingFriendResponseForm(playerID, targetID, inline) {

    if (targetID == null) {
        console.log("Friend Forms must have a targetID");
        return;
    }

    var tID = document.getElementById(targetID);
    //$(tID).empty();

    var form1 = document.createElement("form");
    $(form1).addClass("accept-friend-form").attr("action", "/Players/AcceptFriendRequest").attr("method", "post").append(
        "<input type=\"hidden\" name=\"id\" value=\"" + playerID + "\" /><input type=\"submit\" value=\"Accept\" class=\"button save " + (inline ? "inline-block" : "expand") + "\" />"
    );
    if (inline) $(form1).addClass("inline-block");

    var form2 = document.createElement("form");
    $(form2).addClass("ignore-friend-form").attr("action", "/Players/IgnoreFriendRequest").attr("method", "post").append(
        "<input type=\"hidden\" name=\"id\" value=\"" + playerID + "\" /><input type=\"submit\" value=\"Ignore\" class=\"button cancel " + (inline ? "inline-block" : "expand") + "\" />"
    );
    if (inline) $(form2).addClass("inline-block");

    var form3 = document.createElement("form");
    $(form3).addClass("decline-friend-form").attr("action", "/Players/DeclineFriendRequest").attr("method", "post").append(
        "<input type=\"hidden\" name=\"id\" value=\"" + playerID + "\" /><input type=\"submit\" value=\"Decline\" class=\"button cancel " + (inline ? "inline-block" : "expand") + "\" />"
    );
    if (inline) $(form3).addClass("inline-block");

    $(form1).submit(function (e) {
        e.preventDefault();

        $(form1).ajaxSubmit({
            clearForm: false,
            success: function (responseObj) {
                if (inline) {
                    $(tID).remove();
                }
                else {
                    createRemoveFriendForm(playerID, targetID);
                }
            },
            error: function () {
                alert("Friend response failed. Please try again later.");
            }
        });
    });

    $(form2).submit(function (e) {
        e.preventDefault();

        $(form2).ajaxSubmit({
            clearForm: false,
            success: function (responseObj) {
                if (inline) {
                    $(tID).remove();
                }
                else {
                    createAddFriendForm(playerID, targetID);
                }
            },
            error: function () {
                alert("Friend response failed. Please try again later.");
            }
        });
    });

    $(form3).submit(function (e) {
        e.preventDefault();

        $(form3).ajaxSubmit({
            clearForm: false,
            success: function (responseObj) {

                if (inline) {
                    $(tID).remove();
                }
                else {
                    createAddFriendForm(playerID, targetID);
                }
            },
            error: function () {
                alert("Friend response failed. Please try again later.");
            }
        });
    });

    // Add forms to target
    $(tID).append(form1);
    $(tID).append(form2);
    $(tID).append(form3);
}

// Creates and injects the pending friend button
// @param targetID ID of the page element target location
function createPendingFriendButton(targetID) {

    if (targetID == null) {
        console.log("Friend Forms must have a targetID");
        return;
    }

    var tID = document.getElementById(targetID);
    $(tID).empty();

    var button = document.createElement("button");
    $(button).addClass("expand disabled").append("Friend Request Sent");

    // Add button to target
    $(tID).append(button);
}

$(document).ready(function () {

    /***************************
        SITE-WIDE FEATURES
    ***************************/

    FastClick.attach(document.body);

    // NAVIGATION DROPDOWNS

    var activeDropdownId = "";
    var activeDropdownButton = null;

    var updateArrowPosition = function () {
        // Update position of navigation dropdown arrow on page resize.
        if (activeDropdownButton != null) {
            var width = activeDropdownButton.parent().width();
            var left = activeDropdownButton.parent().position().left;
            var center = left + (width / 2);
            $('#navigation-dropdown-arrow').css('left', center);
        }
    }

    var exitCurrentDropdown = function () {
        $('#' + activeDropdownId).toggleClass('active', false);
        $('[data-dropdownid="' + activeDropdownId + '"]').toggleClass('active', false);
        activeDropdownId = "";
    }

    var exitEveryDropdownElement = function () {
        exitCurrentDropdown();
        $('#navigation-dropdown-arrow').toggleClass('active', false);
        activeDropdownButton = null;
    }

    $(window).resize(function () {
        updateArrowPosition();
    });

    $('body').click(function (e) {

        // Click on dropdown, do nothing
        if ($(e.target).closest('.dropdown-menu').length > 0 || $(e.target).closest('.up-arrow').length > 0 || $(e.target).closest('#nav-menu').length > 0)
        {
            return;
        }

        // Click on dropdown button
        if ($(e.target).closest('[data-dropdownid]').length > 0)
        {
            activeDropdownButton = $(e.target).closest('[data-dropdownid]');
            var targetId = activeDropdownButton.data('dropdownid');

            e.preventDefault();

            $('#' + targetId).toggleClass('active');
            $('#navigation-dropdown-arrow').toggleClass('active');
            if (targetId == 'nav-menu') {
                $('#navigation-dropdown-arrow').toggleClass('dark', true);
            }
            else {
                $('#navigation-dropdown-arrow').toggleClass('dark', false);
            }

            // Exit dropdown
            if (targetId == activeDropdownId) {
                exitCurrentDropdown();
            }
            else {
                exitCurrentDropdown();

                $('#navigation-dropdown-arrow').toggleClass('active', true);
                activeDropdownId = targetId;

                // Activate button
                $('[data-dropdownid="' + activeDropdownId + '"]').toggleClass('active', true);

                updateArrowPosition();
            }

            return;
        }

        // Click anywhere else, exit dropdown
        exitEveryDropdownElement();
    });

    // END NAVIGATION DROPDOWNS

    // SCROLL BOXES

    $('.scroll').slimScroll();

    $('.dropdownScroll').slimScroll({
        height: '250px',
        size: '6px',
        position: 'right',
        color: '#000',
        alwaysVisible: false,
        distance: '1px',
        railVisible: false,
        railDraggable: true,
        railColor: '#222',
        railOpacity: 0.3,
        wheelStep: 10,
        allowPageScroll: false,
        disableFadeOut: false
    });

});


text:
namespace System.ServiceModel {
  public class BasicHttpBinding : HttpBindingBase {
    public BasicHttpBinding();
    public BasicHttpBinding(BasicHttpSecurityMode securityMode);
    public BasicHttpSecurity Security { get; set; }
    public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingParameterCollection parameters);
    public override BindingElementCollection CreateBindingElements();
  }
  public enum BasicHttpMessageCredentialType {
    Certificate = 1,
    UserName = 0,
  }
  public sealed class BasicHttpSecurity {
    public BasicHttpSecurityMode Mode { get; set; }
    public HttpTransportSecurity Transport { get; set; }
  }
  public enum BasicHttpSecurityMode {
    Message = 2,
    None = 0,
    Transport = 1,
    TransportCredentialOnly = 4,
    TransportWithMessageCredential = 3,
  }
  public abstract class HttpBindingBase : Binding {
    public bool AllowCookies { get; set; }
    public EnvelopeVersion EnvelopeVersion { get; }
    public long MaxBufferPoolSize { get; set; }
    public int MaxBufferSize { get; set; }
    public long MaxReceivedMessageSize { get; set; }
    public XmlDictionaryReaderQuotas ReaderQuotas { get; set; }
    public override string Scheme { get; }
    public Encoding TextEncoding { get; set; }
    public TransferMode TransferMode { get; set; }
  }
  public enum HttpClientCredentialType {
    Basic = 1,
    Certificate = 5,
    Digest = 2,
    InheritedFromHost = 6,
    None = 0,
    Ntlm = 3,
    Windows = 4,
  }
  public sealed class HttpTransportSecurity {
    public HttpTransportSecurity();
    public HttpClientCredentialType ClientCredentialType { get; set; }
  }
  public class NetHttpBinding : HttpBindingBase {
    public NetHttpBinding();
    public NetHttpBinding(BasicHttpSecurityMode securityMode);
    public NetHttpBinding(string configurationName);
    public NetHttpMessageEncoding MessageEncoding { get; set; }
    public BasicHttpSecurity Security { get; set; }
    public WebSocketTransportSettings WebSocketSettings { get; }
    public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingParameterCollection parameters);
    public override BindingElementCollection CreateBindingElements();
  }
  public enum NetHttpMessageEncoding {
    Binary = 0,
    Mtom = 2,
    Text = 1,
  }
}
namespace System.ServiceModel.Channels {
  public sealed class HttpRequestMessageProperty : IMessageProperty {
    public HttpRequestMessageProperty();
    public WebHeaderCollection Headers { get; }
    public string Method { get; set; }
    public static string Name { get; }
    public string QueryString { get; set; }
    public bool SuppressEntityBody { get; set; }
    IMessageProperty System.ServiceModel.Channels.IMessageProperty.CreateCopy();
  }
  public sealed class HttpResponseMessageProperty : IMessageProperty {
    public HttpResponseMessageProperty();
    public WebHeaderCollection Headers { get; }
    public static string Name { get; }
    public HttpStatusCode StatusCode { get; set; }
    public string StatusDescription { get; set; }
    IMessageProperty System.ServiceModel.Channels.IMessageProperty.CreateCopy();
  }
  public class HttpsTransportBindingElement : HttpTransportBindingElement {
    public HttpsTransportBindingElement();
    protected HttpsTransportBindingElement(HttpsTransportBindingElement elementToBeCloned);
    public override string Scheme { get; }
    public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context);
    public override BindingElement Clone();
    public override T GetProperty<T>(BindingContext context);
  }
  public class HttpTransportBindingElement : TransportBindingElement {
    public HttpTransportBindingElement();
    protected HttpTransportBindingElement(HttpTransportBindingElement elementToBeCloned);
    public bool AllowCookies { get; set; }
    public AuthenticationSchemes AuthenticationScheme { get; set; }
    public int MaxBufferSize { get; set; }
    public override string Scheme { get; }
    public TransferMode TransferMode { get; set; }
    public WebSocketTransportSettings WebSocketSettings { get; set; }
    public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context);
    public override bool CanBuildChannelFactory<TChannel>(BindingContext context);
    public override BindingElement Clone();
    public override T GetProperty<T>(BindingContext context);
  }
  public interface IHttpCookieContainerManager {
    CookieContainer CookieContainer { get; set; }
  }
  public sealed class WebSocketTransportSettings : IEquatable<WebSocketTransportSettings> {
    public const string BinaryMessageReceivedAction = "http://schemas.microsoft.com/2011/02/websockets/onbinarymessage";
    public const string TextMessageReceivedAction = "http://schemas.microsoft.com/2011/02/websockets/ontextmessage";
    public WebSocketTransportSettings();
    public bool DisablePayloadMasking { get; set; }
    public TimeSpan KeepAliveInterval { get; set; }
    public string SubProtocol { get; set; }
    public WebSocketTransportUsage TransportUsage { get; set; }
    public override bool Equals(object obj);
    public bool Equals(WebSocketTransportSettings other);
    public override int GetHashCode();
  }
  public enum WebSocketTransportUsage {
    Always = 1,
    Never = 2,
    WhenDuplex = 0,
  }
}


text:
namespace Generators.Exercises
{
    // This class derives from CustomExercise instead of GeneratorExercise
    // as it has custom (property-based) tests that cannot be generated from
    // the canonical data.
    public class Diamond : CustomExercise
    {
    }
}


text:
package com.ssm.business.entity;

import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;

@Repository
public class Item implements Serializable {
    private Integer itemId;

    private Integer modelId;

    private String sourceTabel;

    private String sourceField;

    private String targetTable;

    private String targetField;

    private Integer state;

    private List<Item> list;

    public Integer getItemId() {
        return itemId;
    }

    public void setItemId(Integer itemId) {
        this.itemId = itemId;
    }

    public Integer getModelId() {
        return modelId;
    }

    public void setModelId(Integer modelId) {
        this.modelId = modelId;
    }

    public String getSourceTabel() {
        return sourceTabel;
    }

    public void setSourceTabel(String sourceTabel) {
        this.sourceTabel = sourceTabel == null ? null : sourceTabel.trim();
    }

    public String getSourceField() {
        return sourceField;
    }

    public void setSourceField(String sourceField) {
        this.sourceField = sourceField == null ? null : sourceField.trim();
    }

    public String getTargetTable() {
        return targetTable;
    }

    public void setTargetTable(String targetTable) {
        this.targetTable = targetTable == null ? null : targetTable.trim();
    }

    public String getTargetField() {
        return targetField;
    }

    public void setTargetField(String targetField) {
        this.targetField = targetField == null ? null : targetField.trim();
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public List<Item> getList() {
        return list;
    }

    public void setList(List<Item> list) {
        this.list = list;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>CivilOctave: /home/amarjeet/projects/CivilOctave/sage/Documentation Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

CivilOctave

Main Page

Related Pages

Packages

Files

sage

Documentation

Documentation Directory Reference

Directory dependency graph for Documentation:

<map name="dir__4cdd81784b34ba95d24c7e234b2e59dc__dep" id="dir__4cdd81784b34ba95d24c7e234b2e59dc__dep">
<area shape="rect" id="node2" href="dir_510ddf435370c081b45f7ee50457ba8b.html" title="html" alt="" coords="37,63,109,111"/>
<area shape="rect" id="clust2" href="dir_4cdd81784b34ba95d24c7e234b2e59dc.html" alt="" coords="27,52,256,121"/>
<area shape="rect" id="clust1" href="dir_6e8a3169b25775527f7335bcb1517fad.html" title="sage" alt="" coords="16,16,267,132"/>
</map>

Directories

directory  	html

<address class="footer">
Generated on Thu Dec 17 2015 19:42:29 for CivilOctave by

 1.8.11
</address>


text:
from django.urls import path

from .views import createPaypalPayment, executePaypalPayment

urlpatterns = [
    path('create_payment/', createPaypalPayment, name='createPaypalPayment'),
    path('execute_payment/', executePaypalPayment, name='executePaypalPayment'),
]


text:
public class Trie<V> {
	private final int alphabetSize;
	private final Node root;

	private static class Node {
		Object value;
		Node[] children;

		Node(int alphabetSize) {
			this.children = new Node[alphabetSize];
		}
	}

	public Trie(int alphabetSize) {
		this.alphabetSize = alphabetSize;
		this.root = new Node(alphabetSize);
	}

	public V put(String key, V value) {
		int n = key.length();
		int i = 0;
		Node node = this.root;
		while (i < n) {
			char c = key.charAt(i);
			assert c < alphabetSize;
			if (node.children[c] == null) {
				node.children[c] = new Node(alphabetSize);
			}
			node = node.children[c];
			i++;
		}
		@SuppressWarnings("unchecked")
		V ret = (V)node.value;
		node.value = value;
		return ret;
	}

	public V get(String key) {
		int n = key.length();
		int i = 0;
		Node node = this.root;
		while (i < n) {
			char c = key.charAt(i);
			assert c < alphabetSize;
			if (node.children[c] == null) {
				break;
			}
			node = node.children[c];
			i++;
		}
		if (i == n) {
			@SuppressWarnings("unchecked")
			V ret = (V)node.value;
			return ret;
		}
		return null;
	}

	public boolean hasPrefix(String key) {
		int n = key.length();
		int i = 0;
		Node node = this.root;
		while (i < n) {
			char c = key.charAt(i);
			assert c < alphabetSize;
			if (node.children[c] == null) {
				return false;
			}
			node = node.children[c];
			i++;
		}
		return true;
	}
}


text:
from logstash.formatter import LogstashFormatterVersion1
from copy import copy
import json
import time
import logging

import six

from django.conf import settings

class TimeFormatter(logging.Formatter):
    '''
    Custom log formatter used for inventory imports
    '''
    def format(self, record):
        record.relativeSeconds = record.relativeCreated / 1000.0
        return logging.Formatter.format(self, record)

class LogstashFormatter(LogstashFormatterVersion1):

    def reformat_data_for_log(self, raw_data, kind=None):
        '''
        Process dictionaries from various contexts (job events, activity stream
        changes, etc.) to give meaningful information
        Output a dictionary which will be passed in logstash or syslog format
        to the logging receiver
        '''
        if kind == 'activity_stream':
            try:
                raw_data['changes'] = json.loads(raw_data.get('changes', '{}'))
            except Exception:
                pass  # best effort here, if it's not valid JSON, then meh
            return raw_data
        elif kind == 'system_tracking':
            data = copy(raw_data['ansible_facts'])
        else:
            data = copy(raw_data)
        if isinstance(data, six.string_types):
            data = json.loads(data)
        data_for_log = {}

        def index_by_name(alist):
            """Takes a list of dictionaries with `name` as a key in each dict
            and returns a dictionary indexed by those names"""
            adict = {}
            for item in alist:
                subdict = copy(item)
                if 'name' in subdict:
                    name = subdict.get('name', None)
                elif 'path' in subdict:
                    name = subdict.get('path', None)
                if name:
                    # Logstash v2 can not accept '.' in a name
                    name = name.replace('.', '_')
                    adict[name] = subdict
            return adict

        def convert_to_type(t, val):
            if t is float:
                val = val[:-1] if val.endswith('s') else val
                try:
                    return float(val)
                except ValueError:
                    return val
            elif t is int:
                try:
                    return int(val)
                except ValueError:
                    return val
            elif t is str:
                return val

        if kind == 'job_events':
            job_event = raw_data['python_objects']['job_event']
            for field_object in job_event._meta.fields:

                if not field_object.__class__ or not field_object.__class__.__name__:
                    field_class_name = ''
                else:
                    field_class_name = field_object.__class__.__name__
                if field_class_name in ['ManyToOneRel', 'ManyToManyField']:
                    continue

                fd = field_object.name
                key = fd
                if field_class_name == 'ForeignKey':
                    fd = '{}_id'.format(field_object.name)

                try:
                    data_for_log[key] = getattr(job_event, fd)
                    if fd in ['created', 'modified'] and data_for_log[key] is not None:
                        time_float = time.mktime(data_for_log[key].timetuple())
                        data_for_log[key] = self.format_timestamp(time_float)
                except Exception as e:
                    data_for_log[key] = 'Exception `{}` producing field'.format(e)

            data_for_log['event_display'] = job_event.get_event_display2()

        elif kind == 'system_tracking':
            data.pop('ansible_python_version', None)
            if 'ansible_python' in data:
                data['ansible_python'].pop('version_info', None)

            data_for_log['ansible_facts'] = data
            data_for_log['ansible_facts_modified'] = raw_data['ansible_facts_modified']
            data_for_log['inventory_id'] = raw_data['inventory_id']
            data_for_log['host_name'] = raw_data['host_name']
            data_for_log['job_id'] = raw_data['job_id']
        elif kind == 'performance':
            request = raw_data['python_objects']['request']
            response = raw_data['python_objects']['response']

            # Note: All of the below keys may not be in the response "dict"
            # For example, X-API-Query-Time and X-API-Query-Count will only
            # exist if SQL_DEBUG is turned on in settings.
            headers = [
                (float, 'X-API-Time'),  # may end with an 's' "0.33s"
                (float, 'X-API-Total-Time'),
                (int, 'X-API-Query-Count'),
                (float, 'X-API-Query-Time'), # may also end with an 's'
                (str, 'X-API-Node'),
            ]
            data_for_log['x_api'] = {k: convert_to_type(t, response[k]) for (t, k) in headers if k in response}

            data_for_log['request'] = {
                'method': request.method,
                'path': request.path,
                'path_info': request.path_info,
                'query_string': request.META['QUERY_STRING'],
            }

            if hasattr(request, 'data'):
                data_for_log['request']['data'] = request.data

        return data_for_log

    def get_extra_fields(self, record):
        fields = super(LogstashFormatter, self).get_extra_fields(record)
        if record.name.startswith('awx.analytics'):
            log_kind = record.name[len('awx.analytics.'):]
            fields = self.reformat_data_for_log(fields, kind=log_kind)
        # General AWX metadata
        for log_name, setting_name in [
                ('type', 'LOG_AGGREGATOR_TYPE'),
                ('cluster_host_id', 'CLUSTER_HOST_ID'),
                ('tower_uuid', 'LOG_AGGREGATOR_TOWER_UUID')]:
            if hasattr(settings, setting_name):
                fields[log_name] = getattr(settings, setting_name, None)
            elif log_name == 'type':
                fields[log_name] = 'other'
        return fields

    def format(self, record):
        message = {
            # Fields not included, but exist in related logs
            # 'path': record.pathname
            # '@version': '1', # from python-logstash
            # 'tags': self.tags,
            '@timestamp': self.format_timestamp(record.created),
            'message': record.getMessage(),
            'host': self.host,

            # Extra Fields
            'level': record.levelname,
            'logger_name': record.name,
        }

        # Add extra fields
        message.update(self.get_extra_fields(record))

        # If exception, add debug info
        if record.exc_info:
            message.update(self.get_debug_fields(record))

        return self.serialize(message)


text:
echo Copying debug config (app.config.debug)
copy ..\..\app.config.debug OpBot.exe.config