text:
The 3.5.0 release includes features and fixes from a whopping 129 pull requests since 3.4.0.  This release removes a number of "experimental" features from the API, so take a close look at the notes below when upgrading.

## Upgrade notes

### `ol.Object` and `bindTo`

* The following experimental methods have been removed from `ol.Object`: `bindTo`, `unbind`, and `unbindAll`.  If you want to get notification about `ol.Object` property changes, you can listen for the `'propertychange'` event (e.g. `object.on('propertychange', listener)`).  Two-way binding can be set up at the application level using property change listeners.  See [#3472](https://github.com/openlayers/openlayers/pull/3472) for details on the change.

* The experimental `ol.dom.Input` component has been removed.  If you need to synchronize the state of a dom Input element with an `ol.Object`, this can be accomplished using listeners for change events.  For example, you might bind the state of a checkbox type input with a layer's visibility like this:

  ```js
  var layer = new ol.layer.Tile();
  var checkbox = document.querySelector('#checkbox');

  checkbox.addEventListener('change', function() {
    var checked = this.checked;
    if (checked !== layer.getVisible()) {
      layer.setVisible(checked);
    }
  });

  layer.on('change:visible', function() {
    var visible = this.getVisible();
    if (visible !== checkbox.checked) {
      checkbox.checked = visible;
    }
  });
  ```

### New Vector API

* The following experimental vector classes have been removed: `ol.source.GeoJSON`, `ol.source.GML`, `ol.source.GPX`, `ol.source.IGC`, `ol.source.KML`, `ol.source.OSMXML`, and `ol.source.TopoJSON`. You now will use `ol.source.Vector` instead.

  For example, if you used `ol.source.GeoJSON` as follows:

  ```js
  var source = new ol.source.GeoJSON({
    url: 'features.json',
    projection: 'EPSG:3857'
  });
  ```

  you will need to change your code to:

  ```js
  var source = new ol.source.Vector({
    url: 'features.json',
    format: new ol.format.GeoJSON()
  });
  ```

  See https://openlayers.org/en/latest/examples/vector-layer.html for a real example.

  Note that you no longer need to set a `projection` on the source!

  Previously the vector data was loaded at source construction time, and, if the data projection and the source projection were not the same, the vector data was transformed to the source projection before being inserted (as features) into the source.

  The vector data is now loaded at render time, when the view projection is known. And the vector data is transformed to the view projection if the data projection and the source projection are not the same.

  If you still want to "eagerly" load the source you will use something like this:

  ```js
  var source = new ol.source.Vector();
  $.ajax('features.json').then(function(response) {
    var geojsonFormat = new ol.format.GeoJSON();
    var features = geojsonFormat.readFeatures(response,
        {featureProjection: 'EPSG:3857'});
    source.addFeatures(features);
  });
  ```

  The above code uses jQuery to send an Ajax request, but you can obviously use any Ajax library.

  See https://openlayers.org/en/latest/examples/igc.html for a real example.

* Note about KML

  If you used `ol.source.KML`'s `extractStyles` or `defaultStyle` options, you will now have to set these options on `ol.format.KML` instead. For example, if you used:

  ```js
  var source = new ol.source.KML({
    url: 'features.kml',
    extractStyles: false,
    projection: 'EPSG:3857'
  });
  ```

  you will now use:

  ```js
  var source = new ol.source.Vector({
    url: 'features.kml',
    format: new ol.format.KML({
      extractStyles: false
    })
  });
  ```

* The `ol.source.ServerVector` class has been removed. If you used it, for example as follows:

  ```js
  var source = new ol.source.ServerVector({
    format: new ol.format.GeoJSON(),
    loader: function(extent, resolution, projection) {
      var url = …;
      $.ajax(url).then(function(response) {
        source.addFeatures(source.readFeatures(response));
      });
    },
    strategy: ol.loadingstrategy.bbox,
    projection: 'EPSG:3857'
  });
  ```

  you will need to change your code to:

  ```js
  var source = new ol.source.Vector({
    loader: function(extent, resolution, projection) {
      var url = …;
      $.ajax(url).then(function(response) {
        var format = new ol.format.GeoJSON();
        var features = format.readFeatures(response,
            {featureProjection: projection});
        source.addFeatures(features);
      });
    },
    strategy: ol.loadingstrategy.bbox
  });
  ```

  See https://openlayers.org/en/latest/examples/vector-osm.html for a real example.

* The experimental `ol.loadingstrategy.createTile` function has been renamed to `ol.loadingstrategy.tile`. The signature of the function hasn't changed. See https://openlayers.org/en/latest/examples/vector-osm.html for an example.

### Change to `ol.style.Icon`

* When manually loading an image for `ol.style.Icon`, the image size should now be set
with the `imgSize` option and not with `size`. `size` is supposed to be used for the
size of a sub-rectangle in an image sprite.

### Support for non-square tiles

The return value of `ol.tilegrid.TileGrid#getTileSize()` will now be an `ol.Size` array instead of a number if non-square tiles (i.e. an `ol.Size` array instead of a number as `tilsSize`) are used. To always get an `ol.Size`, the new `ol.size.toSize()` was added.

### Change to `ol.interaction.Draw`

When finishing a draw, the `drawend` event is now dispatched before the feature is inserted to either the source or the collection. This change allows application code to finish setting up the feature.

### Misc.

If you compile your application together with the library and use the `ol.feature.FeatureStyleFunction` type annotation (this should be extremely rare), the type is now named `ol.FeatureStyleFunction`.

## New features and fixes

 * [#3646](https://github.com/openlayers/openlayers/pull/3646) - Use graceful-fs in place of fs ([@elemoine](https://github.com/elemoine))
 * [#3645](https://github.com/openlayers/openlayers/pull/3645) - Fix test-coverage.js script ([@elemoine](https://github.com/elemoine))
 * [#3640](https://github.com/openlayers/openlayers/pull/3640) - Make make fail on requires and whitespace errors ([@elemoine](https://github.com/elemoine))
 * [#3644](https://github.com/openlayers/openlayers/pull/3644) - added altclick select to selectfeatures example ([@t27](https://github.com/t27))
 * [#3612](https://github.com/openlayers/openlayers/pull/3612) - Add ol.source.WMTS#getUrls and getRequestEncoding ([@elemoine](https://github.com/elemoine))
 * [#3616](https://github.com/openlayers/openlayers/pull/3616) - Add support for freehand drawing to the Draw interaction ([@ahocevar](https://github.com/ahocevar))
 * [#3634](https://github.com/openlayers/openlayers/pull/3634) - Remove unused local variable ([@fredj](https://github.com/fredj))
 * [#3629](https://github.com/openlayers/openlayers/pull/3629) - Problems with XYZ coordinates in snap interaction ([@tsauerwein](https://github.com/tsauerwein))
 * [#3633](https://github.com/openlayers/openlayers/pull/3633) - Add a Makefile section to .editorconfig ([@elemoine](https://github.com/elemoine))
 * [#3632](https://github.com/openlayers/openlayers/pull/3632) - Make host-examples target copy index.js ([@elemoine](https://github.com/elemoine))
 * [#3631](https://github.com/openlayers/openlayers/pull/3631) - Restore Modify interaction constructor test ([@bjornharrtell](https://github.com/bjornharrtell))
 * [#3630](https://github.com/openlayers/openlayers/pull/3630) - Initial tests for Modify interaction vertex creation ([@bjornharrtell](https://github.com/bjornharrtell))
 * [#3527](https://github.com/openlayers/openlayers/pull/3527) - Replace pake with make? ([@elemoine](https://github.com/elemoine))
 * [#3624](https://github.com/openlayers/openlayers/pull/3624) - Add a one sentence summary for several exportable symbols ([@marcjansen](https://github.com/marcjansen))
 * [#3623](https://github.com/openlayers/openlayers/pull/3623) - OpenLayers overwrites WMS format_options instead of extending them. ([@bartvde](https://github.com/bartvde))
 * [#3621](https://github.com/openlayers/openlayers/pull/3621) - Fix typo in documentation comment ([@openlayers](https://github.com/openlayers))
 * [#3614](https://github.com/openlayers/openlayers/pull/3614) - GML2 parser does not parse all features ([@bartvde](https://github.com/bartvde))
 * [#3619](https://github.com/openlayers/openlayers/pull/3619) - Add a one sentence summary for ol.geom.* exportable symbols ([@marcjansen](https://github.com/marcjansen))
 * [#3618](https://github.com/openlayers/openlayers/pull/3618) - Replace non-breaking space (U+00A0) with regular space (U+0020). ([@tschaub](https://github.com/tschaub))
 * [#3617](https://github.com/openlayers/openlayers/pull/3617) - Add ol.size.hasArea. ([@tschaub](https://github.com/tschaub))
 * [#3597](https://github.com/openlayers/openlayers/pull/3597) - Remove dead link in api doc ([@fredj](https://github.com/fredj))
 * [#3613](https://github.com/openlayers/openlayers/pull/3613) - Add a one sentence summary for ol.interaction* exportable symbols ([@marcjansen](https://github.com/marcjansen))
 * [#3611](https://github.com/openlayers/openlayers/pull/3611) - Improve error handling in Esri JSON format ([@bartvde](https://github.com/bartvde))
 * [#3560](https://github.com/openlayers/openlayers/pull/3560) - Add an example showing how to create a permalink ([@tsauerwein](https://github.com/tsauerwein))
 * [#3571](https://github.com/openlayers/openlayers/pull/3571) - Add wrapX support for vector layers (canvas renderer only) ([@ahocevar](https://github.com/ahocevar))
 * [#3605](https://github.com/openlayers/openlayers/pull/3605) - vector-esri-edit.html uses non api method ([@bartvde](https://github.com/bartvde))
 * [#3602](https://github.com/openlayers/openlayers/pull/3602) - Rename ol.feature.FeatureStyleFunction to ol.FeatureStyleFunction. ([@tschaub](https://github.com/tschaub))
 * [#3604](https://github.com/openlayers/openlayers/pull/3604) - Add charset so that zoom out button shows correctly ([@bartvde](https://github.com/bartvde))
 * [#3603](https://github.com/openlayers/openlayers/pull/3603) - Reformat upgrade-notes.md ([@elemoine](https://github.com/elemoine))
 * [#3599](https://github.com/openlayers/openlayers/pull/3599) - Improve docs for source.Vector options ([@probins](https://github.com/probins))
 * [#3598](https://github.com/openlayers/openlayers/pull/3598) - Remove unnecessary entry in `.gitignore`. ([@tschaub](https://github.com/tschaub))
 * [#3595](https://github.com/openlayers/openlayers/pull/3595) - Add featureloader.jsdoc ([@probins](https://github.com/probins))
 * [#3593](https://github.com/openlayers/openlayers/pull/3593) - Add /examples/index.js to .gitignore ([@fredj](https://github.com/fredj))
 * [#3592](https://github.com/openlayers/openlayers/pull/3592) - Remove reference to binding in Collection docs ([@probins](https://github.com/probins))
 * [#3591](https://github.com/openlayers/openlayers/pull/3591) - Only draw the layer if visible and inside the resolution range ([@fredj](https://github.com/fredj))
 * [#3528](https://github.com/openlayers/openlayers/pull/3528) - Fix memory leak when removing layers from ol.layer.Group ([@fredj](https://github.com/fredj))
 * [#3549](https://github.com/openlayers/openlayers/pull/3549) - Move ol.*_DURATION const to a constructor option ([@fredj](https://github.com/fredj))
 * [#3587](https://github.com/openlayers/openlayers/pull/3587) - Handle left/right segment intersections for top/bottom spans. ([@tschaub](https://github.com/tschaub))
 * [#3516](https://github.com/openlayers/openlayers/pull/3516) - Remove ol.format.BinaryFeature. ([@tschaub](https://github.com/tschaub))
 * [#3586](https://github.com/openlayers/openlayers/pull/3586) - Simplify dragAndDropInteraction in examples. ([@probins](https://github.com/probins))
 * [#3555](https://github.com/openlayers/openlayers/pull/3555) - Esri JSON support ([@bartvde](https://github.com/bartvde))
 * [#3583](https://github.com/openlayers/openlayers/pull/3583) - Add a one sentence summary for ol.proj.* and ol.layer.* exportable symbols ([@marcjansen](https://github.com/marcjansen))
 * [#3581](https://github.com/openlayers/openlayers/pull/3581) - Always show links to related API documentation. ([@tschaub](https://github.com/tschaub))
 * [#3582](https://github.com/openlayers/openlayers/pull/3582) - Index what the examples require. ([@tschaub](https://github.com/tschaub))
 * [#3580](https://github.com/openlayers/openlayers/pull/3580) - Add a one sentence summary for ol.source.* exportable symbols ([@marcjansen](https://github.com/marcjansen))
 * [#3551](https://github.com/openlayers/openlayers/pull/3551) - Automatically add links to API-docs in examples ([@marcjansen](https://github.com/marcjansen))
 * [#3575](https://github.com/openlayers/openlayers/pull/3575) - Check proj equivalence by code. ([@nd0ut](https://github.com/nd0ut))
 * [#3579](https://github.com/openlayers/openlayers/pull/3579) - Use HTTPS were available. ([@tschaub](https://github.com/tschaub))
 * [#3558](https://github.com/openlayers/openlayers/pull/3558) - Example sources in examples dir and built examples in build/examples. ([@tschaub](https://github.com/tschaub))
 * [#3550](https://github.com/openlayers/openlayers/pull/3550) - Reduce differences between the rendering test runner and the standard test runner. ([@tschaub](https://github.com/tschaub))
 * [#3576](https://github.com/openlayers/openlayers/pull/3576) - Add KML options related note the upgrade notes ([@elemoine](https://github.com/elemoine))
 * [#3573](https://github.com/openlayers/openlayers/pull/3573) - Modify draw interaction dispatch order ([@gberaudo](https://github.com/gberaudo))
 * [#3572](https://github.com/openlayers/openlayers/pull/3572) - Do not return a null tileSize ([@ahocevar](https://github.com/ahocevar))
 * [#3570](https://github.com/openlayers/openlayers/pull/3570) - Add missing @api ([@gberaudo](https://github.com/gberaudo))
 * [#3569](https://github.com/openlayers/openlayers/pull/3569) - Fix link to Bootstrap documentation ([@fredj](https://github.com/fredj))
 * [#3559](https://github.com/openlayers/openlayers/pull/3559) - Add support for non-square tiles ([@ahocevar](https://github.com/ahocevar))
 * [#3568](https://github.com/openlayers/openlayers/pull/3568) - Move extractStyles option to ol.format.KML ([@fredj](https://github.com/fredj))
 * [#3562](https://github.com/openlayers/openlayers/pull/3562) - Simplify .ol-zoomslider and .ol-overviewmap CSS ([@fredj](https://github.com/fredj))
 * [#3565](https://github.com/openlayers/openlayers/pull/3565) - Move extractStyles option to ol.format.KML ([@fredj](https://github.com/fredj))
 * [#3523](https://github.com/openlayers/openlayers/pull/3523) - Update proj4 version to 2.3.6 ([@fredj](https://github.com/fredj))
 * [#3556](https://github.com/openlayers/openlayers/pull/3556) - Minor TileUTFGrid error fix ([@klokantech](https://github.com/klokantech))
 * [#3557](https://github.com/openlayers/openlayers/pull/3557) - Update FastClick externs to version 1.0.6 ([@fredj](https://github.com/fredj))
 * [#3517](https://github.com/openlayers/openlayers/pull/3517) - Add tests for previously untested classes ([@marcjansen](https://github.com/marcjansen))
 * [#3548](https://github.com/openlayers/openlayers/pull/3548) - Write the error stack instead of the error itself. ([@tschaub](https://github.com/tschaub))
 * [#3542](https://github.com/openlayers/openlayers/pull/3542) - Generate example index and rebuild examples on source changes. ([@tschaub](https://github.com/tschaub))
 * [#3530](https://github.com/openlayers/openlayers/pull/3530) - external resources not correctly in inline source of example ([@bartvde](https://github.com/bartvde))
 * [#3448](https://github.com/openlayers/openlayers/pull/3448) - Fix WebGL image layer rendering on retina displays ([@elemoine](https://github.com/elemoine))
 * [#3544](https://github.com/openlayers/openlayers/pull/3544) - Update comments about remaining GeoJSON work. ([@tschaub](https://github.com/tschaub))
 * [#3531](https://github.com/openlayers/openlayers/pull/3531) - Fix PointerEventHandler exception with Overlay containing SVG and IE9 ([@mantonovic](https://github.com/mantonovic))
 * [#3521](https://github.com/openlayers/openlayers/pull/3521) - Remove goog.isDefAndNotNull test on ol.layer.Group#getLayers result ([@fredj](https://github.com/fredj))
 * [#3481](https://github.com/openlayers/openlayers/pull/3481) - Proposal for a simpler vector API ([@elemoine](https://github.com/elemoine))
 * [#3472](https://github.com/openlayers/openlayers/pull/3472) - Remove the experimental bindTo method from ol.Object. ([@tschaub](https://github.com/tschaub))
 * [#3505](https://github.com/openlayers/openlayers/pull/3505) - Add a Create Custom Builds tutorial ([@elemoine](https://github.com/elemoine))
 * [#3513](https://github.com/openlayers/openlayers/pull/3513) - Remove layerGroup.setLayers(null) test ([@fredj](https://github.com/fredj))
 * [#3511](https://github.com/openlayers/openlayers/pull/3511) - Add goog.provide's ([@elemoine](https://github.com/elemoine))
 * [#3509](https://github.com/openlayers/openlayers/pull/3509) - Dispatch change event even when geometry is set to null ([@pgiraud](https://github.com/pgiraud))
 * [#3510](https://github.com/openlayers/openlayers/pull/3510) - Use sinon.spy to ensure change event is dispatched ([@pgiraud](https://github.com/pgiraud))
 * [#3504](https://github.com/openlayers/openlayers/pull/3504) - Rework build-examples.js task. ([@tschaub](https://github.com/tschaub))
 * [#3470](https://github.com/openlayers/openlayers/pull/3470) - Add rendering tests ([@tsauerwein](https://github.com/tsauerwein))
 * [#3413](https://github.com/openlayers/openlayers/pull/3413) - Add support for generic external modules with Browserify ([@tsauerwein](https://github.com/tsauerwein))
 * [#3503](https://github.com/openlayers/openlayers/pull/3503) - Use vector source instead of feature overlay in snap example. ([@tschaub](https://github.com/tschaub))
 * [#3495](https://github.com/openlayers/openlayers/pull/3495) - Initial basic project setup tutorial ([@bjornharrtell](https://github.com/bjornharrtell))
 * [#3488](https://github.com/openlayers/openlayers/pull/3488) - Add docs for exportable symbols. ([@tschaub](https://github.com/tschaub))
 * [#3441](https://github.com/openlayers/openlayers/pull/3441) - Add a "Compile Application and OpenLayers Together" tutorial ([@elemoine](https://github.com/elemoine))
 * [#3499](https://github.com/openlayers/openlayers/pull/3499) - Update to closure-util 1.4.0 ([@elemoine](https://github.com/elemoine))
 * [#3494](https://github.com/openlayers/openlayers/pull/3494) - Mark VectorContext @api ([@gberaudo](https://github.com/gberaudo))
 * [#3409](https://github.com/openlayers/openlayers/pull/3409) - AssertionError in WMTS.optionsFromCapabilities. ([@bartvde](https://github.com/bartvde))
 * [#3493](https://github.com/openlayers/openlayers/pull/3493) - Add image loading events to ol.source.ImageStatic ([@tsauerwein](https://github.com/tsauerwein))
 * [#3490](https://github.com/openlayers/openlayers/pull/3490) - Add .editorconfig and instructions on its use. ([@tschaub](https://github.com/tschaub))
 * [#3489](https://github.com/openlayers/openlayers/pull/3489) - Use an abstract base class instead of IVectorContext. ([@gberaudo](https://github.com/gberaudo))
 * [#3483](https://github.com/openlayers/openlayers/pull/3483) - Clarify view.setRotation docs ([@tsauerwein](https://github.com/tsauerwein))
 * [#3485](https://github.com/openlayers/openlayers/pull/3485) - build.py graceful interrupt ([@malaretv](https://github.com/malaretv))
 * [#3484](https://github.com/openlayers/openlayers/pull/3484) - Make sure we copy the example css if it exists ([@bartvde](https://github.com/bartvde))
 * [#3462](https://github.com/openlayers/openlayers/pull/3462) - Remove ol.format.GMLBase from the API ([@ahocevar](https://github.com/ahocevar))
 * [#3445](https://github.com/openlayers/openlayers/pull/3445) - Start a FAQ document. ([@marcjansen](https://github.com/marcjansen))
 * [#3468](https://github.com/openlayers/openlayers/pull/3468) - Use the coveralls executable. ([@marcjansen](https://github.com/marcjansen))
 * [#3415](https://github.com/openlayers/openlayers/pull/3415) - Stable Only unchecked by default. ([@malaretv](https://github.com/malaretv))
 * [#3420](https://github.com/openlayers/openlayers/pull/3420) - Unregister viewport size listener on setTarget(null) ([@elemoine](https://github.com/elemoine))
 * [#3456](https://github.com/openlayers/openlayers/pull/3456) - Updated menu on the JSDOC template (non-responsive) ([@klokan](https://github.com/klokan))
 * [#3475](https://github.com/openlayers/openlayers/pull/3475) - Template examples ([@openlayers](https://github.com/openlayers))
 * [#3455](https://github.com/openlayers/openlayers/pull/3455) - Fix pre-loaded icons images for WebGL ([@tsauerwein](https://github.com/tsauerwein))
 * [#3473](https://github.com/openlayers/openlayers/pull/3473) - Add more tests for ol.coordinate. ([@marcjansen](https://github.com/marcjansen))
 * [#3464](https://github.com/openlayers/openlayers/pull/3464) - Mark more of the API stable. ([@tschaub](https://github.com/tschaub))
 * [#3469](https://github.com/openlayers/openlayers/pull/3469) - Update README. ([@malaretv](https://github.com/malaretv))
 * [#3467](https://github.com/openlayers/openlayers/pull/3467) - Update the coveralls badge. ([@openlayers](https://github.com/openlayers))
 * [#3466](https://github.com/openlayers/openlayers/pull/3466) - Include coveralls code-coverage badge in README. ([@marcjansen](https://github.com/marcjansen))
 * [#3457](https://github.com/openlayers/openlayers/pull/3457) - Integrate istanbul for test coverage ([@marcjansen](https://github.com/marcjansen))
 * [#3446](https://github.com/openlayers/openlayers/pull/3446) - Add updateWhileInteracting to olx.layer.VectorOptions ([@elemoine](https://github.com/elemoine))
 * [#3438](https://github.com/openlayers/openlayers/pull/3438) - Parser documentation and XML readme ([@gberaudo](https://github.com/gberaudo))
 * [#3449](https://github.com/openlayers/openlayers/pull/3449) - Fix assertion message ([@gberaudo](https://github.com/gberaudo))
 * [#3440](https://github.com/openlayers/openlayers/pull/3440) - Add fromLonLat and toLonLat convenience functions ([@ahocevar](https://github.com/ahocevar))
 * [#3423](https://github.com/openlayers/openlayers/pull/3423) - Parse extrude and altitude mode ([@gberaudo](https://github.com/gberaudo))
 * [#3431](https://github.com/openlayers/openlayers/pull/3431) - Better typing ([@fredj](https://github.com/fredj))
 * [#3436](https://github.com/openlayers/openlayers/pull/3436) - Mention readme.md files as help for contributors ([@ahocevar](https://github.com/ahocevar))
 * [#3433](https://github.com/openlayers/openlayers/pull/3433) - Add missing goog.provide/goog.require ol.source.TileEvent ([@fredj](https://github.com/fredj))
 * [#3422](https://github.com/openlayers/openlayers/pull/3422) - Fix Select behavior when multi is false ([@elemoine](https://github.com/elemoine))
 * [#3428](https://github.com/openlayers/openlayers/pull/3428) - Reorder assertions and variable declarations. ([@marcjansen](https://github.com/marcjansen))
 * [#3414](https://github.com/openlayers/openlayers/pull/3414) - Add missing ol.style.AtlasManager goog.require ([@fredj](https://github.com/fredj))
 * [#3429](https://github.com/openlayers/openlayers/pull/3429) - Adding missing provide for SelectFilterFunction ([@pgiraud](https://github.com/pgiraud))
 * [#3426](https://github.com/openlayers/openlayers/pull/3426) - Add assertion messages for all assertion statements ([@bartvde](https://github.com/bartvde))
 * [#3425](https://github.com/openlayers/openlayers/pull/3425) - Fix typo in ol.js ([@elemoine](https://github.com/elemoine))
 * [#3424](https://github.com/openlayers/openlayers/pull/3424) - Remove `@api` annotation from `ol.WEBGL_MAX_TEXTURE_SIZE`. ([@tschaub](https://github.com/tschaub))
 * [#3419](https://github.com/openlayers/openlayers/pull/3419) - Remove describe.only ([@elemoine](https://github.com/elemoine))
 * [#3417](https://github.com/openlayers/openlayers/pull/3417) - ol.interaction.Snap extent fix ([@fperucic](https://github.com/fperucic))
 * [#3410](https://github.com/openlayers/openlayers/pull/3410) - Add ol.Object.unset() method ([@gberaudo](https://github.com/gberaudo))
 * [#3402](https://github.com/openlayers/openlayers/pull/3402) - Add "filter" option to Select interaction ([@elemoine](https://github.com/elemoine))
 * [#3416](https://github.com/openlayers/openlayers/pull/3416) - Remove unnecessary typecasts in examples ([@fredj](https://github.com/fredj))
 * [#3411](https://github.com/openlayers/openlayers/pull/3411) - Listen for a 'change:geometry' event ([@fperucic](https://github.com/fperucic))
 * [#3109](https://github.com/openlayers/openlayers/pull/3109) - Snap feature ([@fperucic](https://github.com/fperucic))
 * [#3407](https://github.com/openlayers/openlayers/pull/3407) - Add v3.4.0 empty section to upgrade notes ([@bartvde](https://github.com/bartvde))


text:
"""
Test the various response formats.
"""

from shared import *

def test_common():
    """
    Common response stuff.
    """

    # Ensure that the http options are carried through to the actual response
    r = JsonResponse('data', http_status=404,
                    http_headers={'X-Custom': 'test'}).get_response()
    assert r.status_code == 404
    assert r['X-Custom'] == 'test'

    # Try to create ``APIResponse`` classes with various data types and options
    APIResponse('')
    APIResponse({'count': 1})
    APIResponse({'count': 1}, http_status=200, http_headers={'custom': True})

    # If passed an exception, it's values are used
    e = APIError('message', code=9,
                 http_status=404,
                 http_headers={'Location': 'http://google.de'})
    r = APIResponse(e)
    assert r.data == e
    assert r.http_status == 404
    assert 'Location' in r.http_headers

    # If passed another ``APIResponse`` object, it's values are used
    r1 = APIResponse('data', http_status=404,
                    http_headers={'Location': 'http://google.de'})
    r2 = APIResponse(r1)
    assert r2.data == r1.data
    assert r2.http_status == 404
    assert 'Location' in r2.http_headers

    # Make sure we can always override the http meta data copied from an
    # ``APIResponse`` or ``APIError``. ``False`` works for removal.
    for data_obj in [r1, e]:
        r2 = APIResponse(data_obj, http_status=500, http_headers=False)
        assert r2.http_status == 500
        assert not r2.http_headers

def test_python_response():
    """
    Test raw python format.
    """
    def format(data): return PythonResponse(data).get_response()

    # everything is passed out unchanged
    assert format(5) == 5
    assert format('string') == 'string'
    assert format(True) == True
    assert format({}) == {}

    # even ``None``
    assert format(None) == None

    # errors (internal and all others) are raised / not catched
    raises(APIError, format, APIError())
    raises(TypeError, format, TypeError())

def test_json_response():
    """
    Test JSON response format.

    TODO: check queryset formatting (needs django setup with database?!)
    """
    def format(data): return JsonResponse(data).get_response().content

    # some basic datatypes
    assert format(5) == '5'
    assert format('string') == '"string"'
    assert format(True) == 'true'
    assert format({}) == '{}'

    # ``None`` should map to empty string
    assert format(None) == ''

    # check exception are formatted to valid json as well
    from django.utils import simplejson
    simplejson.loads(format(APIError('An error occured', code=2)))

    # check return mime type
    JsonResponse({}).get_response().mime_type = 'application/json'

    # test jsonp support
    assert JsonResponse([1, True], jsonp_callback='call').\
        get_response().content == 'call([1, true])'
    # an empty callback string is allowed too, and will still cause a
    # parenthesis  wrap
    assert JsonResponse([1, True], jsonp_callback='').\
        get_response().content == '([1, true])'

redpajama_set_name: RedPajamaGithub


text:
public class CustomAnnotation {

    @WorkInProgress
    @Task(description = "Implement tax computations",
    targetDate = "Jan 1, 2012",
    estimatedHours = 50,
    additionalNote = "This implementation is critical for the final launch")
    public static float ComputeTax(float amount, float rate) {
        return 0;
    }
}

@interface WorkInProgress {
}

@interface Task {

    String description();

    String targetDate();

    int estimatedHours();

    String additionalNote();
}


text:
from __future__ import absolute_import

import os
from textwrap import dedent

from pex import pex_warnings, third_party
from pex.atomic_directory import atomic_directory
from pex.interpreter import PythonInterpreter
from pex.orderedset import OrderedSet
from pex.pex import PEX
from pex.pex_bootstrapper import VenvPex, ensure_venv
from pex.pip.tool import Pip
from pex.pip.version import PipVersion, PipVersionValue
from pex.resolve.resolvers import Resolver
from pex.targets import LocalInterpreter, RequiresPythonError, Targets
from pex.third_party import isolated
from pex.typing import TYPE_CHECKING
from pex.util import named_temporary_file
from pex.variables import ENV

if TYPE_CHECKING:
    from typing import Callable, Dict, Iterator, Optional

    import attr  # vendor:skip
else:
    from pex.third_party import attr

def _pip_venv(
    version,  # type: PipVersionValue
    iter_distribution_locations,  # type: Callable[[], Iterator[str]]
    interpreter=None,  # type: Optional[PythonInterpreter]
):
    # type: (...) -> VenvPex
    path = os.path.join(ENV.PEX_ROOT, "pip-{version}.pex".format(version=version))
    pip_interpreter = interpreter or PythonInterpreter.get()
    pip_pex_path = os.path.join(path, isolated().pex_hash)
    with atomic_directory(pip_pex_path) as chroot:
        if not chroot.is_finalized():
            from pex.pex_builder import PEXBuilder

            isolated_pip_builder = PEXBuilder(path=chroot.work_dir)
            isolated_pip_builder.info.venv = True
            for dist_location in iter_distribution_locations():
                isolated_pip_builder.add_dist_location(dist=dist_location)
            with named_temporary_file(prefix="", suffix=".py", mode="w") as fp:
                fp.write(
                    dedent(
                        """\
                        import os
                        import runpy

                        patches_module = os.environ.pop({patches_module_env_var_name!r}, None)
                        if patches_module:
                            # Apply runtime patches to Pip to work around issues or else bend
                            # Pip to Pex's needs.
                            __import__(patches_module)

                        runpy.run_module(mod_name="pip", run_name="__main__", alter_sys=True)
                        """
                    ).format(patches_module_env_var_name=Pip._PATCHES_MODULE_ENV_VAR_NAME)
                )
                fp.close()
                isolated_pip_builder.set_executable(fp.name, "__pex_patched_pip__.py")
            isolated_pip_builder.freeze()
    return ensure_venv(PEX(pip_pex_path, interpreter=pip_interpreter))

def _vendored_installation(interpreter=None):
    # type: (Optional[PythonInterpreter]) -> VenvPex

    return _pip_venv(
        version=PipVersion.VENDORED,
        iter_distribution_locations=lambda: third_party.expose(("pip", "setuptools", "wheel")),
        interpreter=interpreter,
    )

def _resolved_installation(
    version,  # type: PipVersionValue
    resolver,  # type: Resolver
    interpreter=None,  # type: Optional[PythonInterpreter]
):
    # type: (...) -> VenvPex
    if version is PipVersion.VENDORED:
        return _vendored_installation(interpreter=interpreter)

    def resolve_distribution_locations():
        for installed_distribution in resolver.resolve_requirements(
            requirements=version.requirements,
            targets=Targets(interpreters=(interpreter or PythonInterpreter.get(),)),
            pip_version=PipVersion.VENDORED,
        ).installed_distributions:
            yield installed_distribution.distribution.location

    return _pip_venv(
        version=version,
        iter_distribution_locations=resolve_distribution_locations,
        interpreter=interpreter,
    )

@attr.s(frozen=True)
class PipInstallation(object):
    interpreter = attr.ib()  # type: PythonInterpreter
    version = attr.ib()  # type: PipVersionValue

    def check_python_applies(self):
        # type: () -> None
        if not self.version.requires_python_applies(LocalInterpreter.create(self.interpreter)):
            raise RequiresPythonError(
                "The Pip requested was {pip_requirement} but it does not work with the interpreter "
                "selected which is {python_impl} {python_version} at {python_binary}. Pip "
                "{pip_version} requires Python {requires_python}.".format(
                    pip_requirement=self.version.requirement,
                    pip_version=self.version.value,
                    python_impl=self.interpreter.identity.interpreter,
                    python_version=self.interpreter.identity.version_str,
                    python_binary=self.interpreter.binary,
                    requires_python=self.version.requires_python,
                )
            )

def validate_targets(
    targets,  # type: Targets
    version,  # type: PipVersionValue
    context,  # type: str
):
    # type: (...) -> None
    all_targets = targets.unique_targets()
    invalid_targets = [
        target for target in all_targets if not version.requires_python_applies(target)
    ]
    if invalid_targets:
        raise RequiresPythonError(
            "The Pip requested for {context} was {pip_requirement} but it does not work with "
            "{quantifier} targets selected.\n"
            "\n"
            "Pip {pip_version} requires Python {requires_python} and the following {targets_do} "
            "not apply:\n"
            "{invalid_targets}"
            "".format(
                context=context,
                pip_requirement=version.requirement,
                quantifier="any of the"
                if len(invalid_targets) == len(all_targets)
                else "{invalid} out of the {total}".format(
                    invalid=len(invalid_targets), total=len(all_targets)
                ),
                pip_version=version.value,
                requires_python=version.requires_python,
                targets_do="target does" if len(invalid_targets) == 1 else "targets do",
                invalid_targets="\n".join(
                    "{index}. {target}".format(index=index, target=target)
                    for index, target in enumerate(invalid_targets, start=1)
                ),
            )
        )

def compatible_version(
    targets,  # type: Targets
    requested_version,  # type: PipVersionValue
    context,  # type: str
):
    # type: (...) -> PipVersionValue
    try:
        validate_targets(targets, requested_version, context)
        return requested_version
    except RequiresPythonError as e:
        remaining_versions = OrderedSet([requested_version] + list(PipVersion.values()))
        remaining_versions.discard(requested_version)
        for version in remaining_versions:
            try:
                validate_targets(targets, version, context)
                pex_warnings.warn(
                    "{err}\n" "\n" "Using Pip {version} instead.".format(err=e, version=version)
                )
                return version
            except RequiresPythonError:
                continue
    return PipVersion.v20_3_4_patched

_PIP = {}  # type: Dict[PipInstallation, Pip]

def get_pip(
    interpreter=None,
    version=PipVersion.VENDORED,  # type: PipVersionValue
    resolver=None,  # type: Optional[Resolver]
):
    # type: (...) -> Pip
    """Returns a lazily instantiated global Pip object that is safe for un-coordinated use."""
    installation = PipInstallation(
        interpreter=interpreter or PythonInterpreter.get(),
        version=version,
    )
    pip = _PIP.get(installation)
    if pip is None:
        installation.check_python_applies()
        if version is PipVersion.VENDORED:
            pip = Pip(pip_pex=_vendored_installation(interpreter=interpreter))
        else:
            if resolver is None:
                raise ValueError(
                    "A resolver is required to install {requirement}".format(
                        requirement=version.requirement
                    )
                )
            pip = Pip(
                pip_pex=_resolved_installation(
                    version=version,
                    resolver=resolver,
                    interpreter=interpreter,
                )
            )
        _PIP[installation] = pip
    return pip


text:
import { useTheme } from "@emotion/react"
import Color from "color"
import { observer } from "mobx-react-lite"
import { VFC } from "react"
import { Layout } from "../../../Constants"
import { colorToVec4 } from "../../../gl/color"
import { useStores } from "../../../hooks/useStores"
import { HorizontalGrid } from "./HorizontalGrid"

export const Lines: VFC<{ zIndex: number }> = observer(({ zIndex }) => {
  const theme = useTheme()
  const rootStore = useStores()
  const {
    pianoRollStore: { scrollTop, canvasWidth, canvasHeight, scaleY },
  } = rootStore

  return (
    <HorizontalGrid
      rect={{
        x: 0,
        y: scrollTop,
        width: canvasWidth,
        height: canvasHeight,
      }}
      color={colorToVec4(Color(theme.dividerColor).alpha(0.2))}
      highlightedColor={colorToVec4(Color(theme.dividerColor).alpha(0.5))}
      blackLaneColor={colorToVec4(Color(theme.pianoBlackKeyLaneColor))}
      height={scaleY * Layout.keyHeight}
      zIndex={zIndex}
    />
  )
})


text:
//
//  flipbook.m
//  animation
//
//  Created by Bjoern Seip on 25.08.10.
//  Copyright 2010 Bjoern Seip. All rights reserved.
//

#import "flipbook.h"

@implementation flipbook

@synthesize delegate;
@synthesize tapAlphaFilter;

/************************************************/
/**
 *	Regular Init
 *
 */
- (id)init {

	if (self = [super init])
	{

		_animation_id = 0;
		_animation_frame = 0;
		_animation_frame_count = 0;

		_animation_repeat = 0;

		_running = FALSE;
		_reverse = FALSE;

		_delay = 0;
		_timeout = 0;

		_lastAnimationId = 0;

		_actions = [[NSMutableArray alloc] initWithCapacity:10];
		_animations = [[NSMutableDictionary alloc] initWithCapacity:10];;

		delegate = 0;

	}

	return self;

}

/**
 *  Full Init setting frame and text id
 */
- (id)initWithFrameAndName:(CGRect)frame withName:(char *)pName {

	if ((self = [super initWithFrame:frame])) {

		_animation_id = 0;
		_animation_frame = 0;
		_animation_frame_count = 0;

		_animation_repeat = 0;

		_running = FALSE;
		_reverse = FALSE;

		_delay = 0;
		_timeout = 0;

		_lastAnimationId = 0;

		_actions = [[NSMutableArray alloc] initWithCapacity:10];
		_animations = [[NSMutableDictionary alloc] initWithCapacity:10];;

		delegate = 0;

		textId = pName;

		_position = [[Rectangle alloc] initWithDimensions:0 theLeft:0 theWidth:0 theHeight:0];

		self.opaque = FALSE;

		self.userInteractionEnabled = FALSE;

		// ***********************************************************************
		// ***********************************************************************
		// ***********************************************************************
		// TODO Dictionary und Enumerator einbauen (AnimationId -> Animation *)
		NSEnumerator *enumerator = [_animations keyEnumerator];

		for(NSString *aKey in enumerator){

			NSLog(@"%@",aKey);
			NSLog(@"%@",[[_animations valueForKey:aKey] string]); //made up method

		}
		// ***********************************************************************
		// ***********************************************************************

	}

	return self;

}

/**
 * Drawing routine
 */
- (void)drawRect:(CGRect)rect {

	[super drawRect:rect];

	if (_visible) {
	//	[self loadCurrentImage];
		[_current_image drawAtPoint:CGPointMake(0, 0)];
/*
		NSEnumerator *enumerator = [_actions objectEnumerator];
		flipbookAction * action;

		while (action = [enumerator nextObject]) {

			CGContextRef context = UIGraphicsGetCurrentContext();
			CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
			CGContextStrokeRectWithWidth(context,action->rectangle,1);

		}
 */
	}

}

/**
 * Start animation sequence.
 *
 */
- (void)runAnimation:(UInt16)animationId {

	if ([_animations count] > 0) {

		if (!_running) {
				_reverse = FALSE;
				_animation_id = animationId;
				flipbookAnimation * currentAnimation = [_animations objectForKey:[[NSNumber numberWithInt:animationId] stringValue]];
				_animation_frame = 0;
				_animation_frame_count = currentAnimation->frameCount;
				_valid = FALSE;
				_delay = currentAnimation->delay;
				_timeout = _delay;
				_running = TRUE;

				if ((currentAnimation->positionX != 0) || (currentAnimation->positionY != 0)) {
					_position->left = currentAnimation->positionX;
					_position->top = currentAnimation->positionY;
					[self flushPosition];
				}

				if( [delegate respondsToSelector:@selector(flipbookAnimationStarted)] ) {

					[delegate flipbookAnimationStarted:self  theAnimation:animationId];

				}

		}
	}

}

/**
 * Start animation sequence, run multiple times
 */
- (void)runAnimationRepeat:(UInt16)animationId  withRepeat:(UInt16) repeatCount {

	_animation_repeat = repeatCount;

	[self runAnimation:animationId];

}

/**
 * Start current animation sequence running backwards
 */
- (void)runReverse {

	if (!_running) {

		_reverse = TRUE;

		// _valid = FALSE;

		_timeout = _delay;

		_running = TRUE;

		[self prepare];
	}

}

- (void)setAnimationFrame:(UInt16)animationId withFrame:(UInt16) frameId {
	_animation_id = animationId;
	_animation_frame = frameId;
	flipbookAnimation * currentAnimation = [_animations objectForKey:[[NSNumber numberWithInt:_animation_id] stringValue]];
	_animation_frame_count = currentAnimation->frameCount;
	_valid = FALSE;
	_running = FALSE;

	if ( (currentAnimation->positionX) || (currentAnimation->positionY) ) {
		_position->left = currentAnimation->positionX;
		_position->top = currentAnimation->positionY;
		[self flushPosition];
	}

	[self prepare];
}

- (void)setAnimationFrameNoPosition:(UInt16)animationId withFrame:(UInt16) frameId {

	_animation_id = animationId;
	_animation_frame = frameId;
	flipbookAnimation * currentAnimation = [_animations objectForKey:[[NSNumber numberWithInt:_animation_id] stringValue]];
	_animation_frame_count = currentAnimation.frameCount;
	_valid = FALSE;
	_running = FALSE;
	[self prepare];

}

- (UInt16)addAction:(CGRect)rect withActionId:(int)actionId withAnimationId:(int)animationId {

	// Enable Touch Messages
	// self.userInteractionEnabled = YES;

	flipbookAction * newaction = [[flipbookAction alloc] initWithData:rect pActionId:actionId pAnimationId:animationId];

	[_actions addObject:newaction];

	[newaction release];

	return actionId;

}

- (bool)executeTap:(CGPoint)touchPos {

	if (_enabled) {

		touchPos = CGPointMake(touchPos.x - self.frame.origin.x, touchPos.y - self.frame.origin.y);

		if (tapAlphaFilter) {

			flipbookAnimation * currentAnimation = [_animations objectForKey:[[NSNumber numberWithInt:_animation_id] stringValue]];

			flipbookFrame * currentframe = [currentAnimation getFrame:_animation_frame];

			UIColor * color = [currentframe getPixelColorAtLocation:touchPos];

			float c2af = CGColorGetAlpha(color.CGColor);

			if (c2af == 0) {

				return false;

			}

		}

		NSEnumerator *enumerator = [_actions objectEnumerator];

		flipbookAction * action;

		while (action = [enumerator nextObject]) {

			if ([action hitTest:touchPos]) {

				if (action->animationId > -1) {
					[self runAnimation:action->animationId];
				}

				if (action->actionId) {

					//	if( [self.delegate respondsToSelector:@selector(flipbookActionCommencing:)] ) {

				   [self.delegate flipbookActionCommencing:self theAction:action->actionId];

					//	}

				}

				return true;

			}

		}

	}

	return FALSE;

}

- (UInt16)addAnimation:(UInt16)animationId withCount:(UInt16)pCount withDelay:(UInt16)delay withName:(NSString *)pName {

	return 0;

}

- (UInt16)addSound:(UInt16)animationId withFrame:(UInt16)pFrameId withName:(NSString *)pName {

	NSString * binpath = [[NSBundle mainBundle] pathForResource:pName ofType:@"aif"];

	//declare a system sound id
	SystemSoundID soundID;

	//Get a URL for the sound file
	NSURL *filePath = [NSURL fileURLWithPath:binpath isDirectory:NO];

	//Use audio sevices to create the sound
	AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);

	flipbookAnimation * currentAnimation = [_animations objectForKey:[[NSNumber numberWithInt:animationId] stringValue]];

	flipbookFrame * currentframe = [currentAnimation getFrame:pFrameId];

	currentframe->soundId = soundID;

	//Use audio services to play the sound
	//AudioServicesPlaySystemSound(soundID);

	return 0;

}

- (UInt16)loadAnimation:(UInt16)animationId withName:(NSString *)pName {

	flipbookAnimation * newAnimation = [[flipbookAnimation alloc] init];

	[newAnimation load:pName];

	[_animations setValue:newAnimation forKey:[[NSNumber numberWithInt:animationId] stringValue]];

	[newAnimation release];

	return animationId;

}

- (UInt16)addTransformation:(UInt16)animationId withStepCount:(UInt16)stepCount withXTable:(NSArray *)xTable withYTable:(NSArray *)yTable {

	return 0;

}

/**
 * Load current image to secondary buffer or write to screen
 *
 */
- (void)loadCurrentImage {

	flipbookAnimation * currentAnimation = [_animations objectForKey:[[NSNumber numberWithInt:_animation_id] stringValue]];

	flipbookFrame * currentframe = [currentAnimation getFrame:_animation_frame];

	_current_image = currentframe->image;
}

/**
 * Return currently active frame
 */
- (UInt16)currentFrame {

	return _animation_frame;

}

/**
 * Prepare position and frame data for next display.
 * Must be called exactly once before each frame refresh (e.g. every 40ms for 25fps)
 */
- (void)prepare {

	[super prepare];

	if (_running) {

		if (!_timeout) {

			_timeout = _delay;

			if (_reverse) {
				[self loadCurrentImage];

				if (_animation_frame) {
					--_animation_frame;
				} else {
					_running = FALSE;

					// TODO: Warum funktioniert die Abfrage nicht??
					//if( [delegate respondsToSelector:@selector(flipbookAnimationCompleted)] ) {

						[delegate flipbookAnimationCompleted:self theAnimation:_animation_id];

					//}

				}

			} else {

				flipbookAnimation * currentAnimation = [_animations objectForKey:[[NSNumber numberWithInt:_animation_id] stringValue]];

				flipbookFrame * currentframe = [currentAnimation getFrame:_animation_frame];

				if (currentframe->soundId) {

					AudioServicesPlaySystemSound(currentframe->soundId);
				}

				// TODO: Implement Transformations

				_position.left += currentframe->offsetX;
				_position.top += currentframe->offsetY;

			    [self flushPosition];

				[self loadCurrentImage];

				if (_animation_frame < (_animation_frame_count - 1) ) {

					++_animation_frame;

				} else {

					_running = FALSE;

					if (_animation_repeat) {

						--_animation_repeat;

						[self runAnimation:_animation_id];

					} else {

						// TODO: Warum funktioniert die Abfrage nicht??

					//	if( [self.delegate respondsToSelector:@selector(flipbookAnimationCompleted:)] ) {

							[self.delegate flipbookAnimationCompleted:self theAnimation:_animation_id];

					//	}

					}
				}

			}

		} else {

			--_timeout;

		}

	} else {

		 if (!_valid) {

			[self loadCurrentImage];

			_valid = TRUE;

		 }

	}

	[self setNeedsDisplay];

}

- (bool)isRunning {

	return _running;

}

- (void)tap:(UInt16)pX withY:(UInt16)pY {

}

- (void)lift:(UInt16)pX withY:(UInt16)pY {

}

- (void)drag:(UInt16)pX withY:(UInt16)pY {

}

- (void)dealloc {
	[_animations release];
	[_actions release];
	[_position release];

    [super dealloc];
}

@end


text:
bool test_isabs_check_abspath()
{
    std::string abspath = "/a/b/c";
#ifdef WIN32
	abspath = "c:\\a\\b\\c";
#endif
	return ftx::path::isabs(abspath);
}

bool test_isabs_check_relpath()
{
    std::string relpath = "../a/b/c";
	return !ftx::path::isabs(relpath);
}

bool test_isabs() {

    LOG_TEST_STRING("");

    TEST_BOOL_TO_BOOL(test_isabs_check_abspath(), "is abspath but return false");

    TEST_BOOL_TO_BOOL(test_isabs_check_relpath(), "is relpath but reutrn true");

    return true;
}


text:
/**
 * Imports
 */
var dbContext = require('./../../db/DbContext');
var _ = require('lodash');

/**
 * ProjectPhoto dao
 */
var ProjectPhotoDao = function () {
  this.context = dbContext.entities;
};

_.extend(ProjectPhotoDao.prototype, {

  /**
     * getAll ProjectPhotos
     * @param  {Function} callback
     */
  getAll: function (callback) {
    return this.context.ProjectPhoto.findAll();
  },

  getAllByProjectId: function (id, callback) {
    return this.context.ProjectPhoto.findAll({where: {ProjectId: id}});
  },

  /**
     * get ProjectPhoto by id
     * @param  {Integer}   id
     * @param  {Function} callback
     */
  get: function (id, callback) {
    return this.context.ProjectPhoto.find(id);
  },

  /**
     * save ProjectPhoto with properties
     * @param  {Object}   properties
     * @param  {Function} callback
     */
  save: function(properties, callback){
    this.context.ProjectPhoto.create(properties)
    .success(function (projectPhoto) {
      callback(null, projectPhoto);
    })
    .error(function (error) {
      callback(error, null);
    });
  },

  /**
     * Update projectPhoto from properties
     * @param  {Object}   properties
     * @param  {Function} callback
     */
  update: function (properties, callback) {
    this.get(properties.id).success(function (projectPhoto) {
      if(projectPhoto){
        projectPhoto.updateAttributes(properties).success(function (projectPhoto) {
          callback(null, projectPhoto);
        }).error(function (error) {
          callback(error, projectPhoto);
        });
      }else{
        callback('Aucun média avec l\'id :' + properties.id, null);
      }
    });
  },

  /**
     * Delete projectPhoto from id
     * @param  {Integer}   id
     * @param  {Function} callback
     */
  delete: function (id, callback) {
    this.context.ProjectPhoto.find(id).success(function (projectPhoto) {
      if(projectPhoto){
        projectPhoto.destroy().success(callback);
      }
      else{
        callback('Aucun média avec l\'id :' + id);
      }
    })
    .error(callback);
  }
});

module.exports = ProjectPhotoDao;


text:
using System.Collections;

namespace Magellan.Routing
{
    /// <summary>
    /// Represents the result of attempting to match a route from a path.
    /// </summary>
    public sealed class RouteMatch
    {
        private readonly bool success;
        private readonly IRoute route;
        private readonly string failReason;
        private readonly RouteValueDictionary values;

        /// <summary>
        /// Initializes a new instance of the <see cref="RouteMatch"/> class.
        /// </summary>
        /// <param name="success">if set to <c>true</c> [success].</param>
        /// <param name="route">The route.</param>
        /// <param name="parameterValues">The parameter values.</param>
        /// <param name="failReason">The fail reason.</param>
        private RouteMatch(bool success, IRoute route, IDictionary parameterValues, string failReason)
        {
            this.success = success;
            this.route = route;
            this.failReason = failReason;
            values = new RouteValueDictionary(parameterValues);
        }

        /// <summary>
        /// Produces a successful result.
        /// </summary>
        /// <param name="route">The route.</param>
        /// <param name="parameterValues">The parameter values.</param>
        /// <returns></returns>
        public static RouteMatch Successful(IRoute route, IDictionary parameterValues)
        {
            return new RouteMatch(true, route, parameterValues, null);
        }

        /// <summary>
        /// Produces an unsuccessful result, giving a reason for the failure.
        /// </summary>
        /// <param name="route">The route.</param>
        /// <param name="reason">The reason.</param>
        /// <returns></returns>
        public static RouteMatch Failure(IRoute route, string reason)
        {
            return new RouteMatch(false, route, null, reason);
        }

        /// <summary>
        /// Gets a value indicating whether the attempt to match the route was successful.
        /// </summary>
        /// <value><c>true</c> if success; otherwise, <c>false</c>.</value>
        public bool Success
        {
            get { return success; }
        }

        /// <summary>
        /// Gets the route that was matched.
        /// </summary>
        /// <value>The route.</value>
        public IRoute Route
        {
            get { return route; }
        }

        /// <summary>
        /// Gets the collection of route values extracted from the path.
        /// </summary>
        /// <value>The values.</value>
        public RouteValueDictionary Values
        {
            get { return values; }
        }

        /// <summary>
        /// Gets the reason why the route was not matched.
        /// </summary>
        /// <value>The fail reason.</value>
        public string FailReason
        {
            get { return failReason; }
        }
    }
}


text:
package bank;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Account_implement {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);

		System.out
				.println("Guide of supported actions: Open (O), Quit (Q), Login(L), Deposit $$$ (D), Withdraw $$$ (W), Balance (B), Terminate (T).");
		System.out.println("When finished enter 'T' to terminate!");
		String userAction = null;
		Account account = null; // current account

		Map<Integer, Account> accounts = new HashMap<Integer, Account>(); // all
																			// created
																			// accounts

		while (true) { // run infinite loop unless terminated
			System.out.print("What would you like to do? ");

			userAction = input.nextLine();

			switch (userAction.toLowerCase()) {
			case "o":
			case "open":
				account = new Account();
				accounts.put(account.getAccountNo(), account);
				System.out.println(account.getAccountNo());
				break;
			case "q":
			case "quit":
				if (account != null) {
					account = null;
					System.out.println("Goodbye");
				} else {
					System.out.println("Hello");
				}
				break;
			case "l":
			case "login":
				System.out.print("Enter account number: ");
				int num = input.nextInt();
				input.nextLine(); // clear the input buffer
				if (accounts.containsKey(num)) {
					account = accounts.get(num); // if num is in database
					System.out.println("Hello");
					// (hashmap), then the
					// object is read
				} else {
					System.out.println("Account does not exist");
				}
				break;
			case "d":
			case "deposit":
				if (account != null) {
					System.out.print("How much would like to deposit? ");
					double depositedAmount = input.nextDouble();
					input.nextLine(); // clear the input buffer
					account.Deposit(depositedAmount);
					System.out
							.println("You have deposited $" + depositedAmount);
				} else {
					System.out.println("You are not logged in!");
				}
				break;
			case "w":
			case "withdraw":
				if (account != null) {
					System.out.print("How much would like to withdraw? ");
					double withdrawnAmount = input.nextDouble();
					input.nextLine(); // clear the input buffer
					account.Withdraw(withdrawnAmount);
					System.out
							.println("You have withdrawn $" + withdrawnAmount);
				} else {
					System.out.println("You are not logged in!");
				}
				break;
			case "b":
			case "balance":
				if (account != null) {
					System.out.println(account.getBalance());
				} else {
					System.out.println("You are not logged in!");
				}
				break;
			case "t":
			case "terminated":
				System.out.println("Terminated");
				System.exit(0);
				break;
			default:
				System.out.println("ERROR");
				break;
			}
			userAction = null;
		}
	}
}


text:
<?php

namespace App\Http\Controllers;

use App\Location;
use App\Tweet;
use Illuminate\Http\Request;

class MapController extends Controller
{
    public function index()
    {
        $locations = Location::all();

        return view('map')->with('locations', $locations);
    }

    public function getPlaceInfo(Request $request)
    {
        $place = $request->input('query');

        $response['count'] = Tweet::where(
                function ($query) {
                    $query->where('naive_bayes', 'traffic')
                        ->orWhere('svm', 'traffic')
                        ->orWhere('decision_tree', 'traffic');
                })
            ->where(
                function ($query) use ($place) {
                    $query->where('raw_tweet', 'like', "%$place%")
                        ->orWhere('raw_tweet', 'like', "%$place%");
                })
            ->where('date_time', '>=', date("Y-m-d H:i:s", strtotime("today")))
            ->count();

        $response['recent_tweets'] = Tweet::select(['date_time', 'raw_tweet'])
            ->where(
                function ($query) {
                    $query->where('naive_bayes', 'traffic')
                        ->orWhere('svm', 'traffic')
                        ->orWhere('decision_tree', 'traffic');
                })
            ->where(
                function ($query) use ($place) {
                    $query->where('raw_tweet', 'like', "%$place%")
                        ->orWhere('raw_tweet', 'like', "%$place%");
                })
            ->orderBy('date_time', 'desc')
            ->take(3)
            ->get();

        return response()->json($response);
    }
}


text:
package com.palominolabs.benchpress.example.multidb.value;

import com.palominolabs.benchpress.job.id.Identifiable;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.ThreadSafe;
import org.apache.commons.configuration.Configuration;

/**
 * Used to construct ValueGeneratorFactory instances. A ValueGeneratorFactory contains specific configuration data,
 * whereas ValueGeneratorFactoryFactory is most likely stateless and only exists to encapsulate config parsing logic.
 */
@ThreadSafe
public interface ValueGeneratorFactoryFactory extends Identifiable {

    @Nonnull
    ValueGeneratorFactory getFactory(Configuration c);
}


text:
class NewsStay < ActiveRecord::Base
	mount_uploader :image, PictureUploader
end


text:
<?php

use common\modules\lead\models\LeadSourceInterface;
use common\modules\lead\models\searches\LeadSourceSearch;
use common\widgets\grid\ActionColumn;
use common\widgets\GridView;
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $searchModel LeadSourceSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
/* @var $visibleButtons array */

$this->title = Yii::t('lead', 'Lead Sources');
$this->params['breadcrumbs'][] = ['label' => Yii::t('lead', 'Leads'), 'url' => ['/lead/lead/index']];
$this->params['breadcrumbs'][] = Yii::t('lead', 'Sources');
?>

<?= Html::encode($this->title) ?>

		<?= Html::a(Yii::t('lead', 'Create Lead Source'), ['create'], ['class' => 'btn btn-success']) ?>

	<?php // echo $this->render('_search', ['model' => $searchModel]); ?>

	<?= GridView::widget([
		'id' => 'lead-source-grid',
		'dataProvider' => $dataProvider,
		'filterModel' => $searchModel,
		'columns' => [
			['class' => 'yii\grid\SerialColumn'],

			'id',
			'name',
			[
				'attribute' => 'type_id',
				'value' => 'type.name',
				'filter' => $searchModel::getTypesNames(),
				'label' => Yii::t('lead', 'Type'),
			],
			[
				'attribute' => 'url',
				'format' => 'raw',
				'value' => static function (LeadSourceInterface $leadSource): ?string {
					if (!$leadSource->getURL()) {
						return null;
					}
					return Html::a(Html::encode($leadSource->getURL()), $leadSource->getURL(), [
						'target' => '_blank',
					]);
				},
			],
			'phone:tel',
			[
				'attribute' => 'dialer_phone',
				'visible' => $searchModel->scenario !== $searchModel::SCENARIO_OWNER,
			],
			[
				'attribute' => 'owner_id',
				'value' => 'owner',
				'filter' => $searchModel::getOwnersNames(),
				'label' => Yii::t('lead', 'Owner'),
				'visible' => $searchModel->scenario !== $searchModel::SCENARIO_OWNER,
			],
			'sort_index',
			[
				'class' => ActionColumn::class,
				'visibleButtons' => $visibleButtons,
			],
		],
	]); ?>


text: Mostly proofs of concepts / useful / hacky stuff.


text:
import os
from setuptools import find_packages, setup

with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
    README = readme.read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-disbi',
    version=__import__("disbi").__version__,
    packages=find_packages(),
    include_package_data=True,
    license='MIT License',
    description='A Django app framework for managing and integrating systems biology data.',
    long_description=README,
    url='https://github.com/DISBi/django-disbi',
    download_url='https://github.com/DISBi/django-disbi/archive/0.0.2.tar.gz',
    author='Rüdiger Frederik Busche',
    author_email='ruedigerbusche@web.de',
    install_requires=[
        'django>=1.9,<2',
        'django-import-export==0.5.0',
        'numpy>=1.11.0',
        'matplotlib>=1.5.1,<2',
        'more-itertools',
        'psycopg2-binary',
    ],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Framework :: Django :: 1.9',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


text: NGS read classification using a Spark framework.


text:
package docs

import _ "embed"

//go:embed batchmove.md
var batchMoveDocument string

const BatchMoveType = "batchmove"

func init() {
	addCmdDocumentInfo(BatchMoveType, batchMoveDocument)
}


text:
import {ɵPLATFORM_WORKER_UI_ID as PLATFORM_WORKER_UI_ID} from '@angular/common';
import {ResourceLoader} from '@angular/compiler';
import {COMPILER_OPTIONS, createPlatformFactory, PLATFORM_ID, PlatformRef, StaticProvider} from '@angular/core';
import {ɵplatformCoreDynamic as platformCoreDynamic, ɵResourceLoaderImpl as ResourceLoaderImpl} from '@angular/platform-browser-dynamic';

export {VERSION} from './version';

/**
 * @publicApi
 * @deprecated platform-webworker is deprecated in Angular and will be removed in version 10
 */
export const platformWorkerAppDynamic =
    createPlatformFactory(platformCoreDynamic, 'workerAppDynamic', [
      {
        provide: COMPILER_OPTIONS,
        useValue: {providers: [{provide: ResourceLoader, useClass: ResourceLoaderImpl, deps: []}]},
        multi: true
      },
      {provide: PLATFORM_ID, useValue: PLATFORM_WORKER_UI_ID}
    ]);


text:
<?php
include_once("php_includes/common_frame_a.php");
include_once("php_includes/check_login_status.php");
include_once("php_includes/include_admin_column.php");

?>

 Home

Select Student ID

    <form id="stu-master-form" action="/readyMadeCode/eduSec/index.php?r=student%2Fstu-master%2Fcreate" method="post">
<input type="hidden" name="_csrf" value="NHBnY0dyWktnPD8oLyEJHQxdBCkjNmonZ0hXAHEzKxplIg0GMUEbBQ==">

BATCH

<select class="form-control" id="batch" name="batch" onchange="getstuds();">
<option value="" disabled selected>Choose Batch</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2021">2022</option>
<option value="2021">2023</option>
</select>

#	Student ID	First Name	Last Name

   </form>

<?php

include_once("php_includes/footer.php");

 ?>


text:
class DeveloperUnitAttendance

  attr_accessor :range, :developer, :attendances

  def initialize(developer, range)
    @developer = developer
    @range = range
    @attendances = @developer.attendances.in_range(range)
  end

  def late
    @attendances.late
  end

  def absent
    @attendances.absent
  end

end


text:
struct data
{
	float Humidity;
	float Temperature;
};

#endif


text:
using namespace Shiny;

//------------------------------------------------------------------------------
Allocator::~Allocator() = default;

//------------------------------------------------------------------------------
AllocatorException::AllocatorException(
    std::string message,
    EXCEPTION_CALLSITE_PARAMS)
    : Exception(message, EXCEPTION_INIT_BASE_ARGS) {}

//------------------------------------------------------------------------------
OutOfMemoryException::OutOfMemoryException(EXCEPTION_CALLSITE_PARAMS)
    : AllocatorException(
          "Allocation failed because not enough memory left to allocate",
          EXCEPTION_INIT_BASE_ARGS) {}

//------------------------------------------------------------------------------
OutOfMemoryException::OutOfMemoryException(
    std::string message,
    EXCEPTION_CALLSITE_PARAMS)
    : AllocatorException(message, EXCEPTION_INIT_BASE_ARGS) {}

//------------------------------------------------------------------------------
DoubleFreeException::DoubleFreeException(
    void* userPointer,
    EXCEPTION_CALLSITE_PARAMS)
    : AllocatorException(
          fmt::format("Attempted to free {} more than once", userPointer),
          EXCEPTION_INIT_BASE_ARGS) {}


text:
@foreach($categories as $category)
    <option value="{{ $category->id }}"> {{ $category->category }}</option>
@endforeach


text:
/** Defines utilities used to implement the harness that runs user code. **/
package com.google.cloud.dataflow.sdk.util.common.worker;


text:
package org.apache.lucene.search;

import org.apache.lucene.util.PriorityQueue;

final class HitQueue extends PriorityQueue<ScoreDoc> {

  /**
   * Creates a new instance with size elements. If
   * prePopulate is set to true, the queue will pre-populate itself
   * with sentinel objects and set its {@link #size()} to size. In
   * that case, you should not rely on {@link #size()} to get the number of
   * actual elements that were added to the queue, but keep track yourself.

   * NOTE: in case prePopulate is true, you should pop
   * elements from the queue using the following code example:
   *
   *

   * PriorityQueue<ScoreDoc> pq = new HitQueue(10, true); // pre-populate.
   * ScoreDoc top = pq.top();
   *
   * // Add/Update one element.
   * top.score = 1.0f;
   * top.doc = 0;
   * top = (ScoreDoc) pq.updateTop();
   * int totalHits = 1;
   *
   * // Now pop only the elements that were *truly* inserted.
   * // First, pop all the sentinel elements (there are pq.size() - totalHits).
   * for (int i = pq.size() - totalHits; i > 0; i--) pq.pop();
   *
   * // Now pop the truly added elements.
   * ScoreDoc[] results = new ScoreDoc[totalHits];
   * for (int i = totalHits - 1; i >= 0; i--) {
   *   results[i] = (ScoreDoc) pq.pop();
   * }
   *

   *
   *
NOTE: This class pre-allocate a full array of
   * length size.
   *
   * @param size
   *          the requested size of this queue.
   * @param prePopulate
   *          specifies whether to pre-populate the queue with sentinel values.
   * @see #getSentinelObject()
   */
  HitQueue(int size, boolean prePopulate) {
    super(size, prePopulate);
  }

  @Override
  protected ScoreDoc getSentinelObject() {
    // Always set the doc Id to MAX_VALUE so that it won't be favored by
    // lessThan. This generally should not happen since if score is not NEG_INF,
    // TopScoreDocCollector will always add the object to the queue.
    return new ScoreDoc(Integer.MAX_VALUE, Float.NEGATIVE_INFINITY);
  }

  @Override
  protected final boolean lessThan(ScoreDoc hitA, ScoreDoc hitB) {
    if (hitA.score == hitB.score)
      return hitA.doc > hitB.doc;
    else
      return hitA.score < hitB.score;
  }
}


text:
SYNONYM

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

#### Published in
Enchir. fung. (Paris) 190 (1886)

#### Original name
Hydnum floriforme Schaeff., 1774

### Remarks
null


text:
import {module, test, expect} from '../qunit';
import moment from '../../moment';

module('now');

test('now', function(assert) {
    var startOfTest = new Date().valueOf(),
        momentNowTime = moment.now(),
        afterMomentCreationTime = new Date().valueOf();

    assert.ok(startOfTest <= momentNowTime,
        'moment now() time should be now, not in the past');
    assert.ok(momentNowTime <= afterMomentCreationTime,
        'moment now() time should be now, not in the future');
});

test('now - Date mocked', function(assert) {
    // We need to test mocking the global Date object, so disable 'Read Only' jshint check
    /* jshint -W020 */
    var RealDate = Date,
        customTimeMs = moment('2015-01-01T01:30:00.000Z').valueOf();

    function MockDate() {
        return new RealDate(customTimeMs);
    }

    MockDate.now = function() {
        return new MockDate().valueOf();
    };

    MockDate.prototype = RealDate.prototype;

    Date = MockDate;

    try {
        assert.equal(moment().valueOf(), customTimeMs,
            'moment now() time should use the global Date object');
    } finally {
        Date = RealDate;
    }
});

test('now - custom value', function(assert) {
    var customTimeStr = '2015-01-01T01:30:00.000Z',
        customTime = moment(customTimeStr, moment.ISO_8601).valueOf(),
        oldFn = moment.now;

    moment.now = function() {
        return customTime;
    };

    try {
        assert.equal(moment().toISOString(), customTimeStr,
            'moment() constructor should use the function defined by moment.now, but it did not');
        assert.equal(moment.utc().toISOString(), customTimeStr,
            'moment() constructor should use the function defined by moment.now, but it did not');
    } finally {
        moment.now = oldFn;
    }
});

test('empty object, empty array', function(assert) {
    function assertIsNow(gen, msg) {
        var before = +(new Date()),
            mid = gen(),
            after = +(new Date());
        assert.ok(before <= +mid && +mid <= after, 'should be now : ' + msg);
    }

    assertIsNow(function() {
        return moment();
    }, 'moment()');
    assertIsNow(function() {
        return moment([]);
    }, 'moment([])');
    assertIsNow(function() {
        return moment({});
    }, 'moment({})');
    assertIsNow(function() {
        return moment.utc();
    }, 'moment.utc()');
    assertIsNow(function() {
        return moment.utc([]);
    }, 'moment.utc([])');
    assertIsNow(function() {
        return moment.utc({});
    }, 'moment.utc({})');
});


text:
package map;

import java.awt.geom.Point2D;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import java.util.ArrayList;
import java.util.List;

public class EntityXmlParser {

	private List entityList;
	private MapXmlParser mapData;
	private NodeList mapXmlElements;

	EntityXmlParser(String xmlMapFile){
		entityList = new ArrayList();
		mapData = new MapXmlParser(xmlMapFile);
		mapXmlElements = mapData.getElementList("Entity");
		parseElementListForEntities(mapXmlElements);
	}

	private Entity getEntity(Element entityElement) {

		//for each <employee> element get text or int values of
		//name ,id, age and name
		String templatePath = mapData.getTextValue(entityElement,"Template");
		//int uid = getIntValue(entityElement, "Entity");
		float theta = mapData.getFloatValue(entityElement,"Orientation");
		Point2D.Float position = getPoint2DFloat(entityElement, "Position");

		//Create a new Employee with the value read from the xml nodes
		Entity e = new Entity(0, position.x, position.y, theta, templatePath);

		return e;
	}

	private void parseElementListForEntities(NodeList elementList){
		//get the root elememt
		if(elementList != null && elementList.getLength() > 0) {
			for(int i = 0 ; i < elementList.getLength();i++) {

				//get the employee element
				Element el = (Element)elementList.item(i);

				//get the Employee object
				Entity e = getEntity(el);

				//add it to list
				entityList.add(e);
			}
		}
	}

	private Point2D.Float getPoint2DFloat(Element ele, String tagName) {
		//in production application you would catch the exception
		if(tagName.equals("Position")){

			NodeList nl = ele.getElementsByTagName("Position");

			if(nl != null && nl.getLength() > 0)
			{
				String x, y;
				Element el = (Element)nl.item(0);
				x = el.getAttribute("x");
				y = el.getAttribute("z");

				return new Point2D.Float(Float.parseFloat(x), Float.parseFloat(y));
			}
			else
				return null;
		}
		else
			return null;
	}

	public List getEntityList(){
		return entityList;
	}

}


text:
<?php
	error_reporting(E_ALL);
	if (!empty($_POST['input'])) {
		include 'markdownify_extra.php';
		if (!isset($_POST['leap'])) {
			$leap = MDFY_LINKS_EACH_PARAGRAPH;
		} else {
			$leap = $_POST['leap'];
		}

		if (!isset($_POST['keepHTML'])) {
			$keephtml = !MDFY_KEEPHTML;
		} else {
			$keephtml = $_POST['keepHTML'];
		}
		if (!empty($_POST['extra'])) {
			$md = new Markdownify_Extra($leap, MDFY_BODYWIDTH, $keephtml);
		} else {
			$md = new Markdownify($leap, MDFY_BODYWIDTH, $keephtml);
		}
		if (ini_get('magic_quotes_gpc')) {
			$_POST['input'] = stripslashes($_POST['input']);
		}
		$output = $md->parseString($_POST['input']);
	} else {
		$_POST['input'] = '';
	}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
		<title>HTML to Markdown Converter</title>

		<?php if (empty($_POST['input'])): ?>
		<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
			<fieldset>
				<legend>HTML Input</legend>
				<textarea style="width:100%;" cols="85" rows="40" name="input"><?php echo htmlspecialchars($_POST['input'], ENT_NOQUOTES, 'UTF-8'); ?></textarea>
			</fieldset>
			Markdownify Extra: <input name="extra" checked="checked" id="extra" type="checkbox" value="1"  />
			Links after each block elem: <input name="leap" id="leap" type="checkbox" value="1"  />
			keep HTML: <input name="keepHTML" id="keepHTML" type="checkbox" value="1" checked="checked" />
			<input type="submit" name="submit" value="submit" />
		</form>
		<?php else: ?>

<a href="<?php echo $_SERVER['PHP_SELF']; ?>">BACK

<?php echo htmlspecialchars($output, ENT_NOQUOTES, 'UTF-8'); ?>

		<?php endif; ?>


text:
/**
 * LrProjectAction.java
 *
 * Builds graphs datasets and provides graphs to
 * LrProjectAction/floatingbox.jelly and
 * LrProjectAction/index.jelly
 *
 * @author Yann LE VAN
 *
 */

package hudson.plugins.loadrunner;

import java.io.IOException;
import java.util.ArrayList;

import hudson.model.AbstractBuild;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.ProminentProjectAction;
import hudson.model.AbstractProject;
import hudson.util.ChartUtil;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.graphics2d.svg.*;

import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

import hudson.plugins.loadrunner.results.*;

public class LrProjectAction implements Action, ProminentProjectAction {

/**
    * The owner of this action.
    */
	private final AbstractProject<?, ?> project;
	private AbstractBuild<?,?> owner;
	private final BuildListener listener;
	private final ArrayList<LrRepeatableTransactionConfig> lrTransactsConfList;

	/**
	 *   Constructor
	 */
   public LrProjectAction(AbstractProject<?,?> project, BuildListener listener,  ArrayList<LrRepeatableTransactionConfig> lrTransactsConfList) {
	   this.project = project;
	   this.listener = listener;
	   this.lrTransactsConfList = lrTransactsConfList;

   }

	public String getDisplayName() {
		return PluginImpl.LPA_DISPLAY_NAME;
	}

   public String getIconFileName() {
	      return PluginImpl.LPA_ICON_FILE_NAME;
   }

   public String getUrlName() {
	      return PluginImpl.LPA_URL;
   }

   public String getName() {
	      return PluginImpl.LPA_NAME;
   }

   public boolean isFloatingBoxActive() {
       return true;
   }

   public boolean isGraphActive () {
	   return true;
   }

   public String getGraphName() {
       return getDisplayName();
   }

   public void setOwner(AbstractBuild<?,?> owner) {
	   this.owner = owner;
   }

   /**
    * Getter for property 'project'.
    *
    * @return Value for property 'project'.
    */
   public AbstractProject<?, ?> getProject() {
      return project;
   }

   protected Class<LRAparser> getLRAparserClass() {
	   return LRAparser.class;
	}

   protected Class<LrResultTable> getLrResultTableClass() {
	   return LrResultTable.class;
	}

   /**
    * Generates the graph that shows Response Times Performance Indicators for a given transaction
    * @param req -
    * @param rsp -
    * @throws IOException -
    */
   @SuppressWarnings("deprecation")
   public void doRespTimeGraph(final StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException {

	final String lrTransactName = req.getParameter("lrTransact");
    final JFreeChart respTimeChart = ChartFactory.createLineChart(
    			lrTransactName + " response times (ms)", //req.getParameter("lrTransact"),//lr_transact_list[0],//"geoentity_Global", // charttitle
	            "build", // unused
	            "milliseconds", // range axis label
	            this.buildRespTimeDataset(lrTransactName), //req.getParameter("lrTransact")), // data
		    	PlotOrientation.VERTICAL, // orientation
	            true, // include legend
	            true, // tooltips
	            false // urls
	            );
    Plot plot = respTimeChart.getPlot();

	ChartUtil.generateGraph(req, rsp, respTimeChart ,getGraphWidth(), getGraphHeight());

   }

   /**
    * Generates the graph that shows Response Times Performance Indicators for a given transaction
    * @param req -
    * @param rsp -
    * @throws IOException -
    */
   @SuppressWarnings("deprecation")
   public void doErrorRateGraph(final StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException {

    final String lrTransactName = req.getParameter("lrTransact");
    final JFreeChart errorRateChart = ChartFactory. createBarChart(
    			lrTransactName + " error rate (%)", //req.getParameter("lrTransact"),// // "geoentity_Global", // charttitle
	            "build", // unused
	            "%", // range axis label
	            this.buildErrorRateDataset(lrTransactName), //req.getParameter("lrTransact")), //"geoentity_Global"), // data
		    	PlotOrientation.VERTICAL, // orientation
	            true, // include legend
	            true, // tooltips
	            false // urls
	            );

	ChartUtil.generateGraph(req, rsp, errorRateChart ,getGraphWidth(), getGraphHeight());

   }

   /**
    * Builds the DataSet to graph Resp Time for a given LR transaction
    * @param lrTransact
    * @throws IOException - InterruptedException
    */
   public DefaultCategoryDataset buildRespTimeDataset(String lrTransact) throws IOException, InterruptedException {

	final DefaultCategoryDataset buffer = new DefaultCategoryDataset();
	final DefaultCategoryDataset graphDataset = new DefaultCategoryDataset();
	int idx = 0;

	for (AbstractBuild<?, ?> build = getProject().getLastBuild(); build != null; build = build.getPreviousBuild()) {

		LrResultTable action = build.getAction(LrResultTable.class);
    	if (action != null && /*action.DicExists()*/ action.getStatsDic().get(lrTransact) != null && idx < PluginImpl.LPA_MAX_BUILDS_IN_GRAPHS) {

    		/*
    		 * Builds Dataset with actual response times
    		 */
    		buffer.addValue(action.getStatsDic().get(lrTransact).getStat().get("Average").doubleValue()*1000, "Average", Integer.toString(build.number));
    		buffer.addValue(action.getStatsDic().get(lrTransact).getStat().get("90 Percent").doubleValue()*1000, "90th Percent", Integer.toString(build.number));

    		/*
    		 * Builds Dataset with transaction SLA
    		 */
    		buffer.addValue(getAvgRespTimeSLA(lrTransact)*1000, "Average SLA", Integer.toString(build.number));
    		buffer.addValue(getPctRespTimeSLA(lrTransact)*1000, "90th Percent SLA", Integer.toString(build.number));
    		++idx;
    	}
    	else {
    		//listener.getLogger().println(" ### null Action OR null StatsDic in LrResultTable for build " + build.number);
    	}
     }

	/*
	 * Reverse Dataset Order
	 */
	int i = buffer.getColumnCount() - 1;
    while (i >= 0) {
    	graphDataset.addValue(buffer.getValue(0,i), buffer.getRowKey(0), buffer.getColumnKey(i));
    	graphDataset.addValue(buffer.getValue(1,i), buffer.getRowKey(1), buffer.getColumnKey(i));
    	graphDataset.addValue(buffer.getValue(2,i), buffer.getRowKey(2), buffer.getColumnKey(i));
    	graphDataset.addValue(buffer.getValue(3,i), buffer.getRowKey(3), buffer.getColumnKey(i));
    	i--;
    }

	return graphDataset;

   }

   /**
    * Builds the DataSet to graph Resp Time for a given LR transaction
    * @param lrTransact
    * @throws IOException - InterruptedException
    */
   public DefaultCategoryDataset buildErrorRateDataset(String lrTransact) throws IOException, InterruptedException {

	final DefaultCategoryDataset buffer = new DefaultCategoryDataset();
	final DefaultCategoryDataset errorRateDataset = new DefaultCategoryDataset();
	int idx = 0;

	for (AbstractBuild<?, ?> build = getProject().getLastBuild(); build != null; build = build.getPreviousBuild()) {

		LrResultTable action = build.getAction(LrResultTable.class);
    	if (action != null && /*action.DicExists()*/ action.getStatsDic().get(lrTransact) != null && idx < PluginImpl.LPA_MAX_BUILDS_IN_GRAPHS) {
    		double passTr = action.getStatsDic().get(lrTransact).getStat().get("Pass").doubleValue();
    		double failTr = action.getStatsDic().get(lrTransact).getStat().get("Fail").doubleValue();
    		double stopTr = action.getStatsDic().get(lrTransact).getStat().get("Stop").doubleValue();
    		double errorRate = 100*(failTr + stopTr) / (passTr + failTr + stopTr);
    		buffer.addValue(errorRate, "Error Rate", Integer.toString(build.number));
    		buffer.addValue(getErrorRateSLA(lrTransact), "Error Rate SLA", Integer.toString(build.number));
    		++idx;
    	}
    	else {
    		//listener.getLogger().println(" ### null Action OR null StatsDic in LrResultTable for build " + build.number);
    	}
     }

	/*
	 * Reverse Dataset Order
	 */
	int i = buffer.getColumnCount() - 1;
    while (i >= 0) {
    	errorRateDataset.addValue(buffer.getValue(0,i), buffer.getRowKey(0), buffer.getColumnKey(i));
    	errorRateDataset.addValue(buffer.getValue(1,i), buffer.getRowKey(1), buffer.getColumnKey(i));
    	i--;
    }

	return errorRateDataset;

   }

   /**
    * Getter for property 'graphWidth'.
    *
    * @return Value for property 'graphWidth'.
    */
   public int getGraphWidth() {
      return 600;
   }

   /**
    * Getter for property 'graphHeight'.
    *
    * @return Value for property 'graphHeight'.
    */
   public int getGraphHeight() {
      return 400;
   }

   public ArrayList<String> getLrTransactList() {

	   ArrayList<String> lr_transact_list = new ArrayList<String>();

	   for(LrRepeatableTransactionConfig lrTransactConfig : lrTransactsConfList) {
		   if (lrTransactConfig.getLrTransactName() != null) {
			lr_transact_list.add(lrTransactConfig.getLrTransactName());
		   }
		   else
		   {
			   // DO NOTHING
		   }
	   }
	   return lr_transact_list;

   }

   public String getMainLrTransactName() {
	   for(LrRepeatableTransactionConfig lrTransactConfig : lrTransactsConfList) {
		   if (lrTransactConfig.isMainTransact()) {
			   return lrTransactConfig.getLrTransactName();
		   }
		   else
		   {
			   // DO NOTHING
		   }

	   }
	   return null;
   }

   public float getAvgRespTimeSLA(String lrTransact) {

	   for(LrRepeatableTransactionConfig lrTransactConfig : lrTransactsConfList) {
		   if (lrTransactConfig.getLrTransactName().equals(lrTransact)) {
			   return lrTransactConfig.getAvgRespTimeSLA();
		   }
		   else
		   {
			   // DO NOTHING
		   }
	   }
	   return Float.NaN;
   }

   public float getPctRespTimeSLA(String lrTransact) {

	   for(LrRepeatableTransactionConfig lrTransactConfig : lrTransactsConfList) {
		   if (lrTransactConfig.getLrTransactName().equals(lrTransact)) {
			   return lrTransactConfig.getPctRespTimeSLA();
		   }
		   else
		   {
			   // DO NOTHING
		   }
	   }
	   return Float.NaN;
   }

   public float getErrorRateSLA(String lrTransact) {

	   for(LrRepeatableTransactionConfig lrTransactConfig : lrTransactsConfList) {
		   if (lrTransactConfig.getLrTransactName().equals(lrTransact)) {
			   return lrTransactConfig.getErrorRateSLA();
		   }
		   else
		   {
			   // DO NOTHING
		   }
	   }
	   return Float.NaN;
   }
}